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!
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')
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? 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With