1

I need to change a column type in a SQL Server table.

I need do it using a script or C#.

The original datatype is integer and the new type is varchar(50).

I can do it using this SQL script:

ALTER TABLE confezionamento ALTER COLUMN partnumber varchar(50) 

but the problem is that this column is in a set of primary keys.

When I try do execute, an error occurred because PK_CONFEZIONAMENTO is using the column.

How I can do it without access to SQL Server Management Studio?

2
  • you should remove the c# keywords from this question, as this is sql server related only Commented Apr 25, 2015 at 18:25
  • 1
    While I very much agree with marc_s, I have worked with many projects where the PK is a string rather than utilizing a UNIQUE constraint on the field (in this case part number) and using an INT PK for foreign keys with much faster queries. These decisions for whatever reason often come down from people who don't understand databases. Commented Apr 25, 2015 at 18:27

1 Answer 1

4

You will need to run SQL Commands to do the following steps:

  • Drop primary key constraint
  • Alter primary key
  • Add primary key constraint

If there are any foreign keys or indexes, you may have to deal with them as well.

The commands you are looking for will be similar to these:

Alter table confezionamento drop constraint PK_CONFEZIONAMENTO
ALTER TABLE confezionamento ALTER COLUMN partnumber varchar(50) 
ALTER TABLE confezionamento ADD CONSTRAINT PK_CONFEZIONAMENTO PRIMARY KEY (partnumber)

These commands can all be sent from C# using ADO.Net or similar methods.

Sign up to request clarification or add additional context in comments.

1 Comment

... and to drop the primary key constraint, you first need to find and drop all referencing foreign key constraints, too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.