views:

2510

answers:

3

hi,I am trying to rename the column datatype from text to ntext but getting error

Msg 4927, Level 16, State 1, Line 1
Cannot alter column 'ColumnName' to be data type ntext.

query that i m using is as follows:-

alter table tablename alter column columnname ntext null
+1  A: 

I expect you'll need to copy the data out - i.e. add a scratch column, fill it; drop the old column; add the new column, copy the data back, remove the scratch column:

ALTER TABLE TableName ADD tmp text NULL
GO
UPDATE TableName SET tmp = ColumnName
GO
ALTER TABLE TableName DROP COLUMN ColumnName
GO
ALTER TABLE TableName ADD ColumnName ntext NULL
GO
UPDATE TableName SET ColumnName = tmp
GO
ALTER TABLE TableName DROP COLUMN tmp


For applying database-wide, you can script it out from info-schema (note you should filter out any system tables etc):

SELECT 'ALTER TABLE [' + TABLE_SCHEMA + '].[' + TABLE_NAME+ '] ADD [__tmp] text NULL
GO
UPDATE [' + TABLE_SCHEMA + '].[' + TABLE_NAME+ '] SET [__tmp] = [' + COLUMN_NAME + ']
GO
ALTER TABLE [' + TABLE_SCHEMA + '].[' + TABLE_NAME+ '] DROP COLUMN [' + COLUMN_NAME + ']
GO
ALTER TABLE [' + TABLE_SCHEMA + '].[' + TABLE_NAME+ '] ADD [' + COLUMN_NAME + '] ntext ' +
    CASE IS_NULLABLE WHEN 'YES' THEN 'NULL' ELSE 'NOT NULL' END + '
GO
UPDATE [' + TABLE_SCHEMA + '].[' + TABLE_NAME+ '] SET [' + COLUMN_NAME + '] = [__tmp]
GO
ALTER TABLE [' + TABLE_SCHEMA + '].[' + TABLE_NAME+ '] DROP COLUMN [__tmp]'
FROM INFORMATION_SCHEMA.COLUMNS WHERE DATA_TYPE = 'text'
Marc Gravell
Is there any way to use this query for all the table in the database without going through each table individually
Vinay Pandey
In a word: no. But it would be easy to script the above out using a SELECT from info-schema-tables.
Marc Gravell
how can i remove foreign key constraint to alter the table because it is causing error
Vinay Pandey
You have a foreign key on a text column? Is that even legal? No: I don't have an easy answer to that...
Marc Gravell
+3  A: 

Conversion not allowed. Add new column as ntext then copy converted data to new column, then delete old column. Might consume a lot of diskspace if it's a large table! You should use NVARCHAR(MAX) instead of NTEXT which will not be supported in the future.

Msg 4927

Joakim Backman
Indeed: this works fine ALTER TABLE TableName ALTER COLUMN ColumnName nvarchar(max) null
Marc Gravell
A: 

In MySQL, the query is:

ALTER TABLE [tableName] CHANGE [oldColumnName] [newColumnName] [newColumnType];

Dimitri C.