How do I pass a list as a parameter in a stored procedure?

SqlSql ServerStored Procedures

Sql Problem Overview


Looking to pass a list of User IDs to return a list names. I have a plan to handle the outputed names (with a COALESCE something or other) but trying to find the best way to pass in the list of user IDs. The guts of my sproc will look something like this:

create procedure [dbo].[get_user_names]
@user_id_list, --which would equal a list of incoming ID numbers like (5,44,72,81,126)
@username varchar (30) output
as
select last_name+', '+first_name 
from user_mstr
where user_id in @user_id_list

Passing the values for @user_id_list is my main concern here.

Sql Solutions


Solution 1 - Sql

The preferred method for passing an array of values to a stored procedure in SQL server is to use table valued parameters.

First you define the type like this:

CREATE TYPE UserList AS TABLE ( UserID INT );

Then you use that type in the stored procedure:

create procedure [dbo].[get_user_names]
@user_id_list UserList READONLY,
@username varchar (30) output
as
select last_name+', '+first_name 
from user_mstr
where user_id in (SELECT UserID FROM @user_id_list)

So before you call that stored procedure, you fill a table variable:

DECLARE @UL UserList;
INSERT @UL VALUES (5),(44),(72),(81),(126)

And finally call the SP:

EXEC dbo.get_user_names @UL, @username OUTPUT;

Solution 2 - Sql

As far as I can tell, there are three main contenders: Table-Valued Parameters, delimited list string, and JSON string.

Since 2016, you can use the built-in STRING_SPLIT if you want the delimited route: https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql

That would probably be the easiest/most straightforward/simple approach.

Also since 2016, JSON can be passed as a nvarchar and used with OPENJSON: https://docs.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql

That's probably best if you have a more structured data set to pass that may be significantly variable in its schema.

TVPs, it seems, used to be the canonical way to pass more structured parameters, and they are still good if you need that structure, explicitness, and basic value/type checking. They can be a little more cumbersome on the consumer side, though. If you don't have 2016+, this is probably the default/best option.

I think it's a trade off between any of these concrete considerations as well as your preference for being explicit about the structure of your params, meaning even if you have 2016+, you may prefer to explicitly state the type/schema of the parameter rather than pass a string and parse it somehow.

Solution 3 - Sql

Azure DB, Azure Data WH and from SQL Server 2016, you can use STRING_SPLIT to achieve a similar result to what was described by @sparrow.

Recycling code from @sparrow

