In子句中多个整数行分隔成逗号

时间:2019-01-22 18:04:14

标签: sql tsql ssms

我能够将借位ID的值作为整数行放入逗号分隔列表中。但是,我无法将该列表转换为用于条款中

Declare @LoanNums AS NVARCHAR(Max) = ''
select
   DISTINCT
   @LoanNums =  
    stuff((
        select ',' + CONVERT(NVARCHAR(max), u.LoanId)
        from #tmpLoan u
        where u.LoanId = u.LoanId
        order by u.LoanId
        for xml path('')
    ),1,1,'')
from #tmpLoan

这现在输出132254986,132255002,132255018,249736374,249892143,但是当我将此变量放入IN子句中时看起来不错

DECLARE @SQL AS NVARCHAR(MAX) = ''
SELECT @SQL = 'Select * from myOtherTable Where LoanId in (''' + @LoanNums + ''')'

如果输出此SQL

Select * from myOtherTable WHERE LoanId in
 ('132254986,132255002,132255018,249736374,249892143')

我得到了错误

Conversion failed when converting the varchar value  
'132254986,132255002,132255018,249736374,249892143' to data type int

如何创建正确格式的逗号分隔列表以在IN子句中正确使用?

1 个答案:

答案 0 :(得分:1)

不需要Select * from myOtherTable WHERE LoanId in ('132254986,132255002,132255018,249736374,249892143')

Select * from myOtherTable WHERE LoanId in
  ('132254986','132255002','132255018','249736374','249892143');
             ^ ^         ^ ^         ^ ^         ^ ^