把一串ID组成的字符串当作参数传成存储过程获取数据。很多时候我们希望把这个字符串转成集合以方便用于in操作。 有两种方式可以方便地把这个以某种符号分隔的ID字符串转成临时表。方式一:通过charindex和substring。

  

1 create function func_splitstring
2 (@str nvarchar(max),@split varchar(10))
3  returns @t Table (c1 varchar(100))
4 as
5 begin
6 declare @i int
7 declare @s int
8 set @i=1
9 set @s=1
10 while(@i>0)
11 begin
12 set @i=charindex(@split,@str,@s)
13 if(@i>0)
14 begin
15 insert @t(c1) values(substring(@str,@s,@i-@s))
16 end
17 else begin
18 insert @t(c1) values(substring(@str,@s,len(@str)-@s+1))
19 end
20 set @s = @i + 1
21 end
22 return
23 end

 

执行:select * from dbo.func_splitstring(‘1,2,3,4,5,6′, ‘,’)
方式二:通过XQuery(需要SQL 2005以上版本)。

1 create function func_splitid
2 (@str varchar(max),@split varchar(10))
3 RETURNS @t Table (c1 int)
4 AS
5 BEGIN
6 DECLARE @x XML
7 SET @x = CONVERT(XML,'')
8 INSERT INTO @t SELECT x.item.value('@id[1]', 'INT') FROM @x.nodes('//items/item') AS x(item)
9 RETURN
10 END

执行:select * from dbo.func_splitid(‘1,2,3,4,5,6′, ‘,’)

相关文章:

  • 2021-08-02
  • 2021-07-17
  • 2022-02-16
  • 2022-12-23
  • 2022-02-16
  • 2022-12-23
  • 2022-12-23
  • 2021-07-10
猜你喜欢
  • 2021-11-06
  • 2021-09-09
  • 2022-12-23
  • 2022-01-26
相关资源
相似解决方案