[英]How to convert comma separated variable values to row in SQL Server 2012?
I have a variable in my stored procedure `@param varchar', the parameter value will be like '333,445,443,222' or '555'我的存储过程中有一个变量“@param varchar”,参数值类似于“333,445,443,222”或“555”
I need to store into as row in the #Employee
table, Code
column.我需要在
#Employee
表的Code
列中存储为行。
Expected output:预期 output:
#Employee
temp table: #Employee
临时表:
Code
----
333
445
443
222
It will work with any SQL server version.它适用于任何 SQL 服务器版本。 User define table function
用户定义表 function
CREATE FUNCTION dbo.SplitString
(
@Value nvarchar(max),
@Delim nvarchar(5)
)
RETURNS TABLE
AS
RETURN ( SELECT [Value] FROM
(
SELECT [Value] = LTRIM(RTRIM(SUBSTRING(@Value, [Number],
CHARINDEX(@Delim, @Value + @Delim, [Number]) - [Number])))
FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
FROM sys.all_columns) AS x WHERE Number <= LEN(@Value)
AND SUBSTRING(@Delim + @Value, [Number], DATALENGTH(@Delim)/2) = @Delim
) AS y
);
and then it can be used然后就可以使用了
DECLARE @param varchar(1000)
SET @param = '333,445,443,222'
SELECT value AS Code FROM dbo.SplitString(@param, ',');
Demo: http://sqlfiddle.com/#!18/9eecb/89486演示: http://sqlfiddle.com/#!18/9eecb/89486
Since SQL Server 2016, there has been a built-in function to do this:自 SQL Server 2016 以来,已经有一个内置的 function 可以做到这一点:
select s.value
from string_split(@param, ',') s
I would recommend using it.我会推荐使用它。 The one downside to
string_split()
is that it does not provide ordering in the string. string_split()
的一个缺点是它不提供字符串排序。 If ordering is important and there are no duplicates, then charindex()
can be used.如果排序很重要并且没有重复,则可以使用
charindex()
。 If there can be duplicates, then I recommend a recursive CTE.如果可能有重复,那么我建议使用递归 CTE。
Your problem can be solved with recursive CTE (need to know about maxrecursion
):您的问题可以通过递归 CTE解决(需要了解
maxrecursion
):
create function my_split(@s nvarchar(max), @d nvarchar(1))
returns table return
with
r as (
select
iif(p > 0, left(@s, p - 1), @s) as s,
iif(p > 0, right(@s, len(@s) - p), '') as r
from (select charindex(@d, @s)) as a(p)
union all
select
iif(p > 0, left(r, p - 1), r),
iif(p > 0, right(r, len(r) - p), '')
from r
cross apply (select charindex(@d, r)) as a(p)
where r != ''
)
select s from r;
Output: Output:
+----+-----------------+------+
| | param | code |
+----+-----------------+------+
| 1 | 333,445,443,222 | 333 |
| 2 | 333,445,443,222 | 445 |
| 3 | 333,445,443,222 | 443 |
| 4 | 333,445,443,222 | 222 |
| 5 | 555 | 555 |
+----+-----------------+------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.