一张表t,表头如下:
-----------------
Id Code Num
-----------------
希望当执行如下的插入语句:
insert into t values('1','A1',2)
insert into t values('1','A1',3)
insert into t values('1','B1',4)
insert into t values('1','B1',5)
后能得到如下结果:
-----------------
Id Code Num
-----------------
1 A1 5
1 B1 9就是当有相同的Id和Code列时合并Num值,修改表时也一样,如何用触发器绑定实现呢
-----------------
Id Code Num
-----------------
希望当执行如下的插入语句:
insert into t values('1','A1',2)
insert into t values('1','A1',3)
insert into t values('1','B1',4)
insert into t values('1','B1',5)
后能得到如下结果:
-----------------
Id Code Num
-----------------
1 A1 5
1 B1 9就是当有相同的Id和Code列时合并Num值,修改表时也一样,如何用触发器绑定实现呢
解决方案 »
- sql2008 r2 错误5123
- 请问如何在pub数据库下写查询语句?在哪写?
- 设置id号从10000开始自动增长
- 求一sql语句写法:用当前日前的年份减去数据库表 userinfo 中字段 bornyear 生成此人的年龄,要如何写呢
- 数据类型nvarchar与varchar到底有什么本质上的差别?
- 如果实现我传入一个由id组成的字符串,从函数返回其名称字符串,他们的格式都是由逗号分隔。
- 对Text型字段如何进行读出和存取?
- 请教SQLServer2000安装后企业管理器无法使用
- 一个表中某一列的值进行分组,划分成多列。
- [在线求教]如何将一列的数据,根据某一列分组后,合并到一个列中
- 这个存储过程怎么写啊
- 问几个简单问题,在线等答案
if not object_id('tb') is null
drop table tb
Go
Create table tb([Id] int,[Code] nvarchar(2),[Num] int)
Insert tb
select 1,N'A1',1
Go
Select * from tb
create trigger t1
on tb
instead of insert
as
if exists(select 1 from tb ,inserted where tb.id=inserted.id and tb.code=inserted.code)
begin
update tb
set num=num+(select num from inserted where tb.id=inserted.id and tb.code=inserted.code)
end
else
insert into tb
select * from inserted
-->>
insert into tb
select 1,'a1',2select * from tb1 A1 3
-->>
insert into tb
select 2,'a1',2select * from tb
1 A1 3
2 a1 2这个问题问第三遍了吧
instead of insert
as
if exists(select * from inserted a,t where a.id=t.id and a.code=t.code)
update t set num=t.num+a.num
from t,inserted where a.id=t.id and a.code=t.code
else
insert into t (id,code,num) select id,code,num from inserted
Create table T([Id] int,[Code] nvarchar(2),[Num] int)
go
create trigger tr_t on t
instead of insert
as
update t
set Num=t.Num+i.Num
from
(select ID,Code,sum(Num)Num from inserted group by ID,Code)i
where
t.ID=i.ID and t.Code=i.Codeinsert t
select
ID,Code,sum(Num)Num from inserted i
where
not exists(select 1 from t where t.ID=i.ID and t.Code=i.Code)
group by ID,Codego
insert into t values('1','A1',2)
insert into t values('1','A1',3)
insert into t values('1','B1',4)
insert into t values('1','B1',5) select * from t/*
Id Code Num
----------- ---- -----------
1 A1 5
1 B1 9(2 行受影响)
*/