Sql 为什么IN运算符不处理子查询返回的结果?

Sql 为什么IN运算符不处理子查询返回的结果?,sql,sql-server,sql-server-2008,tsql,subquery,Sql,Sql Server,Sql Server 2008,Tsql,Subquery,为什么操作员不工作,即不返回任何内容 Select * from complaints where Code IN (select distinct stuff(( select ',' + QUOTENAME(cs.Code,'''') from MC_Complaints.dbo.Complaints cs where cs.OverDue= 1 order by cs.Code asc for xml p

为什么操作员不工作,即不返回任何内容

Select * from complaints where Code 
IN 
(select
   distinct  
    stuff((
        select ',' + QUOTENAME(cs.Code,'''')
        from MC_Complaints.dbo.Complaints cs where cs.OverDue= 1
        order by cs.Code asc
        for xml path('')
    ),1,1,'') as codeslist
from MC_Complaints.dbo.Complaints cs)
这个问题

select
   distinct  
    stuff((
        select ',' + QUOTENAME(cs.Code,'''')
        from MC_Complaints.dbo.Complaints cs where cs.OverDue= 1
        order by cs.Code asc
        for xml path('')
    ),1,1,'') as codeslist
from MC_Complaints.dbo.Complaints cs
返回

'LG/17/05/0','LG/17/05/2','LG/17/05/3','Local Council Board/17/05/1','Local Council Board/17/05/10','Local Council Board/17/05/11'
但是IN没有选择任何记录,但是当我把这些代码放在操作符中时,例如

Select * from complaints where Code in 
(
    'LG/17/05/0','LG/17/05/2','LG/17/05/3','Local Council Board/17/05/1','Local Council Board/17/05/10','Local Council Board/17/05/11'
)
然后它出人意料地工作,但不是在返回子查询时。为什么?

填充的结果是一个字符串。字符串恰好包含逗号并不意味着它是一个值列表。字符串“A,B,C”与列表“A”,“B”,“C”完全不同

好消息是,这可以大大简化您的逻辑:

Select c.*
from complaints c
where c.code in (select cs.Code
                 from MC_Complaints.dbo.Complaints cs
                 where cs.OverDue = 1
                );
还有两点。首先,in表达式后面是列别名代码列表。这是不允许的语法

第二,相关的比较是:

where cCode in (
    '''LG/17/05/0'',''LG/17/05/2'',''LG/17/05/3'',''Local Council Board/17/05/1'',''Local Council Board/17/05/10'',''Local Council Board/17/05/11'''
      )

这是一个具有单个字符串值的in列表。

包含引号字符和逗号的字符串不同于由逗号分隔的多个字符串。与大多数其他编程语言一样,T-SQL也是如此。为什么要进行DISTINCT并将其转换为该字符串-IN支持直接使用子查询。看起来您的整个查询可能只是从投诉中选择*,其中代码从MC_complaints.dbo.complaints中选择代码,其中cs.supernate=1。您能否在in子句中使用双引号而不是单引号来分享原因?@AnkitBajpai。我想指出的是,这个值不是一个字符串,但我认为可以重写为“LG/17/05/0”、“LG/17/05/2”、“LG/17/05/3”、“地方议会委员会/17/05/1”、“地方议会委员会/17/05/10”、“地方议会委员会/17/05/11”中的cCode,这与您的建议相同。