views:

2623

answers:

5

I have a column which has a datatype : datetime. But now i want to convert it to datatype varchar. Can i alter the datatype without droppping the column? If yes, then please explain how?

A: 

ALTER TABLE your_table_name MODIFY your_column_name varchar(100);

jcapote
Gives error : Incorrect syntax near 'columnname' on execution.
Samiksha
Wrong platform...
gbn
A: 

ALTER tablename MODIFY columnName newColumnType

I'm not sure how it will handle the change from datetime to varchar though, so you may need to rename the column, add a new one with the old name and the correct data type (varchar) and then write an update query to populate the new column from the old.

http://www.1keydata.com/sql/sql-alter-table.html

Jesse Pepper
Gives error : Incorrect syntax near 'columnname' on execution.
Samiksha
where i wrote columnName you need to be using the name of the column.. are you doing that? If it still fails it may be an indication that it doesn't work for converting datetime to varchar
Jesse Pepper
Thats what i am trying to tell you, modify doesnt work for mssql 2005
Samiksha
Jesse's suggestion of renaming and adding a new column is exactly what you need to do.
OJ
No. The OP asked for MSSQL
gbn
+3  A: 

MSDN says

ALTER TABLE mytable ALTER COLUMN mycolumn newtype

Beware of the limitations of the ALTER COLUMN clause listed in the article

devio
+1  A: 

ALTER TABLE YourTableNameHere ALTER COLUMN YourColumnNameHere VARCHAR(20)

Leon Tayson
+2  A: 

If ALTER COLUMN doesn't work.

It is not unusual for alter column to fail because it cannot make the transformation you desire. In this case, the solution is to create a dummy table TableName_tmp, copy the data over with your specialized transformation in the bulk Insert command, drop the original table, and rename the tmp table to the original table's name. You'll have to drop and recreate the Foreign key constraints and, for performance, you'll probably want to create keys after filling the tmp table.

Sound like a lot of work? Actually, it isn't.

If you are using SQL Server, you can make the SQL Server Management Studio do the work for you!

Bring up your table structure (right-click on the table and select "Modify") and make all of your changes (if the column transformation is illegal, just add your new column - you'll patch it up in a moment). Next, right-click on the background of the Modify window and select "Generate Change Script." In the window that appears, you can copy the change script to the clipboard.

Cancel the Modify (you'll want to test your script, after all) and then paste the script into a new query window. Modify as necessary (e.g. add your transformation while removing the field from the tmp table declaration) and you now have the script necessary to make your transformation.

Mark Brittingham