Question

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

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top