Since MS SQL Server (like most databases) does not support directly changing the type of an existing column, you will have to do this step by step. The way I solved such problems in the past (if your table is called "foo" and your column is called "bar"):
ALTER TABLE foo ADD COLUMN tempbar text; UPDATE foo SET tempbar = cast(cast(bar as varchar) as text); ALTER TABLE foo DROP COLUMN bar; ALTER TABLE foo ADD COLUMN bar text; UPDATE foo SET bar = tempbar; ALTER TABLE foo DROP COLUMN tempbar;
(Some SQL syntaxes may be disabled, it has been a year since I last did this on a different job, so I donβt have access to MS SQL Server or the source. More if your column has an index on it.)
Confirms Donnie for conversion syntax.
[change]
Tom H. suggested using the sp_rename stored procedure to rename tempbar as bar (instead of steps 4-6). This is a solution for MS SQL Server, which can work in many cases. The solution I described will work (with syntax changes) in any SQL database, regardless of version. In my case, I was dealing with primary and foreign keys, and not just with one field, so I had to carefully organize all operations and be portable in several versions of MS SQL Server - it worked explicitly in my favor.
Craig trader
source share