Monday, 2 June 2014

DataTable as Parameter in sql

Create a User-Defined TableType in your database:

CREATE TYPE [dbo].[TableType] AS TABLE(
[UserId] int NOT NULL,
[UserName] [nvarchar](128) NULL,
[Password] [varchar](30)
) 

define a parameter in your Stored Procedure:

CREATE PROCEDURE [dbo].[InsertTable]
@myTableType TableType readonly
AS
BEGIN
insert into [dbo].Users select * from @myTableType 
END
 
 send your DataTable directly to sql server:
 
 SqlCommand command = new SqlCommand("InsertTable");
 command.CommandType = CommandType.StoredProcedure;
 var dt = new DataTable(); //create your own data table
 command.Parameters.Add(new SqlParameter("@myTableType", dt));
 command.ExecuteNonQuery();