Must declare the scalar variable when referencing a table valued parameter

巧了我就是萌 提交于 2019-12-24 08:19:04

问题


This question follows from this one.

The following SQL works:

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

But since RepairID is the first column in the user-defined table type, there is no reason to pass it as an additional parameter.

Thus I wrote:

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    

which causes an error:

Must declare the scalar variable "@NewDetails"

Why does this have the error while the previous version does not?


回答1:


In this case, @NewDetails is a table; as such, you can't just do WHERE RepairID = @NewDetails.RepairID. You can use IN, EXISTS or a JOIN:

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


来源:https://stackoverflow.com/questions/45805242/must-declare-the-scalar-variable-when-referencing-a-table-valued-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!