我正在编写一个游标来从主表中填充新表中的数据,该表包含以下方式的数据
项目颜色
衬衫红色,蓝色,绿色,黄色
我想通过提取项目然后根据其包含的每种颜色将其添加到行中来填充新的表格数据
项目颜色
衬衫红色
衬衫蓝
衬衫绿色
衬衫黄色
我被困在如何
1)Delimate / Split“Colors”字符串 2)将其保存在数组中 3)在光标中使用它
因为我将使用嵌套游标来实现此目的。
答案 0 :(得分:5)
使用Sql Server 2005+和XML数据类型,您可以查看以下内容
DECLARE @Table TABLE(
Item VARCHAR(250),
Colors VARCHAR(250)
)
INSERT INTO @Table SELECT 'Shirt','Red,Blue,Green,Yellow'
INSERT INTO @Table SELECT 'Pants','Black,White'
;WITH Vals AS (
SELECT Item,
CAST('<d>' + REPLACE(Colors, ',', '</d><d>') + '</d>' AS XML) XmlColumn
FROM @Table
)
SELECT Vals.Item,
C.value('.','varchar(max)') ColumnValue
FROM Vals
CROSS APPLY Vals.XmlColumn.nodes('/d') AS T(C)
答案 1 :(得分:3)
文章Faking Arrays in Transact SQL详述了解决此问题的几种技术,从使用PARSENAME()函数(限制为5项)到编写CLR函数。
XML答案是可以针对特定场景选择的详细技术之一。
结合一些提示,我解决了我的字符串拆分问题:
SET NOCOUNT ON;
DECLARE @p NVARCHAR(1000), @len INT;
SET @p = N'value 1,value 2,value 3,value 4,etc';
SET @p = ',' + @p + ',';
SET @len = LEN(@p);
-- Remove this table variable creation if you have a permanent enumeration table
DECLARE @nums TABLE (n int);
INSERT INTO @nums (n)
SELECT A.n FROM
(SELECT TOP 1000 ROW_NUMBER() OVER (ORDER BY TableKey) as n FROM dbo.Table) A
WHERE A.n BETWEEN 1 AND @len;
SELECT SUBSTRING(@p , n + 1, CHARINDEX( ',', @p, n + 1 ) - n - 1 ) AS "value"
FROM @nums
WHERE SUBSTRING( @p, n, 1 ) = ',' AND n < @len;
请注意,考虑到1000个字符串长度限制,您必须拥有一个包含1000行或更多行的表(样本tsql上的dbo.Table)以创建此示例的表变量@nums。在文章中,他们有一个永久的枚举表。
答案 2 :(得分:1)
对于那些喜欢保持简单的人:
-- Here is the String Array you want to convert to a Table
declare @StringArray varchar(max)
set @StringArray = 'First item,Second item,Third item';
-- Here is the table which is going to contain the rows of each item in the String array
declare @@mytable table (EachItem varchar(50))
-- Just create a select statement appending UNION ALL to each one of the item in the array
set @StringArray = 'select ''' + replace(@StringArray, ',', ''' union all select ''') + ''''
-- Push the data into your table
insert into @@mytable exec (@StringArray)
-- You now have the data in an an array inside a table that you can join to other objects
select * from @@mytable
答案 3 :(得分:0)
从SQL Server 2016开始,可以使用OPENJSON and JSON_VALUE函数完成。
答案 4 :(得分:0)
我刚刚完成了这样的事情来创建临时表,以使用链接服务器上的INFORMATION_SCHEMA视图复制源表。但这是一个修改版本,用于创建您要查找的结果。请记住在显示时从“颜色”列中删除最后两个字符。
SELECT
t.Item
, (
SELECT
x.Color + ', ' AS [data()]
FROM
Items x
WHERE
x.Item = t.Item
FOR XML PATH(''), TYPE
).value('.', 'varchar(max)') AS Colors
FROM
Items t
GROUP BY
t.Item