SQL Server 中将某个字符分割的一个字符串,转换为一个表的一列
比如“1,2,3,4,5”这样的字符串转换为一个临时表,这个表有一列5行,每一行存一个数字
函数可以这样写:
create Function StrToTable(@str varchar(1000))
Returns @tableName Table
(
str2table varchar(50)
)
As
–-该函数用于把一个用逗号分隔的多个数据字符串变成一个表的一列
--例如字符串’1,2,3,4,5’ 将编程一个表,这个表有一列5行
Begin
set @str = @str+’,’
Declare @insertStr varchar(50) –截取后的第一个字符串
Declare @newstr varchar(1000) –截取第一个字符串后剩余的字符串
--set @insertStr = left(@str,charindex(',',@str)-1)
--set @insertStr = substring(@str,1,charindex(',',@str)-1)
set @insertStr = substring(@str,1,case
when charindex(',',@str)-1 > 0 then charindex(',',@str)-1
else 0 end)
set @newstr = stuff(@str,1,charindex(‘,’,@str),”)
Insert @tableName Values(@insertStr)
while(len(@newstr)>0)
begin
--set @insertStr = left(@newstr,charindex(',',@newstr)-1)
--set @insertStr = substring(@newstr,1,charindex(',',@newstr)-1)
set @insertStr = substring(@newstr,1,case
when charindex(',',@newstr)-1 > 0 then charindex(',',@newstr)-1
else 0 end)
Insert @tableName Values(@insertStr)
set @newstr = stuff(@newstr,1,charindex(‘,’,@newstr),”)
end
Return
End
然后sql语句可以这样写:
declare str varchar(1000) set str='1,2,3' select * from tablename where id in (select ID from StrToTable(@str) )
注意两处:
set @insertStr = left(@str,charindex(',',@str)-1)
set @insertStr = left(@newstr,charindex(',',@newstr)-1)
这两处如果这样写如果字段中没有逗号,Left()函数和Substring()函数就会出错!
改成这样解决:
set @insertStr = substring(@str,1,case
when charindex(',',@str)-1 > 0 then charindex(',',@str)-1
else 0 end)
set @insertStr = substring(@newstr,1,case
when charindex(',',@newstr)-1 > 0 then charindex(',',@newstr)-1
else 0 end)
最后
LEFT()和SUBSTRING()函数都可截取某个字符前的数字

浙公网安备 33010602011771号