2012-08-26 77 views
0

我有以下存儲過程在我的SQL Server 2008 R2數據庫如何運行SQL Server存儲過程查詢的CSV

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#代碼驗證,因此不需要驗證它。

回答

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 
     ) 
+0

感謝下面複製了很多,我將用它 – Abhi

相關問題