读书人

如何建约束(SQL2000)

发布时间: 2012-08-14 10:39:58 作者: rapoo

怎么建约束(SQL2000)

SQL code
if object_id('[a]') is not null drop table [a]create table a(    [id] int not null IDENTITY(1,1),    age int)if object_id('[b]') is not null drop table [b]create table b(    [id] int not null IDENTITY(1,1),    age datetime)insert into a (age) values (12)insert into b (age) values ('2000-01-01')go Select * From aSelect * From b/*目的:用约束的方式实现当b表age字段修改时相应的更新a表的age字段。      比如2001-01-01改成1999-01-01则a表age应该变成13*/




[解决办法]
可以用触发器么?
[解决办法]
SQL code
 /*这个约束能实现吗? 还是用触发器吧*/ create trigger tr_b_update on b for update as begin          update a set age = d.age     from a s inner join      (select id ,datediff(year,age,getdate()) as age from inserted) d on s.id = d.id             end
[解决办法]
写个触发器的,约束好像实现不了
SQL code
create trigger tri_b_updon bfor updateasif update(age)begin  update a set age=datediff(yy,i.age,getdate())  from inserted i  where a.id=i.idendgoupdate b set age='1999-01-01' where id=1goselect * from a/**id          age----------- -----------1           13(1 行受影响)**/
[解决办法]
SQL code
CREATE Trigger tr_b_updateon bfor updateasif update(age)begin  update a           set age=datediff(year,x.age,getdate())          from inserted x            where a.id=x.idendgo 

读书人网 >SQL Server

热点推荐