简体   繁体   English

SQL Server 2008触发器

[英]Sql Server 2008 Triggers

Table Message already has a trigger. Message已具有触发器。 Running successfully inside that trigger I have an insert statement: 在触发器内成功运行,我有一条insert语句:

Insert into tblSettlement (MessageID,Lat,Long) Select Messageid,y,x from inserted

On the table tblSettlement I have placed that trigger: 在表tblSettlement我放置了该触发器:

 ALTER TRIGGER [dbo].[AddSettlementOnINSERT]
 ON [dbo].[TblSettlement]
 After INSERT
  AS
 DECLARE @id Bigint, @Lat Float,@Long Float, @LocName Varchar(200), @Dist float,@upd    bit 
 Set @upd = (SELECT updated FROM inserted)
 SET @id = (SELECT MessageID FROM inserted)
SET @lat = (SELECT [Lat] FROM inserted)
SET @Long = (SELECT [Long] FROM inserted)
if (@upd = 0) 
begin
declare @table table 
(Location Varchar(200),Distance float)
insert into @table 
SELECT  top 1 Full_Name_nd, SQRT(
  POWer(69.1 * (lat - @lat), 2) +
   POWer(69.1 * (@long - long) * COS(lat / 57.3), 2))As distance
 FROM geodb.dbo.geonames where SQRT(
  POWer(69.1 * (lat - @Lat), 2) +
  POWer(69.1 * (@Long - long) * COS(lat / 57.3), 2)) < 1 
 set @LocName = (select location from @table)
 set @Dist = (select distance from @table)
 Insert into dbo.tblset2

 (Messageid,lat,long,settlement,distance)values(@id,@lat,@long,@locName,@Dist)
  end

However the problem is that whenever we enable above trigger, insertion stops working on Message table. 但是问题在于,只要启用上述触发器,插入操作就会在Message表上停止。

Meaning: we want to insert, after insertion taking few column values and try to update another table with in the same Table's Trigger. 意思是:我们要在插入后插入一些列值,然后尝试使用同一表的触发器中的另一个表进行更新。 Which actually does not allow us to insert. 实际上不允许我们插入。

Your basic assumption about SQL Server triggers is wrong - you seem to be assuming (as many people do) that the trigger will be called once per row inserted - that is NOT the case! 关于SQL Server触发器的基本假设是错误的-您似乎假设(就像很多人一样)触发器将在插入的每一行被调用一次-事实并非如此!

The trigger will be called once per statement - that is, if your statement insert 20 rows at once, your trigger will be called once , and the pseudo table Inserted will contain 20 rows in it. 每个语句将调用一次触发器-也就是说,如果您的语句一次插入20行,则触发器将被调用一次 ,而Inserted的伪表将包含20行

As such, if Inserted contains multiple rows, your statement here will either fail miserably, or select an arbitrary, random entry: 因此,如果“ Inserted包含多行,则此处的语句将失败或失败,或者选择一个任意的随机条目:

DECLARE @id Bigint, @Lat Float,@Long Float, @LocName Varchar(200), @Dist float,@upd    bit 
Set @upd = (SELECT updated FROM inserted)
SET @id = (SELECT MessageID FROM inserted)
SET @lat = (SELECT [Lat] FROM inserted)
SET @Long = (SELECT [Long] FROM inserted)

You have to rewrite your trigger entirely, taking into account that Inserted can and will contain multiple rows . 考虑到Inserted可以并且将包含多行 ,您必须完全重写触发器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM