拆分多行后,通过while循环保存在SQL Server中

时间:2017-11-04 06:12:50

标签: sql sql-server

这是要插入的存储过程。

CREATE PROCEDURE [dbo].[SP_SaveMail]
     @Subject NVARCHAR(550), 
     @Message NVARCHAR(550),  
     @ParentID INT,  
     @SenderID INT, 
     @SenderType INT, 
     @ReceiverID NVARCHAR(MAX), 
     @ReceiverType INT
AS
BEGIN
    DECLARE @MailID INT

    INSERT INTO [dbo].[tbl_Mail] (Subject, Message, ParentID, IsRead, IsDeleted)
    VALUES (@Subject, @Message, @ParentID, 0, 0)

    SET @MailID = (SELECT @@identity)

    if (@MailID > 0)
       -- After this I want to split the @ReceiverID 
       -- The code to split the @ReceiverID is [dbo].SplitString(@ReceiverID, ',')

       -- After split I want to insert it into the table [dbo].[tbl_Mail_Mapping] one by one through for loop or while loop.
   -- BEGIN
   -- DECLARE @tags NVARCHAR(400)

   -- SET @tags = ([dbo].SplitString(@ReceiverID, ','))
   -- WHILE LEN(@tags) > 0
   -- BEGIN
   --     INSERT INTO [dbo].[tbl_Mail_Mapping](MailID, SenderID, SenderType, ReceiverID, ReceiverType)
   --     VALUES (@MailID, @SenderID, @SenderType, @tags, @ReceiverType) 
   -- END
END

以下是要拆分的代码:

ALTER FUNCTION [dbo].[SplitString]
    (@Input NVARCHAR(MAX),
     @Character CHAR(1))
RETURNS @Output TABLE (Item NVARCHAR(1000))
AS
BEGIN
    DECLARE @StartIndex INT, @EndIndex INT

    SET @StartIndex = 1

    IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
    BEGIN
        SET @Input = @Input + @Character
    END

    WHILE CHARINDEX(@Character, @Input) > 0
    BEGIN
        SET @EndIndex = CHARINDEX(@Character, @Input)

        INSERT INTO @Output(Item)
            SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)

        SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
    END

    RETURN
END

有人能告诉我如何在拆分后插入一个while循环并插入查询以插入到表中吗?

注意:@ReceiverID如下所示:3,2,5,即在此我通过调用@ReceiverID分割[dbo].SplitString(@ReceiverID, ',')。拆分后,它会像一个包含列项目3 2 5

的表一样返回

请参阅此屏幕截图:

enter image description here

拆分之后谁能告诉我如何编写while循环来保存??

2 个答案:

答案 0 :(得分:1)

您不需要使用循环。使用表值函数中的SELECT:

INSERT INTO  [dbo].[tbl_Mail_Mapping]( MailID, SenderID, SenderType, RecieverID, RecieverType )
SELECT   @MailID
        ,@SenderID
        ,@SenderType
        ,r.Item
        ,@RecieverType
FROM [dbo].[SplitString](@RecieverID, ',') r
WHERE Item != ''

答案 1 :(得分:0)

在这里,我认为您不需要使用while循环或函数,只需使用var customers = _dbContext.Customers.Where(x => x.AssignedStaff.Id == staffId); 方法,即可完成此操作:

XML