如何使用表类型上的字段?

时间:2019-02-19 10:34:18

标签: tsql stored-procedures

给出以下SQL用户定义的表类型:

CREATE TYPE IntegerIdTableType AS TABLE
(
    Id INT IDENTITY NOT NULL,
    PRIMARY KEY(Id)
);

在存储过程中将类型用作参数时,如何使用Id字段?

CREATE PROCEDURE FindPencilsForPencilCases
    @pencilCaseIds dbo.IntegerIdTableType READONLY
AS
BEGIN
    SELECT *
    FROM Pencils
    INNER JOIN @pencilCaseIds ON @pencilCaseIds.Id = Pencils.PencilCaseId
END

如果我只运行SELECT * FROM @pencilCaseIds,我可以使以上代码运行,但是如果我引用Id字段,则会得到以下异常:

Must declare the scalar variable "@pencilCaseIds".

1 个答案:

答案 0 :(得分:2)

您需要为表值参数添加别名:

CREATE PROCEDURE FindPencilsForPencilCases
    @pencilCaseIds dbo.IntegerIdTableType READONLY
AS
BEGIN
    SELECT *
    FROM Pencils
    INNER JOIN @pencilCaseIds AS tvp 
        ON tvp.Id = Pencils.PencilCaseId
END