SQL Server中CASE语句中的IN条件

时间:2018-08-28 02:24:10

标签: sql-server postgresql

我有一个查询要从Postgres(10.1)迁移到Microsoft SQL Server(13.0)

在Postgres中运行的查询位于:

SELECT * 
FROM source
WHERE
    1 = CASE 
           WHEN 234 NOT IN (SELECT user_id
                            FROM usergroup)
              THEN SOURCE .source_id IN (SELECT DISTINCT sl.source_id
                                         FROM sourcelevel SL)
              ELSE 1
        END

SQL Server失败,并显示以下错误消息:

  

第15层状态1的第11行的消息156   关键字“ IN”附近的语法不正确。

此问题似乎源于IN中使用CASE/WHEN/ELSE/END条件,因为如果我在进行查询时删除了该构造:

SELECT * 
FROM source
WHERE
    SOURCE .source_id IN (SELECT DISTINCT sl.source_id
                          FROM sourcelevel SL)

它执行没有错误。

在SQL Server的IN语句中使用CASE语法有技巧吗?

3 个答案:

答案 0 :(得分:2)

SQL Server没有HAVING COUNT(col) = 7 数据类型。您可以改为重构为嵌套的CASE表达式,如下所示,返回0或1:

Boolean

我认为也可以在没有SELECT * from source WHERE 1 = CASE WHEN 234 NOT IN( SELECT user_id FROM usergroup ) THEN CASE WHEN SOURCE.source_id IN( SELECT DISTINCT sl.source_id FROM sourcelevel SL ) THEN 1 ELSE 0 END ELSE 1 END; 的情况下进行重构,例如:

CASE

答案 1 :(得分:0)

错误不在C:\Users\windows> python Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. Failed calling sys.__interactivehook__ Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site.py", line 410, in register_readline readline.read_history_file(history) File "C:\ProgramData\Anaconda3\lib\site-packages\pyreadline\rlmain.py", line 165, in read_history_file self.mode._history.read_history_file(filename) File "C:\ProgramData\Anaconda3\lib\site-packages\pyreadline\lineeditor\history.py", line 82, in read_history_file for line in open(filename, 'r'): File "C:\ProgramData\Anaconda3\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 991: character maps to <undefined> 部分中,而是在此地方

NOT IN

我不了解PostgreSQL,但是SQL Server绝对不支持这种情况:

THEN SOURCE .source_id IN (SELECT DISTINCT sl.source_id
                           FROM sourcelevel SL)

仔细分析您的查询。

WHERE 1 = SOURCE.source_id IN (SELECT..

如果用户ID不属于用户组,则查询似乎只是限制了查询结果。

SELECT * FROM source WHERE 1 = (CASE WHEN 234 NOT IN(SELECT user_id FROM usergroup) THEN SOURCE.source_id IN (SELECT DISTINCT sl.source_id FROM sourcelevel AS SL) ELSE 1 END) 替换CASE(因为IF不能用作查询的外部部分)

CASE

答案 2 :(得分:0)

我很确定这可以解决这个问题-@u是您的用户ID参数:

SELECT * FROM source
WHERE exists(select * from usergroup where user_id=@u)
or exists(select * from sourcelevel sl where sl.source_id=source.Sourceid)