如何直接在SQL中将逗号分隔值传递给存储过程

时间:2017-09-21 05:48:19

标签: sql-server-2008 tsql stored-procedures split

如何直接在SQLSERVER中将逗号分隔值传递给存储过程?

ALTER PROCEDURE [dbo].[CM_GetUnreadCount_ByUserJid_bilal_onlyfortesting] (@UserID AS VARCHAR(MAX))
AS
DECLARE @myTable TABLE (
    MessageId BIGINT,
    RecieverId VARCHAR(100)
    )

INSERT INTO @myTable (
    MessageId,
    RecieverId
    )
SELECT MAX(MessageID),
    ReceiverID
FROM dbo.CM_MessageStatus
WHERE ReceiverID IN (@UserID)
    AND DeliveredDate IS NOT NULL
GROUP BY ReceiverID

EXEC [CM_GetUnreadCount_ByUserJid_bilal_onlyfortesting] '123', '456'

错误:

  

Msg 8144,Level 16,State 2,Procedure   CM_GetUnreadCount_ByUserJid_bilal_onlyfortesting,第0行程序或   函数CM_GetUnreadCount_ByUserJid_bilal_onlyfortesting太多了   指定的参数。

1 个答案:

答案 0 :(得分:1)

你需要写

exec [CM_GetUnreadCount_ByUserJid_bilal_onlyfortesting] '123,456'

然后你需要在你的存储过程中使用string_split,就像这样:

注意 - 您在2016年只能使用string_split,否则您需要执行其他操作,例如XML PATH

CREATE    PROCEDURE [dbo].[CM_GetUnreadCount_ByUserJid_bilal_onlyfortesting] ( @UserID AS VARCHAR(MAX))
AS


 DECLARE @myTable TABLE
                        (
                          MessageId BIGINT,
                          RecieverId VARCHAR(100)
                        )

DECLARE @UserTable TABLE
( UserId varchar(MAX)
)
INSERT INTO @UserTable (UserID)
select * from string_split(@UserID,','); 

                    INSERT INTO @myTable
                            ( MessageId, RecieverId )
                     SELECT    MAX(MessageID),RecieverID
                      FROM      dbo.Message_status
                      WHERE     RecieverID IN (select * from @UserTable)
                                AND DeliveredDate IS NOT NULL
                                GROUP BY RecieverID

                                --RETURN OUTPUT TO TEST
                                Select * from @myTable