create trigger TR_testtable on testtable for insert,update as begin update a set a.出生年份=left(出生日期,4) from testtable a,inserted b where a.姓名=b. 姓名 end 用触发器
--只要它日期标准就没有关系 如果不标准left截取也未必准确 --当然最好是日期型的 if not object_id('tb') is null drop table tb Go Create table tb([姓名] nvarchar(2),[出生日期]char(8),出生年份 as year([出生日期])) Insert tb select N'张三','18900107' union all select N'李四','19781201' Go Select * from tb /* 姓名 出生日期 出生年份 ---- -------- ----------- 张三 18900107 1890 李四 19781201 1978(2 個資料列受到影響)*/
insert into testtable(姓名,出生日期, 出生年份) values('姓名',出生日期,Year(出生日期))
on testtable for insert,update
as
begin
update a
set a.出生年份=left(出生日期,4)
from testtable a,inserted b
where a.姓名=b. 姓名
end
用触发器
出生年份 as year(出生日期)
这里的出生日期是char型的,所以要用left(出生日期,4),而不能用year函数
不好意思,错了。可以用year函数
declare @var char(10)
set @var = '20100908'
select year(@var)结果
2010
--当然最好是日期型的
if not object_id('tb') is null
drop table tb
Go
Create table tb([姓名] nvarchar(2),[出生日期]char(8),出生年份 as year([出生日期]))
Insert tb
select N'张三','18900107' union all
select N'李四','19781201'
Go
Select * from tb
/*
姓名 出生日期 出生年份
---- -------- -----------
张三 18900107 1890
李四 19781201 1978(2 個資料列受到影響)*/
values('姓名',出生日期,Year(出生日期))
--做计算列
出生年份 as year(出生日期)
[/Quote]
姓名 char(10), 出生日期 char(10), 出生年份 char(4) as left(出生日期,4))