我试图创建一个sql脚本,应该检查,看看是否存在一行。如果不存在,我想创建一个;如果存在,我想更新它。
但是,在下面的代码中,INSERT行抛出以下错误:
视图或函数"是不可更新的,因为修改会影响多个基表。
是否有办法找出这将影响其他基表以及如何实现我的目标?
SQL代码:IF NOT EXISTS (SELECT * FROM g4b_stockcountsummary
WHERE g4b_stockcountid = @scid AND g4b_protoproductid = @ppid)
BEGIN
--stock count data doesn't exist for the given product/stock count, create new record
SET @difference = @count - @expectedtotal
INSERT INTO g4b_stockcountsummary (g4b_stockcountsummaryid, g4b_stockcountid, g4b_protoproductid, g4b_expectedtotal, g4b_counttotal, g4b_difference)
VALUES (NEWID(), @scid, @ppid, @expectedtotal, @count, @difference)
END
ELSE
BEGIN
--stock count data already exists for the given product/stock count, update record
DECLARE @originalcount INT
SET @originalcount = (SELECT g4b_counttotal FROM g4b_stockcountsummary
WHERE g4b_stockcountid = @scid AND g4b_protoproductid = @ppid)
SET @count = @originalcount + @count
SET @difference = @count - @expectedtotal
UPDATE g4b_stockcountsummary
SET g4b_expectedtotal = @expectedtotal,
g4b_counttotal = @count,
g4b_difference = @difference
WHERE g4b_stockcountid = @scid
AND g4b_protoproductid = @ppid
END
g4b_stockcountsummary
为视图。视图可以可更新,但只能在某些条件下更新。它们列在文档中,以
可更新视图
可以通过视图修改底层基表的数据,如只要下列条件为真:
- 任何修改,包括
UPDATE
、INSERT
和DELETE
语句,必须只引用一个基表中的列。
因此,你不能做你想做的。您要么需要修复视图,要么需要独立更新每个基表。
我应该指出lad2025是正确的。您可以在视图上使用instead of
触发器来支持update
。文档引用的是视图的基本更新