给出以下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".
答案 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