Skip to content

Instantly share code, notes, and snippets.

@JohnKingsbury
Last active November 20, 2019 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnKingsbury/255fa65843b2865e7b4ebcc71d4c5326 to your computer and use it in GitHub Desktop.
Save JohnKingsbury/255fa65843b2865e7b4ebcc71d4c5326 to your computer and use it in GitHub Desktop.
TSQL - Converts all NChar fields to NVarChar
declare @tn nvarchar(128)
declare @cn nvarchar(128)
declare @ln int
declare @sql as nvarchar(1000)
declare c cursor for
select table_name,column_name,character_maximum_length
from information_schema.columns
where data_type ='nchar' and
TABLE_NAME not in (select TABLE_NAME from INFORMATION_SCHEMA.VIEWS)
open c
fetch next from c into @tn, @cn, @ln
while @@FETCH_STATUS = 0
begin
BEGIN TRY
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
END TRY
BEGIN CATCH
PRINT 'Error converting ' + @cn
END CATCH
fetch next from c into @tn, @cn, @ln
end
close c
deallocate c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment