其中以逗号分隔的字符串 [英] Where IN a Comma delimited string

查看:100
本文介绍了其中以逗号分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从临时表#temptable的完整列表中检索某些用户。
查询看起来像这样:

I would like to retrieve certain users from a full list of a temp table #temptable. The query looks like this:

DECLARE @List varchar(max)
SELECT @List = coalesce(@List + ',','') + '''' + StaffCode + ''''
FROM tblStaffs

SELECT UserName
FROM #temptable
WHERE #temptable.StaffCode IN (@List)

我可以告诉@List格式正确:

I can tell @List is in a right format:

'AAA','ABB','BBB','CCC','DDD','MMM'

如果我将其更改为

WHERE #temptable.StaffCode IN ('AAA','ABB','BBB','CCC','DDD','MMM')

它当然可以工作,那为什么不输入(@List)?

It certainly works, then why not IN (@List)?

推荐答案

创建一些拆分字符串函数并将逗号分隔的值转换为行,然后可以使用转换后的行 IN 子句

Create some split string function and convert the comma separated values to rows then you can use the converted rows IN clause

DECLARE @List VARCHAR(max)

SELECT @List = COALESCE(@List + ',', '') +StaffCode
FROM   tblStaffs

SELECT UserName
FROM   #temptable
WHERE  #temptable.StaffCode IN (SELECT split_values
                                FROM   dbo.Splitstring_function(@list)) 

此处 用于各种拆分字符串函数

Check here for various Split String function

如果您不想创建函数,则也可以直接使用代码代替创建新函数( M.Ali的答案)。

If you dont want to create functions then you can also directly use the code instead of creating a new function(M.Ali's answer).

另一种方法是使用动态查询

Declare @List varchar(max), @sql nvarchar(max)

Select @List = coalesce(@List + ',','') + '''' + StaffCode + ''''
From tblStaffs

set @sql = '
Select UserName
From #temptable
Where #temptable.StaffCode IN ('+ @List + ')'

--print @sql
exec (@sql)

要始终调试动态查询,请始终 print 执行前动态SQL。

To debug the dynamic query always print the dynamic sql before executing.

这篇关于其中以逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