I have stored procedure where I have to pass parameters, But the problem is I am not sure how many parameters is going to come it can be 1, in next run it can be 5.
cmd.Parameters.Add(new SqlParameter("@id", id)
Can anyone help how can I pass these variable number of parameters in stored procedure? Thanks
A procedure can have a maximum of 2100 parameters; each assigned a name, data type, and direction. Optionally, parameters can be assigned default values.
As a program, a stored procedure can take parameters. There are three types of parameters: IN, OUT and INOUT.
You can define a procedure with no parameters, one parameter, or more than one. The part of the procedure definition that specifies the parameters is called the parameter list.
A Stored Procedure can have any number of output parameters. The simple logic is this — If you want to return 1 value then use 1 output parameter, for returning 5 values use 5 output parameters, for 10 use 10, and so on.
You could pass it in as a comma-separated list, then use a split function, and join against the results.
CREATE FUNCTION dbo.SplitInts ( @List VARCHAR(MAX), @Delimiter CHAR(1) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'INT') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.') ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y WHERE Item IS NOT NULL );
Now your stored procedure:
CREATE PROCEDURE dbo.doStuff @List VARCHAR(MAX) AS BEGIN SET NOCOUNT ON; SELECT cols FROM dbo.table AS t INNER JOIN dbo.SplitInts(@List, ',') AS list ON t.ID = list.Item; END GO
Then to call it:
EXEC dbo.doStuff @List = '1, 2, 3, ...';
You can see some background, other options, and performance comparisons here:
On SQL Server 2016 or above, though, you should look at STRING_SPLIT()
and STRING_AGG()
:
Stored procedures support optional parameters. Like C# 4, you can specify a default value using =
. For example:
create procedure dbo.doStuff( @stuffId int = null, @stuffSubId int = null, ...) as ...
For parameters you don't want to pass, either set them to null
or don't add them to cmd.Parameters
at all. They will have their default value in the stored procedure
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With