在WHERE子句中使用可选参数

时间:2012-05-30 10:57:15

标签: sql-server tsql stored-procedures

我有一个SP

ALTER PROCEDURE dbo.sp_Compare
    @lst varchar(100),
    @frst varchar(100) = NULL,
    @passportNo varchar(50) = NULL
AS
SELECT * FROM dbo.User
WHERE LastName like '%' + @lst + '%'
    AND (
         FirstName like @frst + ' %'
         OR FirstName like '% ' + @frst + ' %'
         OR FirstName like '% ' + @frst
         OR FirstName = @frst
        )
    OR Passport = @passportNo;

有时候@frs@passportNo或两者都可能无法使用

所以我想更改上面的查询,以便在未传递可选参数时(即,当其值为null时)不应考虑该参数在该特定列上进行过滤

即,如果@frst为NULL,则不应基于FirstName过滤结果,它应该像WHERE子句中没有FirstName like '%' + @frst + '%'条件一样工作。

如何在不针对不同情况重复编写相同逻辑的情况下编写查询?

1 个答案:

答案 0 :(得分:8)

WHERE (@frst IS NULL OR 
    (
         LastName like '%' + @lst + '%'
         AND (
             FirstName like @frst + ' %'
             OR FirstName like '% ' + @frst + ' %'
             OR FirstName like '% ' + @frst
             OR FirstName = @frst
        )
    )
 )
 AND (@passportNo IS NULL OR
        Passport = @passportNo);

修改:实际上这应该更有效:

WHERE ( @frst IS NULL OR FirstName like '%' + @frst + '%' )
AND   ( @lst  IS NULL OR LastName  like '%' + @lst  + '%' )
AND   ( @passportNo IS NULL OR Passport = @passportNo )