列组合

时间:2013-07-17 17:07:28

标签: sql sql-server

我知道有一个SQL:

样本表:

ID   FirstName   LastName
1    Jones       Smith
2    Paul        Tabunjong
3    John        Parks

SQL结果:

ID   Name
1    Jones Smith
2    Paul Tabunjong
3    John Parks

现在,有可能扭转它吗?像这样的东西:

样本表:

ID   Name
1    Jones Smith
2    Paul Tabunjong
3    John Parks

SQL结果:

ID   FirstName   LastName
1    Jones       Smith
2    Paul        Tabunjong
3    John        Parks

另一个:是否有可能有这样的事情:

样本表:

ID   CorporateNames
1    Jones Smith; Anna Tomson; Tonny Parker
2    Paul Tabunjong; Poncho Pilato
3    John Parks; Berto Taborjakol

SQL结果:

ID   FirstName   LastName
1    Jones       Smith
1    Anna        Tomson 
1    Tonny       Parker
2    Paul        Tabunjong
2    Poncho      Pilato
3    John        Parks
3    Berto       Taborjakol

1 个答案:

答案 0 :(得分:0)

是的,您可以编写拆分功能,然后使用它来解析数据。下面是使用SUBSTRING()函数的示例拆分函数:

CREATE FUNCTION dbo.Split
(
    @RowData nvarchar(2000),
    @SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
    Id int identity(1,1),
    Data nvarchar(100)
) 
AS  
BEGIN 
    Declare @Cnt int
    Set @Cnt = 1

    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        Insert Into @RtnValue (data)
        Select 
            Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End

    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))

    Return
END