列之一(表1中的Say column1)存储数据如下
Column1 test2;test1;test3 test21;test11;test32 --
我想更新此列,以便数据以排序的形式存储(在按数据拆分后),如下所示
Column1 test1;test2;test3 test11;test21;test32 --
如何以最简单的形式编写查询?我正在使用SQL Server 2005
我可以假设没有使用T-SQL的简单解决方案,那么我可以使用CLR功能吗?
答案 0 :(得分:1)
通过原始SQL无法实现。您可以找到SPLIT函数(T-SQL或CLR)的实现(如http://blogs.microsoft.co.il/blogs/itai/archive/2009/02/01/t-sql-split-function.aspx那个)并通过临时转换字符串列表处理数据到表,然后对其进行排序然后再加入。
答案 1 :(得分:1)
如何以基于集合的方式在T-SQL中执行此操作的示例。它假定目标表具有唯一标识每一行的PK 请注意,排序是基于文本的。我已经添加了第三行测试数据来显示这一点。
DECLARE @t TABLE
(id int ,column1 varchar(50))
INSERT @t
SELECT 1,'test2;test1;test3'
UNION ALL SELECT 2,'test21;test11;test32'
UNION ALL SELECT 3,'test222;test22;test2;test1;test3'
DECLARE @chr_delim char(1)
SET @chr_delim = ';'
;WITH splitCTE
AS
(
SELECT D.id
,SUBSTRING(s,n,CHARINDEX(@chr_delim, s + @chr_delim,n) -n) as ELEMENT
FROM (SELECT id, column1 as s from @t) AS D
JOIN (SELECT ROW_NUMBER() OVER (ORDER BY name) AS n
FROM master..spt_values
) AS nums
ON n <= LEN(s)
AND SUBSTRING(@chr_delim + s,n,1) = @chr_delim
)
UPDATE t
SET column1 = z.col1
FROM @t AS t
JOIN (
SELECT DISTINCT id , STUFF(d.x,1,1,'') AS col1
FROM splitCTE AS r
CROSS APPLY (SELECT ';' + ELEMENT
FROM splitCTE AS c
WHERE c.id = r.id
ORDER BY ELEMENT FOR XML PATH ('')
) d(x)
) AS z
ON z.id = t.id
SELECT * FROM @t