0

I know there is an SQL for this:

Sample Table:

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

SQL Result:

ID   Name
1    Jones Smith
2    Paul Tabunjong
3    John Parks

Now, is it possible to have reverse of it? something like this:

Sample Table:

ID   Name
1    Jones Smith
2    Paul Tabunjong
3    John Parks

SQL Result:

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

Another one: Is it possible to have something like this:

Sample Table:

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

SQL Result:

ID   FirstName   LastName
1    Jones       Smith
1    Anna        Tomson 
1    Tonny       Parker
2    Paul        Tabunjong
2    Poncho      Pilato
3    John        Parks
3    Berto       Taborjakol
microMolvi
  • 636
  • 11
  • 30
Square Ponge
  • 702
  • 2
  • 10
  • 26
  • 1
    how to handle `Dick Van Dyke;Anna Sophie Smith` – bummi Jul 17 '13 at 17:12
  • 1
    Your're going to need to split apart the Name using delimiters. You have the delimiters you need. Check this out http://stackoverflow.com/questions/2647/split-string-in-sql – dseibert Jul 17 '13 at 17:12
  • possible duplicate of [SQL Split function](http://stackoverflow.com/questions/2872358/sql-split-function) – Zzz Jul 17 '13 at 21:50

1 Answers1

0

Yes, you can write a split function and then use it to parse the data. Below is a sample split function using the SUBSTRING() function:

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
Zzz
  • 2,927
  • 5
  • 36
  • 58