如何为CSV的每个值运行SQL Server存储过程查询

时间:2012-08-26 10:57:23

标签: sql sql-server database tsql

我在SQL Server 2008 R2数据库中有以下存储过程

ALTER PROCEDURE [dbo].[usp_send_email] 
    @pStatus Int Out,
    @pEMailId Int Out,
    @pSenderUserName varchar(MAX),  
    @pReceivers VarChar(50),         **-- this column can have csv values**
    @pSub NVarChar(100),
    @pCon NVarchar(MAX),
    @pHasAttachments Bit
AS
BEGIN
   --SET NOCOUNT ON;

   Insert Into MessagingMessage
      (
       CreatedBy,
       [Subject],
       Body,
       HasAttachments
      )
     Values
     (    
      @pSenderUserName,
      @pSub,
      @pCon,
      @pHasAttachments
      )
    SET @pEMailId = SCOPE_IDENTITY()  

     Insert Into MessagingMessageReceipient
      (
       MessageId,
       ReceipientId,
       ReceipientType
      )
     Values
     (    
      @pEMailId,
      @pReceivers,
      1
      )
     SET @pStatus  = SCOPE_IDENTITY() 

END

在上面的代码中,我想在循环中为每个逗号分隔的用户名运行第一个语句,但是第二个插入语句。作为参数的CSV值已经由C#代码验证,因此无需验证它。

1 个答案:

答案 0 :(得分:1)

使用此链接:how to split and insert CSV data into a new table in single statement?,您可以使用一个函数将csv解析为表,我已在下面的代码中使用它。请尝试以下

Insert Into MessagingMessageReceipient
  (
   MessageId,
   ReceipientId,
   ReceipientType
  )
  SELECT
   @pEMailId,
   csv.Part,   -- each @pReceiver
   1
  FROM 
     dbo.inline_split_me(',',@pReceivers) csv

该功能将复制到

下面
CREATE FUNCTION inline_split_me (@SplitOn char(1),@String varchar(7998))
RETURNS TABLE AS
RETURN (WITH SplitSting AS
           (SELECT
                LEFT(@String,CHARINDEX(@SplitOn,@String)-1) AS Part
                    ,RIGHT(@String,LEN(@String)-CHARINDEX(@SplitOn,@String)) AS Remainder
                WHERE @String IS NOT NULL AND CHARINDEX(@SplitOn,@String)>0
            UNION ALL
            SELECT
                LEFT(Remainder,CHARINDEX(@SplitOn,Remainder)-1)
                    ,RIGHT(Remainder,LEN(Remainder)-CHARINDEX(@SplitOn,Remainder))
                FROM SplitSting
                WHERE Remainder IS NOT NULL AND CHARINDEX(@SplitOn,Remainder)>0
            UNION ALL
            SELECT
                Remainder,null
                FROM SplitSting
                WHERE Remainder IS NOT NULL AND CHARINDEX(@SplitOn,Remainder)=0
           )
           SELECT Part FROM SplitSting
       )