How to change data type from date to int in SQL Server 2012? How to change data type from date to int in SQL Server 2012? database database

How to change data type from date to int in SQL Server 2012?


When column is empty (all NULLs) you can make transitional step by using varchar conversion.Direct conversion is not possible, but this should work:
date -> varchar -> int

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

See this answer.


You can't do this directly - a DATE isn't an INT - how should SQL Server convert a date like 2015-05-07 into an INT ??

You have basically two options:

Option #1: rename the current column birthyear to birthdate and add a computed column birthyear that gives you the year only of that date:

-- 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

Option #2: create new column, put the year of your date into that column, drop old column, rename new column to old name

-- add new  column "newbirthyear"ALTER TABLE dbo.Student    ADD NewBirthYear INT -- update table, extract YEAR(birthyear) into new columnUPDATE dbo.StudentSET NewBirthYear = YEAR(birthyear)-- drop old columnALTER TABLE dbo.StudentDROP COLUMN birthyear-- rename new column back to old column nameEXEC sp_RENAME 'Student.NewBirthyear' , 'BirthYear', 'COLUMN'