Passing sets and optional parameters to a stored procedure T-SQL - ASP.NET
You can achieve optional parameters in T-SQL stored procedures by having default values equal NULL.
Example where NULL is used as "ignore this parameter":
CREATE PROCEDURE [dbo].[dcspFilterEmpList]
@ProductName nvarchar(200) = null,
@ProductGroupID int = null
AS BEGIN
SELECT
prod_id AS 'ID',
prod_name AS 'Name'
FROM dbo.Products
WHERE (prod_group_id = @ProductGroupID OR @ProductGroupID IS NULL)
AND (prod_name = @ProductName OR @ProductName IS NULL)
END
It's perfectly fine to define a stored procedure to take a table-valued parameter in T-SQL. Here is an article on the subject http://sqlwithmanoj.wordpress.com/2012/09/10/passing-multipledynamic-values-to-stored-procedures-functions-part4-by-using-tvp/
If you need more info on this google for "table-valued parameter"
Example using multi-valued parameters:
CREATE TYPE XTV_ProductNames AS TABLE --extension, table valued == XTV
( ProductName nvarchar(50))
GO
CREATE TYPE XTV_ProductGroups AS TABLE --extension, table valued == XTV
( ProductGroupID int))
GO
CREATE PROCEDURE [dbo].[dcspFilterEmpList]
@TVP1 XTV_ProductNames READONLY
,@TVP2 XTV_ProductGroups READONLY
AS BEGIN
SELECT
prod_id AS 'ID',
prod_name AS 'Name'
FROM dbo.Products as p
INNER JOIN @TVP1 as s
ON p.prod_name = s.ProductName
UNION
SELECT
prod_id AS 'ID',
prod_name AS 'Name'
FROM dbo.Products as p
INNER JOIN @TVP2 as s
ON p.prod_group_id = s.ProductGroupID
END
Your answer was correct David, but it was a little misleading because the parameter equaling NULL does not make it optional; it just has to be set to any value period. This also creates optional parameters:
CREATE PROCEDURE [dbo].[dcspFilterEmpList]
@ProductName nvarchar(200) = 'DefaultProduct',
@ProductGroupID int = 1
AS
Which could thus be executed without passing any parameters, i.e.:
EXEC [dbo].[dcspFilterEmpList]
I understand that this wasn't necessarily what Piscovetz was trying to do, but it seems to match more closely the actual topic question shown, and it is an important distinction.