T-SQL Case Where语句

时间:2016-06-02 21:26:46

标签: sql-server tsql stored-procedures

我有一个允许用户在UI中选择一些选项的查询。他们可以选择由特定用户搜索,也可以查看所有数据,无论用户是谁。

我当前的WHERE子句如下所示:

WHERE e.mgrQID IN (SELECT QID FROM @temp)
  AND i.isRetired = 0
  AND ym.year IS NOT NULL
  AND ym.month IS NOT NULL

现在,当用户搜索时,这是正常的,这是我最初的方式。我试图添加一个绕过用户块的选项。

这是sudo逻辑:

CASE 
   WHEN @viewType = 'leader' 
      THEN e.mgrQID IN (SELECT QID FROM @temp) 
   ELSE WHEN @viewType = 'all' 
       DONT INCLUDE THIS USER PART 
END

简而言之,我试图在CASE语句中包装WHERE子句的第一行,并且仅当传递的名为@viewType的变量等于leader时才运行它

3 个答案:

答案 0 :(得分:1)

只是做一些预处理,如果你想要它们的领导者,把它们放在临时表中,如果它不是领导者,那么把每个人都放在临时表中

DECLARE @viewType VARCHAR(100)
SET @viewType = 'leader'

DECLARE @tblIdsIWant TABLE
(
    QID INT
)
IF (@viewType = 'leader')
BEGIN
    INSERT INTO @tblIdsIWant
        SELECT QID FROM @temp  --get leaders only
END
ELSE  --@viewType = 'leader'
BEGIN  
    INSERT INTO @tblIdsIWant
        SELECT QID FROM dbo.yourTable  --get everything, including leaders
END

SELECT * FROM dbo.yourOtherTable 
WHERE e.mgrQID IN (SELECT QID from @tblIdsIWant)

答案 1 :(得分:0)

那是OR不是吗?

WHERE (@viewType = 'all' or exists (SELECT 1 FROM @temp t where t.QID = e.mgrQID))
  AND i.isRetired = 0
  AND ym.year IS NOT NULL
  AND ym.month IS NOT NULL

答案 2 :(得分:0)

也许我已将其简化为多,但我会将查询分开

声明@viewType VARCHAR(100)

            set @viewType = 'leader'



            if @viewType = 'leader'

            begin

            SELECT 

            *
 FROM    TableName

             WHERE e.mgrQID IN (SELECT QID FROM @temp)
                                            AND i.isRetired = 0
                                            AND ym.year IS NOT NULL
                                            AND ym.month IS NOT NULL

  else

                            if @viewType = 'All'
                            begin

                            Select *

                            from Tablename
                            WHERE
                                            i.isRetired = 0
                                            AND ym.year IS NOT NULL
                                            AND ym.month IS NOT NULL

                            end