Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass A User-Defined Table to a Stored Procedure

I have a User Defined Table that I am passing into a stored procedure from within a stored procedure.

DECLARE @tmpInput MyTableType;

--Table is populated from an INPUT XML

exec ValidateInputXML SELECT * FROM @tmpInput TI WHERE TI.EntryType = 'Attribute';

Now this isn't giving me an error, but when I run a select from with the ValidateInputXML the table has no data.

like image 332
Steven Avatar asked May 28 '15 19:05

Steven


People also ask

Can you pass a table to a stored procedure?

Table-Valued Parameters aka TVPs are commonly used to pass a table as a parameter into stored procedures or functions. They are helpful in a way, we can use a table as an input to these routines and we can get rid of dealing more complex steps to achieve this process.

How do you execute a stored procedure with user-defined table type in SQL?

First a Table Variable of User Defined Table Type has to be created of the same schema as that of the Table Valued parameter. Then it is passed as Parameter to the Stored Procedure and the Stored Procedure is executed using the EXEC command in SQL Server.

Can we pass table as parameter in function?

Table names can't be parameters unless you use dynamic SQL, and dynamic SQL can't be used inside of a function. You could use a stored procedure: CREATE OR ALTER PROCEDURE dbo.


1 Answers

You can also use Table-Valued parameter for your stored procedure. E.g.

/* Create a table type. */
CREATE TYPE MyTableType AS TABLE 
( Column1 VARCHAR(50)
, ........ );
GO

/* Create a procedure to receive data for the table-valued parameter. */
CREATE PROCEDURE dbo. ValidateInputXML
    @TVP MyTableType READONLY
    AS 
     -- Do what ever you want to do with the table received from caller
    GO

/* Declare a variable that references the type. */
DECLARE @myTable AS MyTableType;

-- Fill @myTable with data and send it to SP. 
insert into @myTable SELECT * FROM @tmpInput TI WHERE TI.EntryType = 'Attribute';


/* Pass the table variable data to a stored procedure. */
EXEC ValidateInputXML @myTable ;
GO
like image 116
vendettamit Avatar answered Dec 14 '22 07:12

vendettamit