如何将逗号分隔的数字字符串解析为临时orderId表?

时间:2011-04-21 02:25:58

标签: sql-server tsql sql-server-2000

我有一堆orderIds'1,18,1000,77 ......'我正在从nvarchar(8000)中撤回。我试图解析此字符串并将id放入临时表。有一种简单有效的方法吗?

要查看我解析的所有orderId的列表,我应该能够这样做:

select orderid from #temp

5 个答案:

答案 0 :(得分:7)

给它一个机会。它会将CSV值拆分并加载到表变量中。

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

Raymond at CodeBetter找到并修改。

答案 1 :(得分:7)

通过数字表创建的最快方式:

--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) = ',';

根据以下文章,这是我多年来一直使用的一种很好的方法: http://www.sqlservercentral.com/articles/T-SQL/62867/

答案 2 :(得分:4)

你怎么看待这个?

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

答案 3 :(得分:2)

这是一个User Defined函数,它返回一个带有Id的DataTable,您可以将其用于关节。 看看this article可以很好地解决这个问题。

   CREATE FUNCTION ParamParserFn( @delimString varchar(255), @delim char(1)) 
    RETURNS @paramtable 
    TABLE ( Id int ) 
    AS BEGIN

    DECLARE @len int,
            @index int,
            @nextindex int

    SET @len = DATALENGTH(@delimString)
    SET @index = 0
    SET @nextindex = 0


    WHILE (@len > @index )
    BEGIN

    SET @nextindex = CHARINDEX(@delim, @delimString, @index)

    if (@nextindex = 0 ) SET @nextindex = @len + 2

     INSERT @paramtable
     SELECT SUBSTRING( @delimString, @index, @nextindex - @index )


    SET @index = @nextindex + 1

    END
     RETURN
    END
    GO

答案 4 :(得分:1)

更改&gt; to&gt; =在以下代码中仅对带有一个逗号的输入正常工作。相信链接文章中的第一条评论。

WHILE (@len > @index )
BEGIN

SET @nextindex = CHARINDEX(@delim, @delimString, @index)