引用 table 值参数时必须声明标量变量

Must declare the scalar variable when referencing a table valued parameter

这个问题来自

以下 SQL 作品:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Update_Repair_Details]
    @RepairID BIGINT,
    @NewDetails NewDetails READONLY
AS
BEGIN
    SET NOCOUNT ON;

    DELETE FROM Repair_Details
    WHERE RepairID = @RepairID

    INSERT INTO Repair_Details
        SELECT *, GETDATE()
        FROM @NewDetails
END

但由于 RepairID 是用户定义的 table 类型中的第一列,因此没有理由将其作为附加参数传递。

于是我写道:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Update_Repair_Details]
    @NewDetails NewDetails READONLY
AS
BEGIN
    SET NOCOUNT ON;

    DELETE FROM Repair_Details
    WHERE RepairID = @NewDetails.RepairID

    INSERT INTO Repair_Details
        SELECT *, GETDATE()
        FROM @NewDetails
END    

导致错误:

Must declare the scalar variable "@NewDetails"

为什么这个有错误,而以前的版本没有?

在这种情况下,@NewDetails 是一个 table;因此,您不能只做 WHERE RepairID = @NewDetails.RepairID。您可以使用 INEXISTSJOIN:

ALTER PROCEDURE [dbo].[Update_Repair_Details]
@NewDetails NewDetails READONLY
AS
BEGIN
    SET NOCOUNT ON;
    DELETE A
    FROM Repair_Details A
    INNER JOIN @NewDetails B
        ON A.RepairID = B.RepairID;

INSERT INTO Repair_Details
SELECT *, GETDATE()
FROM @NewDetails;
END