January 6, 2010 by Christoff Truter SQL
SQL 2008 introduced a nifty feature called Table-Valued Parameters (TVP) into its codebase.
TVPs allow developers to pass sets of data to a stored procedure (i.e. passing a table to a stored
procedure parameter).
The first thing we need to do, is define a table type, like this:
CREATE TYPE [dbo].[MyFriends] AS TABLE( [firstname] [varchar](50) NOT NULL, [lastname] [varchar](50) NOT NULL )
CREATE TABLE [dbo].[friends]( [friendID] [int] IDENTITY(1,1) NOT NULL, [firstname] [varchar](50) NOT NULL, [lastname] [varchar](50) NOT NULL, CONSTRAINT [PK_friends] PRIMARY KEY CLUSTERED ( [friendID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
CREATE PROCEDURE [dbo].[addFriends] @friends MyFriends READONLY AS BEGIN INSERT INTO friends(firstname, lastname) SELECT firstname, lastname FROM @friends END
using (SqlConnection connection = new SqlConnection(@"Some connectionString")) { using (SqlCommand command = new SqlCommand("addFriends", connection) { CommandType = CommandType.StoredProcedure }) { DataTable dt = new DataTable(); // Add columns dt.Columns.Add("firstname", typeof(String)).MaxLength = 50; dt.Columns.Add("lastname", typeof(String)).MaxLength = 50; ; // Add some rows dt.Rows.Add(new Object[] { "Gerhardt", "Stander" }); dt.Rows.Add(new Object[] { "Roland", "Cooper" }); dt.Rows.Add(new Object[] { "Jacques", "Brits" }); connection.Open(); command.Parameters.Add("@friends", SqlDbType.Structured).Value = dt; command.ExecuteNonQuery(); } }