0

我的 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

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

4

1 回答 1

1

使用此链接:如何在单个语句中将 CSV 数据拆分并插入到新表中?,有一个函数可以用来将 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
       )
于 2012-08-26T11:22:53.550 回答