Question

Can the datatype of a field be changed to int from nvarchar??

alter table employee alter column designation int

is this valid?? If not can it be done in some other way??

P.S: I am using MS SQL Server

Était-ce utile?

La solution

You can try doing an alter table. If it fails do this:

  1. Create a new column that's an integer:

ALTER TABLE tableName ADD newCol int;

  1. Select the data from the old column into the new one:

UPDATE tableName SET newCol = CAST(oldCol AS int);

  1. Drop the old column

Autres conseils

It is possible only when you column has no value or blank. If your column has some value which have nvarchar value and you should try to convert it into int, it will give error.

ALTER TABLE [table_name] ALTER COLUMN [column_name] [data_type]
  1. Add new numeric column.
  2. Copy from old char column to new column with trim and conversion.
  3. Drop old char column.
  4. Rename numeric column to old column name.

This worked for me (with decimals but I suppose it will work with ints):

alter table MyTable add MyColNum decimal(15,2) null
go
update MyTable set MyColNum=CONVERT(decimal(15,2), REPLACE(LTRIM(RTRIM(MyOldCol)), ',', '.')) where ISNUMERIC(MyOldCol)=1
go
alter table MyTable drop column MyOldCol
go
EXEC sp_rename 'MyTable.MyColNum', 'MyOldCol', 'COLUMN'
go

Can be done even simpler in just 2 steps

  1. Update the column and set all non numberic values to null so alter won't fail.

  2. Alter the table and set the type to int.

UPDATE employee
SET designation = (CASE WHEN ISNUMERIC(designation)=1 THEN CAST(CAST(designation AS FLOAT) AS INT)END )

ALTER TABLE employee
ALTER COLUMN designation INT

This takes the assumption that that the columns allow nulls. If not then that needs to be handled as well. For example: By altering the column to allow null, then after it has been converted to int then set all null values to 0 and alter the table to not allow null

  1. Create a temp column

    ALTER TABLE MYTABLE ADD MYNEWCOLUMN NUMBER(20,0) NULL;

  2. Copy and casts the data from the old column to the new one

    UPDATE MYTABLE SET MYNEWCOLUMN=CAST(MYOLDCOLUMN AS NUMBER(20,0));

  3. Delete the old column

    ALTER TABLE MYTABLE DROP COLUMN MYOLDCOLUMN;

  4. Rename the new one to match the same name as the old one.

    ALTER TABLE MYTABLE RENAME COLUMN MYNEWCOLUMN TO MYOLDCOLUMN;

Can you try this ?

alter table MyTable add MyColNum Varchar(500) null;
alter table MyTable add MyColNum int null;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top