create trigger DianT on dianbiaoS
for insert
as
begin
declare @nyr datetime, @count int, @device nvarchar(10), @sum real, @dt date
select @device = device,@dt = dt from inserted
select @nyr = CONVERT(varchar(10),(@dt),120)
select @count = COUNT(*) from dianbiaoT where device = @device and dt = @nyr
select @Sum = SUM(Cha) from dianbiaoS where datediff(day,dt,@nyr)=0 and device = @device
if @count > 0
begin
update dianbiaoT set Tian=@sum where device = @device and dt = @nyr
end
else
begin
insert into dianbiaoT (dt, device, Tian) values (@nyr, @device, @sum)
end
end
CREATE TABLE [dbo].[dianbiaoS](
[id] [int] IDENTITY(1,1) NOT NULL,
[dt] [datetime] NULL,
[device] [nvarchar](10) NULL,
[Cha] [real] NULL
) ON [PRIMARY]
GO
优化思路:
1、select @count 这条语句可以变成Exist,性能会大大提升。按照你的代码,其实这样的记录是唯一的吧?
2、后面的update和insert语句可以合并,可以简单的提升性能。
create trigger DianT on dianbiaoS for insert as begin declare @nyr datetime, @device nvarchar(10), @sum real, @dt date select @device = device,@dt = dt from inserted select @nyr = CONVERT(varchar(10),(@dt),120) if exist(select * from diabiaoT where device = @device and dt=@nyr) begin update dianbiaoT set Tian=Sum(select sum(Cha) from dianbiaoS where datediff(day, dt, @nry)=0 and device=@device) where device@device and dt=@nyr else begin inert into dianbiaoT (dt, device, Tian) values (@nyr, @device, select Sum(Cha) from dianbiaoS where datediff(day, dt, @nry) = 0 and device=@device)) end
插入或修改数据的时候还是太慢了, 为什么我把这句 select sum(Cha) from dianbiaoS where datediff(day, dt, @nry)=0 and device=@device 中的 dianbiaoS 替换成 inserted 后 sum 值就是错的
@Summer丿文: 不知道你所谓的慢是什么意思。作为数据库级别的操作,我给你的代码虽然也还存在优化的空间,但是性能不应该有大影响,如果确实存在,那就是你的系统性能的问题了。
此外,我不明白你的业务逻辑,为什么有逻辑条件 datediff(day, dt, @nry) = 0 。从你的代码来说,这个条件跟 device=@device组合后的记录应该是唯一的,此时,你完全不必要使用sum这个指令,毕竟聚合操作是相对消耗资源的。
奇怪的是,难道你的dianbiaoS里,按日期(dt)和设备(device)这两个字段检索会出现重复的数据?如果是,那么,我给你的代码确实还有一些很大的优化(但这个所谓的很大的优化也不应该有你后面的抱怨:还是太慢了)。
create trigger DianT on dianbiaoS for insert as begin declare @theDate datetime, @device nvarchar(10), @cha real select @device = device,@theDate = date(dt), @cha=real from inserted if exist(select dt from diabiaoT where device = @device and date(dt)=date(@theDate)) begin update dianbiaoT set Tian=Tian+@cha where device@device and date(dt)=date(@theDate) else begin inert into dianbiaoT (dt, device, Tian) values (date(@theDate), @device, @cha) end end
能加你企鹅聊吗,我现在暂时发不了图片,
@Summer丿文: 68558710
@519740105:
create trigger DianT on dianbiaoS for insert as begin declare @theDate datetime, @device nvarchar(10), @cha real select @device = device,@theDate = convert(nvarchar(10), dt, 120), @cha=isnull(cha, 0) from inserted if exist(select dt from diabiaoT where device = @device and dt=@theDate) begin update dianbiaoT set Tian=Tian+@cha where device=@device and dt=@theDate else begin inert into dianbiaoT (dt, device, Tian) values (@theDate, @device, @cha) end end
IN适合于外表大而内表小的情况;EXISTS适合于外表小而内表大的情况