SQLServer根据逗号分割字符串给in条件查询
场景:碰到使用存储过程传入'1,2,3'给查询语句的in无效,后面想着类似将字符串转数组,最后发现用函数转成表查询数组使用
--将字符串根据逗号分割成数组表用于in,例如字符串’1,2,3,4,5’ ALTER Function [dbo].[StrToTable](@str varchar(8000)) Returns @tableName Table ( str2table varchar(8000) ) As Begin set @str = @str+ ',' Declare @insertStr varchar(8000) --截取后的第一个字符串 Declare @newstr varchar(8000) --截取第一个字符串后剩余的字符串 set @insertStr = left(@str,charindex(',',@str)-1) set @newstr = stuff(@str,1,charindex(',',@str),'') Insert @tableName Values(TRIM(REPLACE(@insertStr,'?',' '))) while(len(@newstr)>0) begin set @insertStr = left(@newstr,charindex(',',@newstr)-1) Insert @tableName Values(TRIM(REPLACE(@insertStr,'?',' '))) set @newstr = stuff(@newstr,1,charindex(',',@newstr),'') end Return END
使用:
例:
WHERE b.FS IN ( SELECT str2table FROM StrToTable(@参数))
参阅;https://www.cnblogs.com/ChineseMoonGod/p/7308783.html