SQL内部联接:奇怪的结果

时间:2018-09-17 18:37:00

标签: sql-server tsql inner-join

我有如下数据:

Table_A:

Source     tableName     systemid
A           table_1       123abcA2
B           table_1       222DEFD3
C           table_1       369CCCB3


Table_B:

Source     tableName     systemid
Q          table_2       123abc
R          table_2       222DEF
C          table_2       369CCC

我运行了以下查询:

select a.Source, a.tableName, a.systemid as a_systemid, b.systemid as b_systemid
from table_a as a
inner join table_b as b on a.systemid = b.systemid

这是回来的东西:

Source     tableName     a_systemid     b_systemid
A           table_1       123abcA2       123abc
B           table_1       222DEFD3       222def
C           table_1       369CCCB3       369CCC

我什么也得不到吗?由于没有匹配项。

Table A system id = nvarchar data type

Table b systemid = uniqueidentifier data type

1 个答案:

答案 0 :(得分:1)

正在发生隐式转换,并且实际上会截断导致匹配的字符串数据。您需要将uniqueidentifier显式转换为nvarchar(max)。

请参阅this问答。

DECLARE @t1 TABLE([Source] CHAR(1),tableName VARCHAR(10),systemid nvarchar(max))
DECLARE @t2 TABLE([Source] CHAR(1),tableName VARCHAR(10),systemid uniqueidentifier)
INSERT INTO @t1 SELECT 'A','table_1','15b993cc-e8be-405d-bb9f-0c58b66dcdfe_1'
INSERT INTO @t1 SELECT 'B','table_1','4cffe724-3f68-4710-b785-30afde5d52f8_1'
INSERT INTO @t1 SELECT 'C','table_1','7ad22838-ddee-4043-8d1f-6656d2953545_1'
INSERT INTO @t2 SELECT 'Q','table_2','15b993cc-e8be-405d-bb9f-0c58b66dcdfe'
INSERT INTO @t2 SELECT 'R','table_2','4cffe724-3f68-4710-b785-30afde5d52f8'
INSERT INTO @t2 SELECT 'C','table_2','7ad22838-ddee-4043-8d1f-6656d2953545'

select a.Source, a.tableName, a.systemid as a_systemid, b.systemid as b_systemid
from @t1 as a
inner join @t2 as b on a.systemid = CONVERT(NVARCHAR(MAX),b.systemid)

作为一种实践,您应该始终明确地将不匹配的数据类型转换为清晰起见,并避免出现怪异的“正在发生什么?!?!”。东西。