2012-07-06 72 views

回答

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

太感謝你了... :) – user1506955 2012-07-06 14:11:41

+0

@ user1506955沒有問題。請在下次搜索時,這可能是最常問的SQL Server問題之一。 – 2012-07-06 14:13:10

0

我喜歡用一個表值函數來進行分割。

IF OBJECT_ID(N'dbo.StrSplit')IS NOT NULL DROP FUNCTION DBO。[StrSplit] GO

CREATE FUNCTION [DBO]。[StrSplit] ( @String VARCHAR(MAX),@定界符炭(1) ) RETURNS @Results TABLE( 項目NVARCHAR(MAX) ) AS BEGIN DECLARE @INDEX INT DECLARE nvarchar的@SLICE(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]至[公用]

相關問題