如何拆分列值并添加到临时表

时间:2014-06-02 01:58:53

标签: sql-server sql-server-2008-r2

我使用的是SQL Server 2008 R2。

我有一张表tblInstitution,如下所示

InstitutionCode   InstitutionDesc
---------------------------------
ABC               Abra Cada Brad   
DEF               Def Fede Eeee 
GHJ               Gee Hee

我想在InstitutionDesc中拆分值并根据机构代码存储它

InstitutionCode   Token   Score
-------------------------------
ABC               Abra      0
ABC               Cada      0
ABC               Brad      0
DEF               Def       0
DEF               Fede      0
DEF               Eeee      0
GHJ               Gee       0
GHJ               Hee       0

有没有办法在基于集合的操作中执行此操作?

我见过一些示例,其中单个列值可以拆分为同一行的多个列值。但我无法找到可以将同一列拆分为不同行的示例。我不确定究竟应该搜索什么。是否与CTE有关。

1 个答案:

答案 0 :(得分:1)

这是一个递归的CTE选项...

If      Object_ID('tempdb..#tblInstitution') Is Not Null Drop Table #tblInstitution;
Create  Table #tblInstitution (InstitutionCode Varchar(10), InstitutionDesc Varchar(50));

Insert  #tblInstitution (InstitutionCode, InstitutionDesc)
Values  ('ABC','Abra Cada Brad'),
        ('DEF','Def Fede Eeee'),
        ('GHJ','Gee Hee'),
        ('KLM','Kappa');

With    base As
(
        Select  InstitutionCode, 
                LTRIM(RTRIM(InstitutionDesc)) As InstitutionDesc
        From    #tblInstitution
),      recur As
(
        Select  InstitutionCode,
                Left(InstitutionDesc, CharIndex(' ', InstitutionDesc + ' ') - 1) As Token,
                Case
                When    CharIndex(' ', InstitutionDesc) > 0
                Then    Right(InstitutionDesc, Len(InstitutionDesc) - CharIndex(' ', InstitutionDesc))
                Else    Null
                End     As Remaining
        From    base
        Union   All
        Select  InstitutionCode,
                Left(Remaining, CharIndex(' ', Remaining + ' ') - 1) As Token,
                Case
                When    CharIndex(' ', Remaining) > 0
                Then    Right(Remaining, Len(Remaining) - CharIndex(' ', Remaining))
                Else    Null
                End     As Remaining
        From    recur
        Where   Remaining Is Not Null
)
Select  InstitutionCode,
        Token,
        0   As Score
From    recur
Order   By InstitutionCode