-->

Error when trying to pass comma separated values i

2020-05-06 01:10发布

问题:

I am calling this SQL Server stored procedure from another application in this way:

EXEC GlobalReminder @documentidnumber = '${@documentidnumber}';

The documentidnumber is a variable that contains comma separated values, for example 7568, 8990, 5523. It appears that in this format, I am unable to pass multiple values to this parameter and hence this results in an error.

CREATE PROCEDURE [dbo].[GlobalReminder]
    (@documentidnumber NVARCHAR(MAX))
AS
BEGIN
    SET NOCOUNT ON;

    SELECT SUB, REGION, SORTCODE, CLUSTER 
    FROM TABLE1 ct
    INNER JOIN TABLE2 pl ON ct.TYPE_ID = pl.TYPE_ID
    WHERE DOCUMENT_ID IN (@documentidnumber)
END
GO

Can someone please suggest what would be the simplest way to pass multiple values to a single parameter. I went through some of the existing questions already and the solution mentioned seem to be very complex.

Thanks.

回答1:

The correct solution is to use table valued parameter. But in SQL Server 2016 you have the STRING_SPLIT function available which you can use inside the stored procedure:

CREATE PROCEDURE [dbo].[GlobalReminder] (
    @documentidnumber nvarchar(max)
) AS
BEGIN
    SET NOCOUNT ON;

    SELECT SUB, REGION, SORTCODE, CLUSTER
    FROM TABLE1 ct
    INNER JOIN TABLE2 pl ON ct.TYPE_ID = pl.TYPE_ID
    WHERE DOCUMENT_ID IN (
        SELECT value
        FROM STRING_SPLIT(@documentidnumber, ',')
    )
END

Note that if DOCUMENT_ID is an integer column then the comma separated list must also consist of valid integers.



回答2:

You can use split_string():

WHERE DOCUMENT_ID IN (SELECT s.val FROM SPLIT_STRING(@documentidnumber, ',') s(val))