Randel Ramirez
Randel Ramirez

Reputation: 3761

Is it possible to use in C#/SQL Server a table variable as a parameter for stored procedures?

I'm aware that I can use a table value parameter as another option and I was already able to implement it. The reason I'm trying to use this approach(Table variable not Table value) is because I'm studying and I want to learn other ways on how to insert to database through a stored procedure.

Here's the current query I have:

CREATE PROCEDURE TVar
(
DECLARE @TblVar TABLE
(Product nvarchar(max), Qty int)

)
AS
Insert Into sample_tbl Select * FROM @TblVar

Is it possible to have this kind of approach wherein in the C# code I will use a datatable to pass as a parameter which can be done when using a table value parameter. I'm having errors when execute the query .

Here's the error:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'DECLARE'.
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near ')'.

Upvotes: 0

Views: 5477

Answers (1)

Mitch Wheat
Mitch Wheat

Reputation: 300559

Yes. You can use a table value parameter as a parameter to a stored procedure, and you can call from C#.

You need to separately declare a TABLE TYPE:

CREATE TYPE MyTableType AS TABLE 
(
    Product nvarchar(max),
    Qty int
);
GO

and then use like so:

CREATE PROCEDURE TVar   
(   
   @TblVar as dbo.MyTableType READONLY  
)   
AS  
...

These articles show how to build a .NET DataTable to call the stored procedure from C#:

Upvotes: 6

Related Questions