Changing data type of column in SQL Server

主宰稳场 提交于 2019-12-12 01:22:29

问题


I have to change datatype of a column in SQL Server. So what are the constraints in doing?

I know I have to remove index and other constraints?

Do I have to remove not null check ?

What other things do I have to check before altering the datatype?

I need to remove the constraints and alter the table and then add the constraints again.

Is this the right way to do so ?

DROP INDEX UX_1_COMPUTATION ON  dbo.Computation 

ALTER TABLE dbo.Computation
ALTER COLUMN ComputationID NVARCHAR(25) 

CREATE UNIQUE INDEX UX_1_COMPUTATION ON dbo.Computation (ComputationID);

Here UX_1_COMPUTATION is the unique index name, Computation is the table name and ComputationID is the column name.

Is this correct ?

Update

So if there is a composite index where there are more than one column involved , How do i deal with it ? These indexes contains primary key column with non primary key columns .

When i tried executing the following statement

DROP INDEX UX_2_COMPUTATION ON  dbo.Computation 

ALTER TABLE dbo.Computation
ALTER COLUMN ComputationID NVARCHAR(25) 

CREATE UNIQUE INDEX UX_2_COMPUTATION ON dbo.Computation (ComputationID , ComputeGuid);

It is throwing the following exception

SQL DROP INDEX UX_2_COMPUTATION

        ON dbo.Computation

        ALTER TABLE dbo.Computation

        ALTER COLUMN ComputationID  NVARCHAR(10) Not Null

        CREATE INDEX UX_2_COMPUTATION 

        ON dbo.Computation (ComputationID , ComputeGuid): The object 

'PK_Computation' is dependent on column 'ComputationID '.:

      Caused By: Error executing SQL DROP INDEX UX_2_COMPUTATION 

        ON dbo.Computation

        ALTER TABLE dbo.Computation

        ALTER COLUMN ComputationID  NVARCHAR(10) Not Null

        CREATE INDEX UX_2_COMPUTATION 

        ON dbo.Computation (ComputationID , ComputeGuid): The object 

'PK_Computation' is dependent on column 'ComputationID '.:

      Caused By: The object 'PK_Computation' is dependent on column 'ComputationID '.

Thanks,

-Sam


回答1:


Your current statement will change the column to be a nullable NVARCHAR(25) column - is that what you want?

If you want to be sure that your column is going to be NON NULL, you have to explicitly state this:

ALTER TABLE dbo.Computation
ALTER COLUMN ComputationID NVARCHAR(25) NOT NULL


来源:https://stackoverflow.com/questions/13934265/changing-data-type-of-column-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!