SQL Server:游标的使用在这里不可避免?

时间:2013-09-06 13:22:05

标签: sql-server split cursor

我有一个表格,其中只有一列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

...此刻我用光标调用了split函数。您认为有更好,更高效的解决方案吗?

2 个答案:

答案 0 :(得分:1)

在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

答案 1 :(得分:0)

您也可以使用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)