Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. DECLARE @collate nvarchar(100);
  2. DECLARE @table nvarchar(255);
  3. DECLARE @column_name nvarchar(255);
  4. DECLARE @column_id int;
  5. DECLARE @data_type nvarchar(255);
  6. DECLARE @max_length int;
  7. DECLARE @row_id int;
  8. DECLARE @sql nvarchar(max);
  9. DECLARE @sql_column nvarchar(max);
  10. DECLARE @is_Nullable bit;
  11. DECLARE @null nvarchar(25);
  12.  
  13. SET @collate = 'Latin1_General_CI_AS';
  14.  
  15. DECLARE local_table_cursor CURSOR FOR
  16.  
  17. SELECT [name]
  18. FROM sysobjects
  19. WHERE OBJECTPROPERTY(id, N'IsUserTable') = 1
  20.  
  21. OPEN local_table_cursor
  22. FETCH NEXT FROM local_table_cursor
  23. INTO @table
  24.  
  25. WHILE @@FETCH_STATUS = 0
  26. BEGIN
  27.  
  28. DECLARE local_change_cursor CURSOR FOR
  29.  
  30. SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
  31. , c.name column_name
  32. , t.Name data_type
  33. , c.max_length
  34. , c.column_id
  35. , c.is_nullable
  36. FROM sys.columns c
  37. JOIN sys.types t ON c.system_type_id = t.system_type_id
  38. LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
  39. LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
  40. WHERE c.object_id = OBJECT_ID(@table)
  41. ORDER BY c.column_id
  42.  
  43. OPEN local_change_cursor
  44. FETCH NEXT FROM local_change_cursor
  45. INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_nullable
  46.  
  47. WHILE @@FETCH_STATUS = 0
  48. BEGIN
  49.  
  50. IF (@max_length = -1) SET @max_length = 4000;
  51. set @null=' NOT NULL'
  52. if (@is_nullable = 1) Set @null=' NULL'
  53. if (@Data_type='nvarchar') set @max_length=cast(@max_length/2 as bigint)
  54. IF (@data_type LIKE '%char%')
  55. BEGIN TRY
  56. SET @sql = 'ALTER TABLE ' + @table + ' ALTER COLUMN [' + rtrim(@column_name) + '] ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate + @null
  57. PRINT @sql
  58. EXEC sp_executesql @sql
  59. END TRY
  60. BEGIN CATCH
  61. PRINT 'ERROR: Some index or contraint rely on the column ' + @column_name + '. No conversion possible.'
  62. PRINT @sql
  63. END CATCH
  64.  
  65. FETCH NEXT FROM local_change_cursor
  66. INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_Nullable
  67.  
  68. END
  69.  
  70. CLOSE local_change_cursor
  71. DEALLOCATE local_change_cursor
  72.  
  73. FETCH NEXT FROM local_table_cursor
  74. INTO @table
  75.  
  76. END
  77.  
  78. CLOSE local_table_cursor
  79. DEALLOCATE local_table_cursor
  80.  
  81. GO
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement