我对SQL Server不太满意,但我对学习它非常感兴趣。我在下面写了一个查询,通过使用COALESCE获得结果。我试图尽可能地优化查询。我们除了COALESCE之外还有什么好处可以帮助提高性能吗?
SELECT
DISTINCT Account.AcctID,
Account.AcctNum,
Account.Joint,
Applicant.PartyID,
AcctType.AcctTypeID,
AcctType.AcctCatID,
AcctType.AcctTypeNum,
AcctType.AcctTypeName,
AcctType.isHSA
FROM
Account WITH (NOLOCK)
INNER JOIN AcctType WITH (NOLOCK) ON Account.AcctTypeID = AcctType.AcctTypeID
INNER JOIN luAcctCat WITH (NOLOCK) ON AcctType.AcctCatID = luAcctCat.AcctCatID
INNER JOIN APPLICANTACCOUNT WITH (NOLOCK) ON Account.AcctID = APPLICANTACCOUNT.AcctID
WHERE Account.AcctID = @AcctID AND APPLICANTACCOUNT.ApplID = COALESCE(@applId, APPLICANTACCOUNT.ApplID)
答案 0 :(得分:0)
您的逻辑是“在appid上匹配,如果已指定”,但您已经以某种方式对其进行编码,这意味着将在该帐户的每一行上调用COALESCE。如果每个帐户的行数很小,那么无关紧要。但如果大,你可以试试这个:
WHERE Account.AcctID = @AcctID
AND (@applId is null OR APPLICANTACCOUNT.ApplID = @applId)
答案 1 :(得分:0)
您还应该查看案例中的OPTIMIZE FOR UNKNOWN
查询提示。
MSDN链接:http://technet.microsoft.com/en-us/library/ms181714.aspx