SQL Where子句在传递值时使用

时间:2017-04-17 14:44:31

标签: sql sql-server tsql sql-server-2014

我有以下情况。

  

如果将值传递给@UserId参数,我需要对其进行过滤   用户记录。

     

如果没有传递值,那么我需要带上所有记录。

列RecipientId为非空

但是,即使我传递了值,查询总是会返回所有记录。

DECLARE @UserId INT

SET @UserId = 47

SELECT *
FROM Message MR
WHERE MR.CompanyId = 1
    AND (
        MR.RecipientId IS NOT NULL
        OR MR.RecipientId = @UserId
        )

3 个答案:

答案 0 :(得分:5)

只需在变量上使用布尔表达式

declare @UserId  int = null

SELECT *
FROM Message MR
WHERE MR.CompanyId = 1 and (MR.RecipientID = @UserId or @UserId IS NULL)

答案 1 :(得分:0)

我相信您可以使用更简单的表单,因为您提供了ID

DECLARE @UserId INT

SET @UserId = 47

SELECT *
FROM Message MR
WHERE MR.CompanyId = 1
    AND  MR.RecipientId = @UserId

如果没有提供身份证

SELECT *
FROM Message MR
WHERE MR.CompanyId = 1
    AND (
        @UserId IS NULL
        OR MR.RecipientId = @UserId  -- OR get this one, redundant
        )

为什么:

SELECT *
FROM Message MR
WHERE MR.CompanyId = 1
    AND (
        MR.RecipientId IS NOT NULL -- get All NOT NULL *(basically all)
        OR MR.RecipientId = @UserId  -- OR get this one, redundant
        )

答案 2 :(得分:0)

还有一个替代方案,可能效率不高,看看:

DECLARE @UserId INT

SET @UserId = 47

SELECT *
FROM Message MR
WHERE MR.CompanyId = 1
    AND MR.RecipientId = (
        CASE 
            WHEN @UserId IS NULL
                THEN MR.RecipientId
            ELSE @UserId
            END
        )