使用ms sql在表中插入逗号分隔值的存储过程?

时间:2012-07-06 14:05:44

标签: sql-server-2008 java-stored-procedures

我有一个名为assignRole的表。

我传递的是userid(int)csv的字符串,并传递了roleid(int)。

我想要一个存储过程,它将userid从string中分离并获取roleid并在table中插入这些值。这对于userid字符串中的所有值都会发生。

2 个答案:

答案 0 :(得分:0)

首先,创建一个函数:

CREATE FUNCTION [dbo].[SplitInts]
(
   @List       VARCHAR(MAX),
   @Delimiter  CHAR(1)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( 
     SELECT Item = x.i.value('(./text())[1]', 'int') FROM ( 
       SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') 
       + '</i>').query('.') ) AS a CROSS APPLY [XML].nodes('i') AS x(i)) AS y
     WHERE Item IS NOT NULL
   );

现在你可以说:

INSERT dbo.assignRole(RoleID, UserID)
  SELECT @RoleID, Item
  FROM dbo.SplitInts(@UserIDList, ',');

答案 1 :(得分:0)

我喜欢使用表值函数来进行拆分。

如果OBJECT_ID(N'dbo.StrSplit')不是DROP FUNCTION dbo。[StrSplit] GO

创建功能[dbo]。[StrSplit] (        @String VARCHAR(MAX),@ Delimiter char(1) ) 退货        @Results TABLE(               物品NVARCHAR(MAX)        ) 如 开始     DECLARE @INDEX INT     DECLARE @SLICE nvarchar(MAX)

-- HAVE TO SET TO 1 SO IT DOESNT EQUAL ZERO FIRST TIME IN LOOP
SELECT @INDEX = 1


-- Early exit if passed string is null
IF @String IS NULL RETURN

WHILE @INDEX !=0
BEGIN 
          -- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
          SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)

          -- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
          IF @INDEX !=0
                 SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
          ELSE
                 SELECT @SLICE = @STRING
          -- PUT THE ITEM INTO THE RESULTS SET
          INSERT INTO @Results(Items) VALUES(@SLICE)
          -- CHOP THE ITEM REMOVED OFF THE MAIN STRING
          SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)
          -- BREAK OUT IF WE ARE DONE
          IF LEN(@STRING) = 0 BREAK
END
RETURN

END

GO GRANT SELECT ON [dbo]。[StrSplit] TO [public]