【问题标题】:How to do trigger which check the latitude and longitude and if latitude and longitude is correct we can insert to database?如何触发检查经纬度,如果经纬度正确,我们可以插入数据库?
【发布时间】:2021-05-20 16:18:06
【问题描述】:

我想创建触发器 wchich 将在插入数据库之前检查经度和纬度,如果经度不正确,则触发器打印一条消息“错误的经度经度必须是 int 间隔所以我的触发器是那个

create trigger t_point_betweenU2
on UserApp
INSTEAD OF insert 
as
begin
SET NOCOUNT ON;
        declare @latitude as float  
        declare @longitude as float 
        declare @Message Varchar(100)
        
        set @latitude = (select u.latitude from UserApp u)
        set @longitude =    (select u.longitude from UserApp u)
        
        Select  @latitude = i.latitude, @longitude = i.longitude
        from inserted i
        if((@latitude >= 19.7922354 and @latitude <= 20.2173455))
            begin
            Set @Message = 'This latitude is incorrect, latitude must be between 19.7922354 and 20.2173455'
                RaisError(@Message, 16, 1)
                RollBack
            end
        else if((@longitude>= 49.9676667 and @longitude <= 50.1261338))
        begin
            Set @Message = 'This longitude is incorrect , longitude must be between 49.9676667 and 50.1261338'
                RaisError(@Message, 16, 1)
                RollBack
            end
        
end
GO

但是当我有这个触发器时,我无法插入我的数据库 有人可以解释为什么当我有这个触发器时我不能插入数据库吗?

【问题讨论】:

  • 为什么使用TRIGGER 而不是CONSTRAINT
  • 另外,您的触发器假设 INSERT 仅包含一行;这根本不是真的。
  • 如果您确实使用了触发器,请至少学习从 cmets 并在您过去的触发器问题中​​提出的建议。并且 PRINT 不应在生产触发器中使用 - 触发器不返回结果集或消息。它们应该只抛出需要由插入过程处理的错误。
  • 期待人们spend time answering you,然后完全无视他们所说的话,这是非常粗鲁的。请仔细阅读The Silent Bug I Find in Most Triggers,然后删除您的触发器并使用约束
  • 好的,我检查了约束,在这种情况下比触发要好,感谢您的帮助

标签: sql-server triggers geospatial


【解决方案1】:

正如我所提到的,根本不要使用TRIGGER,只需使用几个CONSTRAINTs:

ALTER TABLE dbo.UserApp ADD CONSTRAINT chk_latitude CHECK (latitude >= 19.7922354 and latitude <= 20.2173455);
ALTER TABLE dbo.UserApp ADD CONSTRAINT chk_longitude CHECK (longitude >= 49.9676667 and longitude <= 50.1261338);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2013-09-09
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多