将用户定义的 Table 传递给存储过程

Pass A User-Defined Table to a Stored Procedure

我有一个用户定义的 Table,我正在将其从存储过程中传递到存储过程中。

DECLARE @tmpInput MyTableType;

--Table is populated from an INPUT XML

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

现在这并没有给我一个错误,但是当我使用 ValidateInputXML 运行 select 时,table 没有数据。

用户定义的范围table在存储过程中。执行存储过程后,将创建并填充 table @tmpInput,之后您将无法访问它。

来自文档:

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.

你有两个选择:

选项 1:

创建一个 table,您可以在其中永久存储记录。

选项 2:

select 存储过程中的记录,如:

alter procedure ValidateInputXML 
DECLARE @tmpInput MyTableType;

--Table is populated from an INPUT XML

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

然后

exec ValidateInputXML 

您还可以为存储过程使用 Table 值参数。 例如。

/* 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