0

I am having following stored procedure in my SQL Server 2008 R2 database

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

In above code I want to run the first statement only one time but second insert statements in loop for each comma separated username.CSV value coming as a parameter is already validated by C# code so no need to validate it.

1 Answer 1

1

Using this link: how to split and insert CSV data into a new table in single statement?, there is a function you can use to parse csv to to table and I have used it in the code below. Try the following

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

And the function is copied below

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
       )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.