Someone mistakenly created a bunch of nchar fields in database tables. I noticed this, and after examining the issue, we're moving these fields to nvarchar types and trimming the values inside.
In my script, I currently have it limited to pull only the tables that have nchar types, assuming that the views that are fed by the tables will know to update their values. Is this assumption correct, or should I be including views in this list as well?
For reference, the script in its current form is below (mostly taken from this great SO answer):
declare @tn nvarchar(128)
declare @cn nvarchar(128)
declare @ln int
declare @sql as nvarchar(1000)
declare c cursor for
select cols.table_name,cols.column_name,cols.character_maximum_length
from information_schema.columns cols
inner join information_schema.tables tabs
on (cols.TABLE_SCHEMA = tabs.TABLE_SCHEMA and cols.TABLE_NAME = tabs.TABLE_NAME)
where cols.data_type ='nchar' and tabs.TABLE_TYPE = 'BASE TABLE'
open c
fetch next from c into @tn, @cn, @ln
while @@FETCH_STATUS = 0
begin
set @sql = 'alter table ' + @tn + ' alter column '
+ @cn + ' nvarchar(' + convert(nvarchar(50), @ln) + ')'
exec sp_executesql @sql
set @sql = 'update ' + @tn + ' set ' + @cn + ' = LTRIM(RTRIM(' + @cn + '))'
exec sp_executesql @sql
fetch next from c into @tn, @cn, @ln
end
close c
deallocate c
References