逗号分隔的字符串转成表格参与IN条件查询

返回值为'1,2,3,4,5,6,7',是一个字符串,如果要用IN 查询的话sql认为这是一个完整的字符串,需要将内容分隔转换变成table

定义函数如下:

create Function sysfStrToTable(@str varchar(1000)) 
Returns @tableName Table 
( 
str2table varchar(50) 
) 
As 
--该函数用于把一个用逗号分隔的多个数据字符串变成一个表的一列,例如字符串'1,2,3,4,5' 将变成一个表
Begin 
set @str = @str+',' 
Declare @insertStr varchar(50) --截取后的第一个字符串 
Declare @newstr varchar(1000)--截取第一个字符串后剩余的字符串 
set @insertStr = left(@str,charindex(',',@str)-1) 
set @newstr = stuff(@str,1,charindex(',',@str),'') 
Insert @tableName Values(@insertStr) 
while(len(@newstr)>0) 
begin 
set @insertStr = left(@newstr,charindex(',',@newstr)-1) 
Insert @tableName Values(@insertStr) 
set @newstr = stuff(@newstr,1,charindex(',',@newstr),'') 
end 
Return 
End

  

 调用:

declare @str as varchar(100)
set @str='1,2,3,4,6'

select * from table1
where 
ID IN (SELECT * FROM  dbo.sysfStrToTable(@str) )

  

猜你喜欢

转载自www.cnblogs.com/crrc/p/11280490.html