I have many user-defined-scalar-functions which return varchar(max)
as a result. As a consequence the whole column is varchar(max) even if it consists of only few character strings. I need to convert those varchar(max)
into varchar(N)
to use them as index. I have to do this because indexes are not allowed on varchar(max)
.
Is there an easy and fast way to convert all varchar(max)
columns in a table to varchar(N)
where N is the actual used max length of the variable? Can you please advice how to loop through all the varchar(max)
columns in a table with the code below. The most desirably would be a procedure with the name of a table as a parameter.
declare @SQL varchar(max);
declare @N varchar(max);
set @N = (SELECT max(len([MyColumn])) FROM [dbo].[MyTable])
set @SQL='ALTER TABLE [dbo].[MyTable] ALTER COLUMN [MyColumn] VARCHAR (' + @N +')'
--select @SQL
exec (@SQL)
Update. Alternatively, is there a way to force scalar UDF to return varchar(N) where N would be dynamically adjusted according to the length of the returned string?