我有一张表,其中只有一列 type varchar(max)
,看起来像这样:
COLUMN_A
jon;jonny;johana
jon
fred;brian
james;lars;cliff;kirk
现在我想拆分这些名称并为每个名称设置一行,例如:
COLUMN_A
jon
jonny
johana
jon
fred
brian
james
lars
cliff
kirk
...目前我用光标调用我的拆分函数。您认为对此有更好、更高效的解决方案吗?
我有一张表,其中只有一列 type varchar(max)
,看起来像这样:
COLUMN_A
jon;jonny;johana
jon
fred;brian
james;lars;cliff;kirk
现在我想拆分这些名称并为每个名称设置一行,例如:
COLUMN_A
jon
jonny
johana
jon
fred
brian
james
lars
cliff
kirk
...目前我用光标调用我的拆分函数。您认为对此有更好、更高效的解决方案吗?
在 T-SQL 中:
Begin Transaction
While Exists (Select * From Table
where CharIndex(';', column_A) > 0)
Begin
Insert Table(column_A)
Select Left(column_A, charIndex(';', column_A)-1)
Where charIndex(';', column_A) > 0
-- next 3 lines only if you want to avoid duplicates
And Not exists (Select * From table
Where column_A = Left(column_A,
charIndex(';', column_A)-1))
Update Table set column_A
= substring(columnA, 1+charIndex(';', column_A),
len(column_A) - charIndex(';', column_A))
From table
Where charIndex(';', column_A) > 0
End
Commit Transaction
您还可以使用 XML:
DECLARE @xml xml;
WITH cte AS (
SELECT * FROM (VALUES
('jon;jonny;johana'),
('jon'),
('fred;brian'),
('james;lars;cliff;kirk')) as t(COLUMN_A)
)
SELECT @xml = (
SELECT cast('<e>' + REPLACE(COLUMN_A,';','</e><e>') + '</e>' as xml)
FROM cte
FOR XML PATH(''))
SELECT n.v.value('.','nvarchar(50)') as COLUMN_A
FROM @xml.nodes('/e') AS n(v);
结果:
COLUMN_A
-----------
jon
jonny
johana
jon
fred
brian
james
lars
cliff
kirk
(10 row(s) affected)