Reputation: 771
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.
Upvotes: 0
Views: 481
Reputation: 272296
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.
Upvotes: 3
Reputation: 1270713
You can use split_string()
:
WHERE DOCUMENT_ID IN (SELECT s.val FROM SPLIT_STRING(@documentidnumber, ',') s(val))
Upvotes: 3