Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Passing a datatable to a Stored Procedure in SQL Server 2008

4.70/5 (11 votes)
25 Jun 2011CPOL 135.6K  
Passing a datatable to a Stored Procedure in SQL Server 2008 which helps improve performance.

Create a table:


SQL
CREATE TABLE dbo.TestTableVariable
(
    ID        INT IDENTITY(1,1)    primary key,
    Name    VARCHAR(10),
    Addr    VARCHAR(10)
)

Create the table data type:


SQL
CREATE TYPE dbo.TableVariable AS TABLE
(
    ID        INT
)

Insert some default data:


SQL
INSERT INTO dbo.TestTableVariable VALUES ('aaa', 'addr-aaa')
INSERT INTO dbo.TestTableVariable VALUES ('bbb', 'addr-bbb')
INSERT INTO dbo.TestTableVariable VALUES ('ccc', 'addr-ccc')
INSERT INTO dbo.TestTableVariable VALUES ('ddd', 'addr-ddd')

Create the Stored Procedure that has the table variable as the parameter:


SQL
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE dbo.SelectTestTableVariable
(
    @TableVar dbo.TableVariable READONLY
)
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT ID, Name, Addr FROM dbo.TestTableVariable
    WHERE ID IN (SELECT ID FROM @TableVar)
        
END
GO

Here is the C# code for a console application:


SQL
static void Main(string[] args)
{
    DataSet dataset = new DataSet();
    DataTable dataTable = new DataTable();
    dataTable.Columns.Add("ID");
    var dr = dataTable.NewRow();
    dr["ID"] = 1;
    dataTable.Rows.Add(dr);
    using (SqlConnection conn = new SqlConnection(
      @"Data Source=.\SqlExpress;Initial Catalog=Work;Integrated Security=True;"))
    {
        conn.Open();       
        using (SqlCommand cmd = new SqlCommand("[dbo].[SelectTestTableVariable]"))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;
            cmd.Parameters.AddWithValue("@TableVar", dataTable);
            using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
            {
                adp.Fill(dataset);
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)