加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SQLServer 触发器初探

发布时间:2020-12-12 12:54:52 所属栏目:MsSql教程 来源:网络整理
导读:继上次的SQL Server空间化任务之后, 笔者又接到新的任务: 当数据库属性字段发生变化时,在不改变业务代码的条件下,自动更新空间数据。 首先想到的解决方案就是触发器。 基本思路: ??? 在数据更新或插入完毕之后,当表的x,y字段任意一个的值发生变化时,
字段
类型
说明
videoid
varchar
主键ID
videoname
varchar
摄像机名
clientx
number

经度

clienty
number
纬度
geom
geometry
实际坐标
--?为表增加坐标字段
alter?table?videopointinfo?add?geom?geometry;

--?创建或修改触发器,?创建用create,修改用alter
alter?trigger?tri_videopointinfo?on?videopointinfo
after?update,insert?as
--?当clientx或clienty有更新时调用
if?update(clientx)?or?update(clienty)
begin
????--?当clientx或clienty任意一个有空值时设置geom为空
????if?(select?clientx?from?inserted)?is?null?or?(select?clienty?from?inserted)?is?null
????begin
????????update?v?set?
????geom=null
????from?videopointinfo?v
????where?exists(select?1?from?inserted?where?videoflag=v.videoflag)
????????Return
????end
????
????update?v?set?
????geom=geometry::STGeomFromText('POINT('+convert(varchar,CLIENTX)+'?'+convert(varchar,CLIENTY)+')',4326)
????from?videopointinfo?v
????where?exists(select?1?from?inserted?where?videoflag=v.videoflag)
end

最后可以尝试着更新几条数据,测试效果。

再来条开启和禁用触发器的语句

disable?trigger?trigDB?on?database?--禁用触发器
enable?trigger?trigDB?on?database?--开启触发器

参考文档:msdn - create trigger

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

继上次的SQL Server空间化任务之后,

笔者又接到新的任务:

当数据库属性字段发生变化时,在不改变业务代码的条件下,自动更新空间数据。

首先想到的解决方案就是触发器。

基本思路:

??? 在数据更新或插入完毕之后,当表的x,y字段任意一个的值发生变化时,即开始更新空间字段数据。


下面以摄像机表videopointinfo为例

    推荐文章
      热点阅读