如何在SQL Server 2012中将数据类型从date更改为int?

时间:2015-05-07 11:15:00

标签: sql-server database

我有一张像

这样的表格
CREATE TABLE Student 
(
    s_id int NOT NULL IDENTITY(1,1),
    sname nvarchar(30) NOT NULL,
    address nvarchar(30) NOT NULL,
    gender varchar(10) NOT NULL,
    birthyear date NOT NULL,
    CONSTRAINT PK_Student PRIMARY KEY (s_id)
);

现在,我想将列birthyear的数据类型从date更改为integer

我遵循了w3school.com的教程:

ALTER TABLE table_name
ALTER COLUMN column_name datatype

这是我的代码:

ALTER TABLE Student 
ALTER COLUMN birthyear int

但它会抛出错误

  

操作数类型冲突:日期与int

不兼容
你能帮助我的人吗?请。

谢谢!

2 个答案:

答案 0 :(得分:8)

当列为空(所有NULL)时,您可以使用varchar转换进行过渡步骤。 直接转换是不可能的,但这应该有效:
日期 - > varchar - > INT

ALTER TABLE Student ALTER COLUMN birthyear varchar(200);
ALTER TABLE Student ALTER COLUMN birthyear int;

请参阅this answer

答案 1 :(得分:7)

您无法直接执行此操作 - DATE不是INT - SQL Server如何将2015-05-07之类的日期转换为INT } ??

您基本上有两种选择:

选项#1 :将当前列birthyear重命名为birthdate,然后添加一个计算列birthyear,该列只显示该日期的年份:< / p>

-- rename "birthyear" to "birthdate"
EXEC sp_RENAME 'Student.Birthyear' , 'BirthDate', 'COLUMN'

-- add new computed column "birthyear"
ALTER TABLE dbo.Student 
   ADD BirthYear AS YEAR(birthdate) PERSISTED

选项#2 :创建新列,将日期年份放入该列,删除旧列,将新列重命名为旧名称

-- add new  column "newbirthyear"
ALTER TABLE dbo.Student 
   ADD NewBirthYear INT 

-- update table, extract YEAR(birthyear) into new column
UPDATE dbo.Student
SET NewBirthYear = YEAR(birthyear)

-- drop old column
ALTER TABLE dbo.Student
DROP COLUMN birthyear

-- rename new column back to old column name
EXEC sp_RENAME 'Student.NewBirthyear' , 'BirthYear', 'COLUMN'