我有一个student表中含有列birthday
birthday
1983-10-20
1985-6-6
1984-5-4
1987-5-1
...
我想增加一列age,来计算年龄,结果:
birthday age
1983-1-2 24
1985-1-1 22
1984-1-1 23
1987-1-1 20
birthday
1983-10-20
1985-6-6
1984-5-4
1987-5-1
...
我想增加一列age,来计算年龄,结果:
birthday age
1983-1-2 24
1985-1-1 22
1984-1-1 23
1987-1-1 20
birthday
1983-1-2
1985-1-1
1984-1-1
1987-1-1
...
我想增加一列age,来计算年龄,结果:
birthday age
1983-1-2 24
1985-1-1 22
1984-1-1 23
1987-1-1 20
--直接用Update更新update 表名 set age = datediff(yy,birthday,getdate())
asexec ('alter table Student add age int')update student set age=datediff(yy,birthday,getdate())
go
我想让他自动的计算,你说的update student set age=datediff(yy,birthday,getdate())中的yy是什么意思?
返回跨两个指定日期的日期和时间边界数。 语法
DATEDIFF ( datepart , startdate , enddate ) 参数
datepart是规定了应在日期的哪一部分计算差额的参数。下表列出了 Microsoft® SQL Server™ 识别的日期部分和缩写。日期部分 缩写
year yy, yyyy
quarter qq, q
Month mm, m
dayofyear dy, y
Day dd, d
Week wk, ww
Hour hh
minute mi, n
second ss, s
millisecond ms
asexec ('alter table Student add age int')update student set age=datediff(yy,birthday,getdate())
go
exec ('alter table Student add age int')?
create table #t(name varchar(100),birthday datetime)
insert into #t select 'aa','1980-2-6'--给表添加公式字段
exec ('alter table #t add age as (datediff(yy,birthday,getdate()))')insert into #t select 'bb','1985-2-6'select * from #tdrop table #t
asexec ('alter table Student add age int')update student set age=datediff(yy,birthday,getdate())
go
服务器: 消息 2705,级别 16,状态 4,行 1
各表中的列名必须唯一。在表 'student' 中多次指定了列名 'age'。
create proc MP1
as
alter table student
add age int
执行:MP1create proc MP2
as
update student
set age=year(getdate())-year(BIRTHDAY)
执行:
MP2结果就可以出来~~~
我试过了,你的方法可以做,但是会出现:
服务器: 消息 2705,级别 16,状态 4,行 1
各表中的列名必须唯一。在表 'student' 中多次指定了列名 'age'。但是结果还是出来了!!!
如何去掉这些错误~~~~~
as--先判断一下列是否存在
exec ('if exists (select * from syscolumns where id=object_id(''Student'') and name=''age'')
alter table Student add age int')update student set age=datediff(yy,birthday,getdate())
go
as--先判断一下列是否存在,如果不存在,才添加列
exec ('if not exists (select * from syscolumns where id=object_id(''Student'') and name=''age'')
alter table Student add age int')update student set age=datediff(yy,birthday,getdate())
go
as
alter table student
add age int
执行:MP1create proc MP2
as
update student
set age=year(getdate())-year(BIRTHDAY)
执行:
MP2和你的代码:create proc test
as
update student set age=datediff(yy,birthday,getdate())
go
哪个比较好?
我只想在我学习SQL的过程中,有个好的朋友帮助我~~~