版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/luo4105/article/details/51347050
以前都是也得mysql,现在写sqlserver的触发器,感觉改动还是蛮大的
1.定义变量
#在mysql中变量直接这么定义就可以了
SET @VALUE = "111";
#在sql server中
declare @count int;
#并赋值
set @count =0;
#如果是查询,必须这么些
select @count = count(*) from WQ_MNINF_D_REAL where STCD=@stcd;
2.判断
在mysql中,if判断的格式 if 条件 then 语句 end if;
而在sql server中,if判断的格式
if(条件) begin 语句 end;
例子
#mysql
IF @VALUE4=1 THEN
INSERT INTO t_sca_history_data (METER_CODE,PARAM_CODE,DATA_VALUE,V_VALUE,DATE_TIME) VALUES
(NEW.METER_CODE,NEW.PARAM_CODE,NEW.DATA_VALUE,NEW.V_VALUE,NEW.DATE_TIME);
END IF;
sql server
if(@count=0)
begin
insert into WQ_MNINF_D_REAL select STCD,TYPE,UPPERVALUE,LOWERVALUE,TM,NT,@smid,@stnm,@prjcd,@pipcd from inserted;
end
3.触发器的new
在mysql中,用new.NAME 可以得到触发器触发插入的值,而sql server不是这样的,sql server是把处罚的数据放在一个临时表中,所以它的操作是这样的
#inserted代表插入数据的那张临时表,同时还有deleted 这张用作删除数据的临时表
select STCD from inserted
#若只是把插入的数据插入另一张表,语句如下
insert into WQ_WWFINF_D_REAL select PRJCD,TM,INFL,SWWL,CWWL,OTPS,OTF,QOEC,PSPPS,NT FROM inserted;
#如果还有加点别的数据,可以这么做
insert into WQ_MNINF_D_REAL select STCD,TYPE,UPPERVALUE,LOWERVALUE,TM,NT,@smid,@stnm,@prjcd,@pipcd from inserted;
4.我做的触发器的代码,改触发器的作用是把原始数据表的数据插入到实时数据表中,如果实时表没有该数据,就插入,如果有,就删除再插入
BEGIN
declare @stcd varchar(30);
declare @count int;
declare @smid int;
declare @stnm varchar(30);
declare @prjcd varchar(30);
declare @pipcd varchar(30);
select @stcd = STCD from inserted;
select @count = count(*) from WQ_MNINF_D_REAL where STCD=@stcd;
select @smid = SMID from WQ_WQSINF_B where STCD=@stcd;
select @stnm = STNM from WQ_WQSINF_B where STCD=@stcd;
select @prjcd = PRJCD from WQ_WQSINF_B where STCD=@stcd;
select @pipcd = PIPCD from WQ_WQSINF_B where STCD=@stcd;
if(@count=0)
begin
insert into WQ_MNINF_D_REAL select STCD,TYPE,UPPERVALUE,LOWERVALUE,TM,NT,@smid,@stnm,@prjcd,@pipcd from inserted;
end
else
begin
delete WQ_MNINF_D_REAL where STCD=@stcd;
insert into WQ_MNINF_D_REAL select STCD,TYPE,UPPERVALUE,LOWERVALUE,TM,NT,@smid,@stnm,@prjcd,@pipcd from inserted;
end
END
这篇博文给我作用挺大的,一并贴出
http://blog.csdn.net/chenbin520/article/details/6026686