Many times we come across a situation where we need to pass a table to stored procedure from C# code. In such scenarios what we can do is either loop through table and send rows one by one or we can directly pass the full table to the procedure. Passing rows one by one may be inefficient as we have to iterate through rows and call procedure again and again.
SQL Server provides us an efficient way of doing the same using 'User Defined Types' So for passing a table valued parameter to a stored procedure we need to create a user defined table type that will have same columns that we want to pass to the table. Click Database Node > Programmability > Types, then User-Defined Table Types. Now we create a table which will be filled by stored procedure.
SQL Server provides us an efficient way of doing the same using 'User Defined Types' So for passing a table valued parameter to a stored procedure we need to create a user defined table type that will have same columns that we want to pass to the table. Click Database Node > Programmability > Types, then User-Defined Table Types. Now we create a table which will be filled by stored procedure.
- CREATE TABLE [dbo].[Employee](
- [Emp_ID] [int] IDENTITY(1,1) NOT NULL,
- [Emp_name] [varchar](100) NULL,
- [Emp_Sal] [decimal](10, 2) NULL
- ) ON [PRIMARY]
- GO
- CREATE TYPE Employee AS TABLE
- (
- [Emp_ID] [int] IDENTITY(1,1) NOT NULL,
- [Emp_name] [varchar](100) NULL,
- [Emp_Sal] [decimal](10, 2) NULL
- )
- GO
- CREATE PROCEDURE sp_InsertEmployee
- @employees employee READONLY
- AS
- INSERT INTO Employee(Emp_name,Emp_Sal)
- SELECT Emp_name,Emp_Sal
- FROM @employees
- DECLARE @testtable employee
- INSERT INTO @testtable(Emp_name,Emp_Sal)
- VALUES ('Anees', 1000.00),
- ('Rick', 1200.00),
- ('John', 1100.00)
- select * from @testtable
- DECLARE @testtable employee
- INSERT INTO @testtable(Emp_name,Emp_Sal)
- VALUES ('Anees', 1000.00),
- ('Rick', 1200.00),
- ('John', 1100.00)
- exec sp_InsertEmployee @testtable
- select * from Employee


Humayun Kabir MamunPosted Jan 25, 2016, 5:51 PM EST
Nice...
Ankur MistryTOP 100Posted Jan 25, 2016, 5:46 PM EST
Nice share.
Gowtham KTOP 100Posted Jan 25, 2016, 4:08 PM EST
Good One
Yashwant VishwakarmaPosted Jan 24, 2016, 11:55 PM EST
Nice info, thanks for sharing !!
Mohammed IbrahimPosted Jan 24, 2016, 11:35 PM EST
nice
Shubham KumarPosted Jan 24, 2016, 11:00 PM EST
nice share
Debasis SahaTOP 100Posted Jan 24, 2016, 10:27 PM EST
Nice..