4

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
  • Have updated re your question Apr 15, 2009 at 10:36

3 Answers 3

4

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

1
  • Indeed: this works fine ALTER TABLE TableName ALTER COLUMN ColumnName nvarchar(max) null Apr 15, 2009 at 9:23
3

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'
4
  • Is there any way to use this query for all the table in the database without going through each table individually Apr 15, 2009 at 10:20
  • In a word: no. But it would be easy to script the above out using a SELECT from info-schema-tables. Apr 15, 2009 at 10:27
  • how can i remove foreign key constraint to alter the table because it is causing error Apr 15, 2009 at 13:16
  • 1
    You have a foreign key on a text column? Is that even legal? No: I don't have an easy answer to that... Apr 15, 2009 at 13:47
0

In MySQL, the query is:

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.