SqlServer触发器A表中插入一行数据后动态在B表中插入A表中计算后数据
表t_mydata 的列定义如下:
int id ,int station_id, datetime data_time,float LJLL
示例数据:
www.2cto.com
13911834 1 2012-08-19 8:00:00 2039886
13944831 1 2012-08-20 8:00:00 2043351
表t_station 的列定义如下
Int station_id,varchar station_name ,varchar station_detail
示例数据:
1 MD1 铭德二期
2 MD2 铭德一期
表t_point 的列定义如下:
Int point_id,varchar point_name,varchar point_desc,int point_station_id
示例数据:
1 MD1_LJLL 累计流量 1
2 MD2_LJLL 累计流量 2
表t_DTLJ 的定义如下:
Datetime data_time, float MD1_DTLJLL,flaot MD2_DTLJLL
这三个表的关系是:
www.2cto.com
t_point的列point_name的内容是t_station表中station_name列内容加“_”加t_mydata表中数据列的列名。
t_mydata的station_id列 和 t_station表的 station_id列相连接。
t_DTLJ表的数据列的名称是t_station表的station_name列的内容加“_DT”加t_mydata表的LJLL名。
t_mydata表中列LJLL中的值是个累计增大的值。
我现在要求得是,向t_mydata表中插入一条数据后,计算出插入时间的数据和当天8点时的数据的差,将这差值插入到表t_DTLJ表中的对应的列中。
CREATE TRIGGER [CaculateDTLJ] ON [dbo].[t_mydata]
FOR INSERT
AS
declare @time datetime ---插入时间
declare @stationid int ---站点ID
declare @station_name varchar(20) ---站点英文名称
declare @point_name varchar(20) ---点英文名称
declare @minTime datetime --时间段内最小时间
declare @str varchar(20)
DECLARE @sql nvarchar(1000) --动态sql语句
declare @param nvarchar(100)
--将插入的数据的站点ID和插入时间赋值给变量。
select @stationid=station_id,@time=data_time from inserted
--声明游标 从t_point表中查询出所有累计量的点,累计量以LJ为关键字标志
www.2cto.com
并将累计量的名称,拆分为站名称和点名称
DECLARE name_cursor CURSOR
FOR SELECT substring(point_name,0,CHARINDEX('_',point_name)) as 'station_name',substring(point_name,CHARINDEX('_',point_name)+1,len(point_name)-CHARINDEX('_',point_name)) as 'point_name'
FROM t_point WHERE point_station_id= @stationid and point_name like '_%LJ%';
--打开游标
open name_cursor
--读取游标数据
FETCH NEXT FROM name_cursor into @station_name,@point_name
--循环判断游标中是否有数据未读取
WHILE @@FETCH_STATUS = 0
BEGIN
--时间段内最小值
declare @minval float
--时间段内最大值
declare @maxval float
--时间段内差值
declare @val float
set @str=@station_name+'_DT'+@point_name
--判断t_DTLJ表中是否含有列@str
IF COL_LENGTH('t_DTLJ', @str) IS NOT NULL
begin
--查询当天8点时的时间,如果当前时间大于8点,则当天8点时间为当天8点时间。如果当前时间小于8点,则当天8点时间为前一天8点时间。
www.2cto.com
select @minTime=min(data_time) from t_mydata where station_id=@stationid and data_time between (CASE when datepart([hour], @time)=8 and datepart([mi], @time)=0 and datepart([ss], @time)=0 then DATEADD([hour],-16,convert(varchar(10),@time,120)) when datepart([hour], @time)>=8 THEN DATEADD([hour], 8,convert(varchar(10),@time,120)) else DATEADD([hour],-16,convert(varchar(10),@time,120))end) and @time
--查询当天8点和当前时间的记录的差值
select @sql='select @minval=min(isnull('+@point_name+',-1)),@maxval=max(isnull('+@point_name+',-1)) from t_mydata where station_id=@stationid and data_time in(@minTime,@time)'
set @param = '@time datetime,@minTime datetime,@stationid int,@minval float output,@maxval float output'
print @sql
--执行sql语句
exec sp_executesql @sql,@param,@time,@minTime,@stationid,@