Last active
November 20, 2019 09:52
-
-
Save JohnKingsbury/255fa65843b2865e7b4ebcc71d4c5326 to your computer and use it in GitHub Desktop.
TSQL - Converts all NChar fields to NVarChar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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