Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a table like

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

Now I want to change data type of column birthyear from date to integer.

I followed tutorial of w3school.com :

ALTER TABLE table_name
ALTER COLUMN column_name datatype

Here is my code:

ALTER TABLE Student 
ALTER COLUMN birthyear int

But it throws an error

Operand type clash: date is incompatible with int

Can you people help me? Please.

Thank you!

like image 757
Loint Avatar asked May 07 '15 11:05

Loint


People also ask

How do I change the format of a date in SQL query?

You can specify the format of the dates in your statements using CONVERT and FORMAT. For example: select convert(varchar(max), DateColumn, 13), format(DateColumn, 'dd-MMM-yyyy')

Can you change data type in SQL Server?

You can modify the data type of a column in SQL Server by using SQL Server Management Studio or Transact-SQL. Modifying the data type of a column that already contains data can result in the permanent loss of data when the existing data is converted to the new type.

Is date an integer in SQL?

Is date an integer in SQL? The SQL Server stores both date & time as integers. The date integer stores the no of days elapsed since a base date (which is 1900-01-01). Since Date is internally a integer, we can convert any integer to date using the cast function.


1 Answers

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.

like image 167
wladimirec Avatar answered Sep 17 '22 14:09

wladimirec