2017-09-21 105 views
0

如何直接在SQLSERVER中將逗號分隔值傳遞給存儲過程?如何直接在SQL中將逗號分隔值傳遞給存儲過程

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, Line 0 Procedure or function CM_GetUnreadCount_ByUserJid_bilal_onlyfortesting has too many arguments specified.

回答

1

你需要寫

exec [CM_GetUnreadCount_ByUserJid_bilal_onlyfortesting] '123,456' 

然後你需要string_split它存儲的過程中,就像這樣:

注意 - 你只能使用string_split在2016年,否則你需要做一些其他的東西,如XML路徑

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 
相關問題