Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 603
RetroCoder Avatar asked Apr 21 '11 02:04

RetroCoder


3 Answers

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/

like image 118
artofsql Avatar answered Nov 16 '22 13:11

artofsql


Give this a shot. It'll split and load your CSV values into a table variable.

declare @string nvarchar(500)
declare @pos int
declare @piece nvarchar(500)
declare @strings table(string nvarchar(512))

SELECT @string = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'

if right(rtrim(@string),1) <> ','
   SELECT @string = @string  + ','

SELECT @pos =  patindex('%,%' , @string)
while @pos <> 0 
begin
 SELECT @piece = left(@string, (@pos-1))

 --you now have your string in @piece
 insert into @strings(string) values ( cast(@piece as nvarchar(512)))

 SELECT @string = stuff(@string, 1, @pos, '')
 SELECT @pos =  patindex('%,%' , @string)
end

SELECT * FROM @Strings

Found and modified from Raymond at CodeBetter.

like image 7
p.campbell Avatar answered Nov 16 '22 12:11

p.campbell


what do you think about this one?

CREATE TABLE #t (UserName VARCHAR(50))

DECLARE @sql VARCHAR(MAX)
SELECT @sql = 'INSERT INTO #t SELECT ''' + REPLACE(@UserList, ',', ''' UNION SELECT ''') + ''''
PRINT (@sql)
EXEC (@sql)

SELECT * FROM #t

IF OBJECT_ID('tempdb..#t') IS NOT NULL BEGIN DROP TABLE #t END

http://swooshcode.blogspot.ro/2009/10/sql-split.html

like image 4
Ash Avatar answered Nov 16 '22 12:11

Ash