这个触发器怎么写?(100分)

  • 主题发起人 主题发起人 htz
  • 开始时间 开始时间
H

htz

Unregistered / Unconfirmed
GUEST, unregistred user!
我用SQL7做后台数据库,是一个主从关系的两个表组成的,主表ID,是主索引,自动加1
的,从表里有ID跟主表对应,ID可以重复,现在想在主表里写一个出发器实现这样的
功能,就是每当主表里加入一条记录的时候,从表里也自动加一个记录,同时这条记录
字段ID值要和主表ID一样,就是对应上,如何写呢,关键是取出主表自动增加的
ID的值,请大家帮忙!!!
 
create trigger.....on 主表
...
insert into 从表(...) select .... from updated;
....
 
不好意思
太久没玩SQL SERVER 了
应该是
insert into 从表(...) select .... from inserted;
id 也取的出的....
 
declare @id int;
select @id=id from inserted

要考虑多行的情况
 
写的详细点!!!!!
 
写的详细点!!!!!
 
Declare @InsertedID int--(视你主标的ID列的类型而定)
内容
@InsertID=@@IDENTITY--(利用该SQL函数取得主标中刚建立的记录的ID好)
接下来就是插入记录了;
可以用select into 语句将结果插入从表
 
select max(xxID) from...就ok了,
紀錄總是一條一條添加的吧,要取出主表自动增加的ID的值,取最大值準沒錯
 
不可以直接取出max(xxID),得用@@IDENTITY
SQL2000直接支持这种主从表的连接。
 
expect:说的详细点!
 
sql2000有级联支持。或
declare @id int
set @id = @@identity
insert into ....
 
CREATE TRIGGER triggername ON tablename
FOR INSERT
AS
declare @userid int
select @userid=id from inserted
insert into tablename (id) values(@userid)
 
scorpions:当一次插入多条记录时你那样写是不行的!

如下:
CREATE TRIGGER triggername ON tablename
FOR INSERT
AS
//if除id其他字段都可为空或有缺省值
insert into tablename (id)
select id from inserted
//else当其他字段为非空且无缺省值,其中defaultvalues用常量代替即可
insert into tablename (id,others)
select id, 'defaultvalues' from inserted
 
正好我刚做过跟这类似的存贮过程,给你参考.

CREATE PROCEDURE intable

AS

insert into lszl(peoplecode,name,sex,mankind,birthday,sbron,citybron,
helth,high,special,workdegree,wherework,dws,dwcity,dwblock,dwrode,
dwcode,dwyb,dwphone,school,expertnow,studydegree,poname,powherework,
poworkdegree,whatcountry,peoplelife,walkroute,countrystay,forignphone,
backupfile,jts,jtcity,jtblock,jtrode,jtcode,jtdy,jtl,jtyb,jtphone,
editdate)
select peoplecode,name,sex,mankind,birthday,sbron,citybron,
helth,high,special,workdegree,wherework,dws,dwcity,dwblock,dwrode,
dwcode,dwyb,dwphone,school,expertnow,studydegree,poname,powherework,
poworkdegree,whatcountry,peoplelife,walkroute,countrystay,forignphone,
backupfile,jts,jtcity,jtblock,jtrode,jtcode,jtdy,jtl,jtyb,jtphone,
editdate
from grzl
where peoplecode in (select peoplecode
from grzlback)

delete
from grzl
where peoplecode in (select peoplecode
from grzlback)

insert into grzl
select *
from grzlback

建议用存储过程,不要用触发器.
 
多人接受答案了。
 
后退
顶部