Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL statement which returns id and splits comma separated values

Tags:

sql-server

I have a table with the following data:

NodeId ExternalIds
50     601
56     700,701

How do I write an SQL-statement which splits the ExternalIds-column and returns:

NodeId ExternalIds
50     601
56     700
56     701

I have found a lot of user defined functions and procedure which splits a string into a table, but I cannot get any of them to work

edit

create table #tmpTable (NodeId int, ExternalIds varchar(50))
insert into #tmpTable (NodeId,ExternalIds) values (50, '600')
insert into #tmpTable (NodeId,ExternalIds) values (56, '700,701')

select NodeId, 
    (SELECT * FROM [dbo].[SplitString](select * from #tmpTable,',') where NodeId=56)from #tmpTable)
where NodeId=56
drop table #tmpTable

where SplitString is based on the following:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create FUNCTION [dbo].[SplitString] 
(
    -- Add the parameters for the function here
    @myString varchar(500),
    @deliminator varchar(10)
)
RETURNS 
@ReturnTable TABLE 
(
    -- Add the column definitions for the TABLE variable here
    [id] [int] IDENTITY(1,1) NOT NULL,
    [part] [varchar](50) NULL
)
AS
BEGIN
        Declare @iSpaces int
        Declare @part varchar(50)

        --initialize spaces
        Select @iSpaces = charindex(@deliminator,@myString,0)
        While @iSpaces > 0

        Begin
            Select @part = substring(@myString,0,charindex(@deliminator,@myString,0))

            Insert Into @ReturnTable(part)
            Select @part

    Select @myString = substring(@mystring,charindex(@deliminator,@myString,0)+ len(@deliminator),len(@myString) - charindex(' ',@myString,0))


            Select @iSpaces = charindex(@deliminator,@myString,0)
        end

        If len(@myString) > 0
            Insert Into @ReturnTable
            Select @myString

    RETURN 
END

I am trying to get some data from the database for Umbraco (the cms), which is designed with the comma-separated values.

thanks Thomas

like image 435
ThomasD Avatar asked Jun 03 '11 21:06

ThomasD


1 Answers

select NodeId, 
       S.part
from #tmpTable
  cross apply [dbo].[SplitString](ExternalIds, ',') as S
like image 177
Mikael Eriksson Avatar answered Sep 27 '22 19:09

Mikael Eriksson