SQL 逗号分隔值的拆分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5487961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Splitting of comma separated values
提问by Shahsra
I have some columns with comma-separated values. For example
我有一些带有逗号分隔值的列。例如
A
一种
as,ad,af,ag
My manager wants the output looks like this:
我的经理希望输出如下所示:
A
一种
as
ad
af
ag
All these should come under one row. I guess we need to use something line break.
所有这些都应该在一行之下。我想我们需要使用换行符。
Hi can we use replace with char(13)+char(10) something. This one also works...
嗨,我们可以用 char(13)+char(10) 替换吗?这个也有效...
Thanks, Shashra
谢谢,莎莎拉
回答by DCNYAM
You can create a user defined UDF like the one shown below. Then, just pass in the comma separated list from another query and it will return a table with each value in a separate row.
您可以创建一个用户定义的 UDF,如下所示。然后,只需从另一个查询中传入逗号分隔的列表,它将返回一个表,其中每个值都位于单独的行中。
CREATE FUNCTION [dbo].[fnSplitStringAsTable]
(
@inputString varchar(MAX),
@delimiter char(1) = ','
)
RETURNS
@Result TABLE
(
Value varchar(MAX)
)
AS
BEGIN
DECLARE @chIndex int
DECLARE @item varchar(100)
-- While there are more delimiters...
WHILE CHARINDEX(@delimiter, @inputString, 0) <> 0
BEGIN
-- Get the index of the first delimiter.
SET @chIndex = CHARINDEX(@delimiter, @inputString, 0)
-- Get all of the characters prior to the delimiter and insert the string into the table.
SELECT @item = SUBSTRING(@inputString, 1, @chIndex - 1)
IF LEN(@item) > 0
BEGIN
INSERT INTO @Result(Value)
VALUES (@item)
END
-- Get the remainder of the string.
SELECT @inputString = SUBSTRING(@inputString, @chIndex + 1, LEN(@inputString))
END
-- If there are still characters remaining in the string, insert them into the table.
IF LEN(@inputString) > 0
BEGIN
INSERT INTO @Result(Value)
VALUES (@inputString)
END
RETURN
END
回答by bvr
Check this without using User Defined Function
在不使用用户定义函数的情况下检查此项
DECLARE @param VARCHAR(MAX)
SET @param = 'as,ad,af,ag'
SELECT Split.a.value('.', 'VARCHAR(100)') AS ColName
FROM
(
SELECT CONVERT(XML, '<M>' + REPLACE(ColName, ',', '</M><M>') + '</M>') AS ColName
FROM (SELECT @param AS ColName) TableName
) AS A CROSS APPLY ColName.nodes ('/M') AS Split(a)