如果是一个团队项目, 并且没有约定好Collation, 在 MS SQL Server中编程就会遇到这样的问题
Cannot resolve the collation conflict between "Latin1_General_CI_AS" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation.
很简单的一个问题, 就是说因为编码问题,不同编码的字符串并不能直接进行比较, 这种有两个解决方法, 1是在 query中 指定 用某一个collation进行比较, 另外一个就是修改column的 collation type 来避免这种错误…
我这里的处理方法是第二种, 一个一个column改起来很累, 写了个script, 这样除了 被当作 constraints比如 primary key, foreign key之外的 varchar, char,nvarchar 都可以统一修改成一个collation…
以下是代码,简短不解说…
1: declare @CollationName varchar(500);
2:
3: set @CollationName = 'SQL_Latin1_General_CP1_CI_AS'
4:
5: create table #tmp (sqlStr varchar(max));
6:
7: insert into #tmp
8: select 'alter table [' + o.name + '] alter column [' + c.name + ']' +
9: (case c.system_type_id when 167 then ' varchar(' when 175 then ' char(' else ' nvarchar(' end)
10: + convert(varchar,c.max_length) + ') collate ' + @CollationName
11: from sys.columns c,
12: sys.objects o
13: where c.object_id=o.object_id and o.type='U' and c.system_type_id in (167,175,231) and collation_name<>@CollationName
14: and c.name not in (
15: select cc.COLUMN_NAME
16: from
17: INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
18: INFORMATION_SCHEMA.KEY_COLUMN_USAGE cc
19: where
20: cc.TABLE_NAME = pk.TABLE_NAME
21: and cc.CONSTRAINT_NAME = pk.CONSTRAINT_NAME)
22:
23: while (exists (select * from #tmp))
24: begin
25: declare @sqlStr varchar(max);
26: select @sqlStr=(select top 1 sqlstr from #tmp);
27: exec(@sqlStr)
28: delete from #tmp where sqlStr=@sqlStr
29: end
30:
31: drop table #tmp;
32:
33:
34: