I am trying to use T-SQL to alter a column with data already in it from char to varbinary. This is very easy to do in Enterprise Manager, but just for my own knowledge I'm trying to figure out how to do this in T-SQL. I don't mind losing the data (I'm using a temp table to bring the converted data back in), but I want to keep the column in the same place. Here's what I have so far, but I keep getting an implicit conversion error:
UPDATE UserProfile
SET PassID = CAST(PassID AS VARBINARY(128))
GO
ALTER TABLE UserProfile
ALTER COLUMN PassID VARBINARY(128)
GO
In Enterprise Manager, there is an option to preview the code that will be executed. If you check that you will often find to make a change that is disallowed with simple alters and to keep the column order the same, the table is dropped and recreated. What makes the operation difficult, in the general case, is handling foreign key constraints.
Column order should never be relied on in Tables, but I can understand the desire from a documentation point of view.
The general approach for altering a column's datatype is to:
1. Drop any foreign key constraints.
2. Rename the table to a temporary name.
3. Recreate the table with the new definition.
4. Copy the data back -- setting identity insert if necessary.
5. Recreate all foreign key constraints. (4 and 5 can probably be switched.)
6. Drop the original table.
If you don't care about column order, you can rename the old column, add a new column with the different datatype, transfer the data, and drop the original column.
No comments:
Post a Comment