消息 512,级别 16,状态 1,过程 trg_pricebase,第 13 行子查询返回了超过 1 个值

Msg 512, Level 16, State 1, Procedure trg_pricebase, Line 13 Subquery returned more than 1 value

how to solve this kind of probe help me please:

错误:

Msg 512, Level 16, State 1, Procedure trg_pricebase, Line 13 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been terminated.


我的触发器是:

ALTER TRIGGER [dbo].[trg_pricebase]
ON  [dbo].[tbl_model2]        
AFTER UPDATE
AS 
   BEGIN

                DECLARE @price_base NVARCHAR(50) = (SELECT tbl_model2.price_base FROM tbl_model2)
                DECLARE @tipid  int = (SELECT tbl_model2.id FROM tbl_model2)


                INSERT INTO tbl_price_history (tbl_price_history.price_base,tbl_price_history.tipid)
                VALUES (@price_base, @tipid )

    END

执行以下 [sub] 查询以查看查询 return 多于一行:

SELECT tbl_model2.price_base FROM tbl_model2
SELECT tbl_model2.id FROM tbl_model2

我假设您想将旧值(table 删除)或新值(table 插入)插入到 *history table 中:

ALTER TRIGGER [dbo].[trg_pricebase]
ON  [dbo].[tbl_model2]        
AFTER UPDATE
AS 
BEGIN
    INSERT  INTO tbl_price_history (price_base, tipid)
    SELECT  price_base, tipid
    FROM    deleted -- for old values
    -- or FROM  inserted -- for new values
END

参考文献:inserted and deleted table

我的灵力告诉我你想要

alter trigger[dbo].[trg_pricebase] on [dbo].[tbl_model2]after update as 
begin
    insert into dbo.tbl_price_history (
        price_base,
        tipid
    ) select
        price_base,
        id
    from
        inserted
end

你有两个基本问题。 首先,要只读取受更新语句影响的行,请使用 inserteddeleted 伪表。 其次,一个触发器可以触发多行,你不能假设只有一个受影响的行。

当您为变量赋值时,您不应该使用您在查询中遵循的方法。

DECLARE @price_base NVARCHAR(50) = (SELECT tbl_model2.price_base FROM tbl_model2)

括号 returns 中的此 select 语句是一个结果集,不是单个值,不能存储到变量中(table 数据类型变量除外)。这种方法千万别练,这样总会报错。

您应该始终使用

select top 1 @price_base = price_base FROM tbl_model2

当您插入多行时,将值赋给触发器内的变量会导致您丢失数据。