WHERE user_id IN (SELECT value FROM STRING_SPLIT( @user_id_list, ',')

Simple and effective way of accepting a list of values into a Stored Procedure

Solution 4 - Sql

I solved this problem through the following:

  1. In C # I built a String variable.

> string userId="";

  1. I put my list's item in this variable. I separated the ','.

> for example: in C# > > userId= "5,44,72,81,126";

and Send to SQL-Server

> SqlParameter param = cmd.Parameters.AddWithValue("@user_id_list",userId);

  1. I Create Separated Function in SQL-server For Convert my Received List (that it's type is NVARCHAR(Max)) to Table.

> CREATE FUNCTION dbo.SplitInts
> (
> @List VARCHAR(MAX),
> @Delimiter VARCHAR(255)
> )
> RETURNS TABLE
> AS
> RETURN ( SELECT Item = CONVERT(INT, Item) FROM
> ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)')
> FROM ( SELECT [XML] = CONVERT(XML, ''
> + REPLACE(@List, @Delimiter, '
') + '').query('.')
> ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
> WHERE Item IS NOT NULL
> );

  1. In the main Store Procedure, using the command below, I use the entry list.

> SELECT user_id = Item FROM dbo.SplitInts(@user_id_list, ',');

Solution 5 - Sql

You can try this:

create procedure [dbo].[get_user_names]
    @user_id_list varchar(2000), -- You can use any max length
    
    @username varchar (30) output
    as
    select last_name+', '+first_name 
    from user_mstr
    where user_id in (Select ID from dbo.SplitString( @user_id_list, ',') )

And here is the user defined function for SplitString:

Create 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

Solution 6 - Sql

Check the below code this work for me

@ManifestNoList      VARCHAR(MAX)


WHERE
    (
        ManifestNo IN (SELECT value FROM dbo.SplitString(@ManifestNoList, ','))
    )

Solution 7 - Sql

this is perfect working for me . this perfect example i hope solved many users problem.

Step 1 Creare reference table in sql like this

 Create TYPE dbo.tblNames
AS TABLE
(
    [Name] nvarchar(max)
);
go

create TYPE dbo.tblNamesWithCols
AS TABLE
(
    [Name] nvarchar(max)
);
go

Step 2 create store procedure with reference table parameters like this

    create proc syTest
    @VarTbleNameList AS dbo.tblNames READONLY,
    @VarTbleNameColsList AS dbo.tblNamesWithCols READONLY,
	@VarWhereQuery nvarchar(max)
    as
    begin
    ......
......  End

**Calling Store Procedure with parameters **

DECLARE @VarTbleList AS dbo.tblNames
INSERT INTO @VarTbleList
VALUES ( 'tblEmployes' )
INSERT INTO @VarTbleList
VALUES ( 'tblDepartments' )
INSERT INTO @VarTbleList
VALUES ( 'tblCities' )

DECLARE @VarTbleColList AS dbo.tblNamesWithCols
INSERT INTO @VarTbleColList
VALUES ( 'tblEmployes.EmployeId as empId;' )
INSERT INTO @VarTbleColList
VALUES ( 'tblEmployes.EmployeName as empName;' )
INSERT INTO @VarTbleColList
VALUES ( 'tblDepartments.DepartmentName as deptName;'  )
INSERT INTO @VarTbleColList
VALUES ( 'tblDepartments.DepartmentId as deptId;' )

EXECUTE  syTest @VarTbleList , @VarTbleColList , @VarWhereQuery ='test'

Solution 8 - Sql

The proper way is to create a user defined data type:

CREATE TYPE [dbo].[IntArray] AS TABLE
(
	[ID] [INT] NULL
)

Then you can use this custom data type:

CREATE OR ALTER PROCEDURE [dbo].[sp_GetUserNames]
(
    @userIds [IntArray] READONLY
)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
        "Name" = u.LastName + ', ' + u.FirstName
    FROM dbo.User u
    JOIN @userIds uid ON u.Id = uid.Id;
END

Usage:

@DECLARE @result TABLE
(
    Name NVARCHAR(max)
);

@DECLARE @ids [IntArray] = SELECT x.userId FROM dbo.sometable x;

SET @result = EXECUTE [dbo].[sp_GetUserNames] @userIds = @ids;

SELECT * FROM @result;

Solution 9 - Sql

Maybe you could use:

select last_name+', '+first_name 
from user_mstr
where ',' + @user_id_list + ',' like '%,' + convert(nvarchar, user_id) + ',%'

Solution 10 - Sql

You can use this simple 'inline' method to construct a string_list_type parameter (works in SQL Server 2014):

declare @p1 dbo.string_list_type
insert into @p1 values(N'myFirstString')
insert into @p1 values(N'mySecondString')

Example use when executing a stored proc:

exec MyStoredProc @MyParam=@p1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser4840156View Question on Stackoverflow
Solution 1 - SqlMatthew SontumView Answer on Stackoverflow
Solution 2 - SqlAmbrose LittleView Answer on Stackoverflow
Solution 3 - SqlPeter HenryView Answer on Stackoverflow
Solution 4 - SqlBehrouzMoslemView Answer on Stackoverflow
Solution 5 - SqlSparrowView Answer on Stackoverflow
Solution 6 - SqlChamath JeevanView Answer on Stackoverflow
Solution 7 - SqlAamir HussainView Answer on Stackoverflow
Solution 8 - SqlMovGP0View Answer on Stackoverflow
Solution 9 - SqlSkippyView Answer on Stackoverflow
Solution 10 - SqlChris HalcrowView Answer on Stackoverflow