Thursday, November 10

Cannot resolve collation conflict for equal to operation

I had the error message "Cannot resolve collation conflict for equal to operation" today when exporting tables from one SQL server database into another. It seems this was because the collation settings of the two databases were different.

I found the script below here, which goes through the information_schema.tables object and calls ALTER TABLE to reset all the collation settings on all columns in all tables to the defaults. (I've updated this slightly to reset nvarchar and char columns).


alter procedure p1 as

DECLARE COL_CURSOR CURSOR READ_ONLY FOR
select table_schema, table_name, column_name,
column_default, is_Nullable, Data_type,
character_maximum_length, collation_name
from information_schema.columns

INNER JOIN
(SELECT TABLE_NAME TN FROM
information_schema.tables where
TABLE_TYPE='BASE TABLE' ) IT ON
(TABLE_NAME=TN)
where Data_type = 'varchar' or Data_type =
'nvarchar' or data_type='char'
DECLARE @table_schema varchar(10), @table_name
varchar(100), @column_name varchar(100),
@column_default varchar(100), @is_Nullable
varchar(5), @Data_type varchar(100),
@character_maximum_length varchar(10),
@collation_name varchar(200)

DECLARE @Execstr VARCHAR(2000)
OPEN COL_CURSOR
FETCH NEXT FROM COL_CURSOR INTO @table_schema,
@table_name, @column_name,
@column_default, @is_Nullable, @Data_type,
@character_maximum_length, @collation_name
WHILE (@@fetch_status > -1)
BEGIN
IF (@@fetch_status > -2)
BEGIN
SET @Execstr = 'ALTER TABLE ' + @table_schema
+ '.' + @table_name
+ ' ALTER COLUMN [' + @column_name + '] ' +
@Data_type + ' ('+ @character_maximum_length + ') '
+ CASE WHEN @is_Nullable='no' THEN ' NOT NULL'
ELSE ' NULL ' END
exec (@Execstr)
PRINT ('Executing -->'+ @Execstr )
PRINT ('Orig COLLATION WAS -->'+
@collation_name )

END
FETCH NEXT FROM COL_CURSOR INTO @table_schema,
@table_name, @column_name,
@column_default, @is_Nullable, @Data_type,
@character_maximum_length, @collation_name
END
CLOSE COL_CURSOR
DEALLOCATE COL_CURSOR
GO

2 comments:

Anonymous said...

Does not seem to work when the column is a primary key

Anonymous said...

yeah, or an index, or another constraint...