I have a stored procedure that I need to pass multiple parameters in SQL Server 2012. My application will build a report for all employees or certain employees. I have a check list box for the employees if the user wants to choose certain employees instead of all of them. I want to use those selected employees in the where clause in the stored procedure. I've read in SQL Server 2012 you can pass a table as a parameter with multiple values. I can't seem to find a good example to fit my situation. Any help would be greatly appreciated.
2 Answers
Let's say you are passing EmployeeIDs, and they are integers. First, create a table type in the database:
CREATE TYPE dbo.EmployeesTVP AS TABLE(EmployeeID INT PRIMARY KEY);
Now your stored procedure can say:
CREATE PROCEDURE dbo.GetEmployees
@empTVP dbo.EmployeesTVP READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT EmployeeID, Name FROM dbo.Employees AS e
WHERE EXISTS (SELECT 1 FROM @empTVP WHERE EmployeeID = e.EmployeeID);
END
GO
And if you want to handle the all scenario, you can say:
IF EXISTS (SELECT 1 FROM @empTVP)
SELECT EmployeeID, Name FROM dbo.Employees AS e
WHERE EXISTS (SELECT 1 FROM @empTVP WHERE EmployeeID = e.EmployeeID);
ELSE
SELECT EmployeeID, Name FROM dbo.Employees;
(You could combine these with an OR conditional, but I tend to find this just gives the optimizer fits.)
Then you create a DataTable in your C# code from the checkboxes, and pass the parameter to your stored procedure as a parameter type of Structured. You can fill in the rest but:
DataTable tvp = new DataTable();
// define / populate DataTable from checkboxes
using (connectionObject)
{
using (SqlCommand cmd = new SqlCommand("dbo.GetEmployees", connectionObject))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvparam = cmd.Parameters.Add("@empTVP", SqlDbType.Structured);
tvparam.TypeName = "dbo.EmployeesTVP";
tvparam.Value = tvp;
// ... execute the cmd, grab a reader, etc.
}
}
3 Comments
Complementary to the Aaron response:
1/ Send your data packed as XML and use an XML data type for your parameter
or
2/ Join your employee IDs values into a single string, comma separated, then split those values.