Table Valued Parameters in SQL 2008

Miscrosoft SQL Server 2008 has been upgraded to accept table values as parameters for Stored Procedures (SPs). Once a Table Valued Parameter (TVP) is passed as a parameter to a SP it can be used like any table but we cannot modify the parameter since it is readonly. Table Valued Parameters can be used to have multiple values as parameters for the SP that reviously was done using one of the following ways:

  1. Using a series of multiple parameters.

  2. Using delimited string or XML documents and pass those text values to SP.

  3. Creating a series of individual SQL statements that affect multiple rows.

TVPs are defined using the user-defined table types. The table type is used to describe the structure of the TVP. We can see that the TVP are strongly typed.

Using a Table value parameter

  1. Create a Table Type and define the table structure:
    1. Create type CustomerType as Table  
    2. (  
    3.    CustomerID INT  
    4. );  
    5. GO  
  2. Declare a SP that has a parameter of table type:
    1. Create procedure GetAllCustomer  
    2.   
    3. @CustomerIDs_TVP CustomerType READON  
    4. LY  
    5. AS  
    6. Select CustomerID, CustomerName from Customer  
    7. inner join @CustomerIDs_TVP  
    8. on Customer.CustomerID = @CustomerIDs_TVP.CustomerID  
    9. GO  
  3. Using the TVP as parameter with the SP:
    1. DECLARE @CustomerIDs_TVP AS CustomerType  
    2. INSERT INTO @CustomerIDs_TVP (CustomerID) VALUES (1),(2),(3),(4),(5)  
    3. EXEC GetAllCustomer @CustomerIDs_TVP;  
    4. GO  

We can see the output of the preceding executed query is all the customers from Customer table having customerIDs 1, 2, 3, 4 and 5.

Using TVP in C# .NET

  1. DataTable tableCustomerIds = new DataTable();  
  2. tableCustomerIds.Columns.Add("CustomerID"typeof(int));  
  3. tableCustomerIds.Rows.Add(1);  
  4. tableCustomerIds.Rows.Add(2);  
  5. tableCustomerIds.Rows.Add(3);  
  6. tableCustomerIds.Rows.Add(4);  
  7. tableCustomerIds.Rows.Add(5);  
  8. using (SqlConnection conn = newSqlConnection("Server=localhost;Database=MyDB;Trusted_Connection=True;"))  
  9. {  
  10.    SqlCommand cmd = new SqlCommand("GetAllCustomer", conn);  
  11.    cmd.CommandType = CommandType.StoredProcedure;  
  12.    SqlParameter sqlParam = cmd.Parameters.AddWithValue("@CustomerIDs_TVP", tableCustomerIds);  
  13.    cmd.CommandTimeout = 0;  
  14.    sqlParam.SqlDbType = SqlDbType.Structured; //tells ADO.NET we are passing TVP  
  15.    SqlDataAdapter adapter = new SqlDataAdapter(cmd);  
  16.    DataSet sptable = new DataSet();  
  17.    adapter.Fill(sptable);  
  18. }  
This was all about Table Valued Parameters in SQL Server 2008. Please let me know your thoughts about the article.

Up Next
    Ebook Download
    View all
    Learn
    View all