从 Select 查询中将数据分配给用户定义的 Table 类型?

Assign Data to a User-Defined Table type from Select Query?

我有一个存储过程,它从多个 table 中检索三列。我想在用户定义的多值 table 中获取结果并将变量传递给另一个过程以对变量数据执行操作。

但是它不起作用。知道为什么它不起作用吗?

--This is the initial stored procedure
Create Procedure spSelectData
AS
BEGIN
    Select 
        Userid, first_date, last_update
    From Users
END

--This is to create the table type.
Create type Task1TableType AS TABLE
(
     Userid nvarchar(20),
     First_date datetime,
     Last_update datetime
)

--Declare a table of type 
DECLARE @firstStep AS Task1TableType
(
    Userid nvarchar(20),
    First_date datetime,
    Last_update datetime
)

Insert @firstStep EXEC spSelectData

Select * from @firstStep

-- This is the procedure 1
CREATE PROC spTest1
   @TTType Task1TableType READONLY
AS
BEGIN
    Select * from @TTType
END

问题在这里:

DECLARE @firstStep AS Task1TableType
(
    Userid nvarchar(20),
    First_date datetime,
    Last_update datetime
)


Insert @firstStep
EXEC spSelectData;

应该是:

DECLARE @firstStep AS Task1TableType;

Insert INTO @firstStep
EXEC spSelectData;

EXEC spTest1
  @firstStep;

不需要在定义类型的地方定义列,INSERT需要INTO子句。之后更改您的代码即可。

SqlFiddleDemo