2017-10-04 41 views
1

我正在對排序規則的代碼進行測試。在SQL Server 2016中爲列設置排序規則

declare @table table 
       (
        col1 varchar(10) collate Latin1_General_CS_AS 
        -- modified for column 
       ) 

insert into @table 
values('abcd') 

declare @table1 table 
       (
        col2 varchar(10) 
        --database default(collate SQL_Latin1_General_CP1_CI_AS) 
       ) 

insert into @table1 
values('abcd') 

-- executing this results in an error 'Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CS_AS" in the equal to operation.' 

select * 
from @table a 
join @table1 b on a.col1 = b.col2 

--executing below works fine 
select * 
from @table a 
join @table1 b on a.col1 collate Latin1_General_CS_AS = b.col2 

--executing below again throws error 
select * 
from @table a 
join @table1 b on a.col1 collate Latin1_General_CS_AS = b.col2 collate SQL_Latin1_General_CP1_CI_AS 

需要理解,雖然我在表變量中指定排序規則,但仍然會導致錯誤。

我在做什麼錯?

回答

2

您只在比較的一側指定collate(哪一邊無關緊要)。

--executing below works fine 
select * from @table a join @table1 b 
on a.col1 collate Latin1_General_CS_AS = b.col2 

--executing below also works fine 
select * from @table a join @table1 b 
on a.col1 = b.col2 collate SQL_Latin1_General_CP1_CI_AS 

不能指定的比較是在同一時間兩個不同的排序規則,正如你在最後的例子有(...... CS_AS & ...... CI_AS)。

+0

因此,即使在創建表時指定它不會工作,我們仍然需要在where子句中提及嗎? – omkar

+1

@omkar當兩個列的排序規則不同時,您必須選擇一個排序規則以用於比較的兩側。 - 在表級別指定排序規則可讓您設置默認排序規則,以便與字符串文字進行比較。 http://rextester.com/ZPF30783 – SqlZim

+0

@omkar你只需要在join子句的兩邊使用不同的排序規則時指定它。在你的情況下,'a'和'b'使用不同的排序規則,所以你必須指定使用哪一個。 –

0

基本原則是您必須對列進行整理以便比較正常工作。

如果a.col1歸類Latin1_General_CS_AS然後 你可以用它們

  • 的一個上a.col1 = b.col2整理Latin1_General_CS_AS

  • 上a.col1整理Latin1_General_CS_AS = B。 COL2

  • a.col1整理SQL_Latin1_General_CP1_CI_AI = b.col2整理 SQL_Latin1_General_CP1_CI_AI(你可以,只要它是改變兩側相同)