Search code examples
sql-servert-sqlsql-server-2000

How to Parse a comma delimited string of numbers into a temporary orderId table?


I have a bunch of orderIds '1, 18, 1000, 77 ...' that I'm retreiving from a nvarchar(8000). I am trying to parse this string and put the id into a temporary table. Is there a simple and effective way to do this?

To view a list of all the orderIds that I parsed I should be able to do this:

select orderid from #temp

Solution

  • The fastest way via a numbers table that takes seconds to create:

    --First build your numbers table via cross joins
    select top 8000 ID=IDENTITY(int,1,1)
    into numbers
    from syscolumns s1
    ,syscolumns s2
    ,syscolumns s3
    GO
    --add PK
    alter table numbers add constraint PK_numbers primary key clustered(ID);
    GO
    
    create table #temp(
    ID int identity(1,1) primary key,
    StringValues varchar(8000)
    )
    
    declare @orderIds varchar(8000)
        set @orderIds =  ',1, 18, 1000, 77, 99, 1000, 2, 4,'
    
    insert into #temp(StringValues)
    select substring(@orderIds,ID+1,charindex(',',@orderIds,ID+1)-ID-1)
    from numbers where ID < len(@orderIds)and substring(@orderIds,ID,1) = ',';
    

    This is a great method I've been using for years based on the following article: http://www.sqlservercentral.com/articles/T-SQL/62867/