在一個(gè)團(tuán)隊(duì)項(xiàng)目中,沒(méi)有約定好Collation, 在 MS SQL Server中編程就會(huì)遇到這樣的問(wèn)題:
Cannot resolve the collation conflict between "Latin1_General_CI_AS" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation.
因?yàn)榫幋a問(wèn)題,不同編碼的字符串并不能直接進(jìn)行比較,這種有兩個(gè)解決方法,1是在 query中 指定 用某一個(gè)collation進(jìn)行比較, 另外一個(gè)就是修改column的 collation type 來(lái)避免這種錯(cuò)誤。
第二種方法,一個(gè)一個(gè)column改起來(lái)很累,寫(xiě)了個(gè)script,除了 被當(dāng)作 constraints比如 primary key, foreign key之外的 varchar, char,nvarchar 都可以統(tǒng)一修改成一個(gè)collation…
完整sql代碼:
復(fù)制代碼 代碼如下:
declare @CollationName varchar(500);
set @CollationName = 'SQL_Latin1_General_CP1_CI_AS'
create table #tmp (sqlStr varchar(max));
insert into #tmp
select 'alter table [' + o.name + '] alter column [' + c.name + ']' +
(case c.system_type_id when 167 then ' varchar(' when 175 then ' char(' else ' nvarchar(' end)
+ convert(varchar,c.max_length) + ') collate ' + @CollationName
from sys.columns c,
sys.objects o
where c.object_id=o.object_id and o.type='U' and c.system_type_id in (167,175,231) and collation_name>@CollationName
and c.name not in (
select cc.COLUMN_NAME
from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE cc
where
cc.TABLE_NAME = pk.TABLE_NAME
and cc.CONSTRAINT_NAME = pk.CONSTRAINT_NAME)
while (exists (select * from #tmp))
begin
declare @sqlStr varchar(max);
select @sqlStr=(select top 1 sqlstr from #tmp);
exec(@sqlStr)
delete from #tmp where sqlStr=@sqlStr
end
drop table #tmp;