I'm having a problem when converting all table columns with ntext type in my database. I wrote this query in order to alter my columns, but there is a syntax error:
ALTER TABLE mytable ALTER COLUMN mycolumn
VARCHAR(SELECT MAX(DATALENGTH(mycolumn)) FROM mytable);
Even though SELECT MAX(DATALENGTH(mycolumn)) FROM mytable is returning the correct number, the query cannot be executed.
The syntax error is:
Incorrect syntax near the keyword 'select'.(which is inside the
varchar)
How can I solve the problem?
3 Answers 3
You will need to execute this as dynamic sql because the size of the column cannot be a variable.
DECLARE @Length int = SELECT MAX(DATALENGTH(mycolumn)) FROM mytable
DECLARE @MyTable varchar(100) = 'mytable'
DECLARE @MyColumn varchar(100) = 'mycolumn'
DECLARE @SQL varchar(8000) = 'ALTER TABLE ' + @MyTable +' ALTER COLUMN '+ @MyColumn +' VARCHAR(' + CONVERT(varchar, @Length) + ')'
EXEC(@SQL)
The benefit of this is you could loop over sys.objects and sys.columns to find all ntext columns and convert them to varchar.
Comments
I fear you cannot do this inside an ALTER COLUMN statement. At least I've never seen this.
You should do this way:
Calculate the max data length in that column (you're already doing this):
SELECT MAX(DATALENGTH(mycolumn)) FROM mytable
Now just replace the value you got in the previous query:
ALTER TABLE mytable ALTER COLUMN mycolumn VARCHAR(MAXVALUEFROMPREVIOUSQUERY);
1 Comment
Trying:
SET @maxLength = SELECT MAX(DATALENGTH(mycolumn)) FROM mytable;
ALTER TABLE mytable ALTER COLUMN mycolumn VARCHAR(@maxLength);
ntexttovarcharmight cause data loss, Do you neednvarchar?ntexttovarchar(max_of_length_of_column)all columns in my table. How data loss happens in my case?ntextis double byte andvarcharis (under most collations) single byte so not all characters can be represented.