问题
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.
回答1:
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
回答2:
The scope of the user defined table is in the stored procedure. Once the stored procedure is executed the table @tmpInput is created and populated and after that you cannot access it.
From the docs:
The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.
You have two options:
OPTION 1:
Create a table in which you can store the records permanently.
OPTION 2:
select the records from inside the stored procedure like :
alter procedure ValidateInputXML
DECLARE @tmpInput MyTableType;
--Table is populated from an INPUT XML
SELECT * FROM @tmpInput TI WHERE TI.EntryType = 'Attribute';
and then
exec ValidateInputXML
来源:https://stackoverflow.com/questions/30515297/pass-a-user-defined-table-to-a-stored-procedure