递归CTE错误:类型不匹配

时间:2016-07-13 17:50:44

标签: sql sql-server tsql common-table-expression type-mismatch

我有这个CTE

WITH items AS ( 
        SELECT 1 AS lvl, 
               i.[No_] [Parent Item No_], 
               i.[No_], 
               i.[Description], 
               CAST(N'' AS NVARCHAR(20)) /* COLLATE Latin1_General_100_CS_AS  */ 
        FROM Item i
        LEFT JOIN KitComponent bc ON bc.[Parent Item No_] = i.[No_] 
        LEFT JOIN Item ci ON ci.[No_] = bc.[No_] 
        GROUP BY i.[No_], i.[Description], i.[Unit Price] 

        UNION ALL

        SELECT i.lvl + 1, 
               i.[No_], 
               i2.[No_], 
               i2.[Description], 
               CAST(bc.[Variant Code] AS NVARCHAR(20)) 
        FROM KitComponent bc
        JOIN items i ON i.[No_] = bc.[Parent Item No_]
        JOIN Item i2 ON i2.[No_] = bc.[No_] 
) 
SELECT * FROM items WHERE [Parent Item No_] = '4000540001'

它适用于一台服务器,没有指定排序规则的注释部分。然后我将整个事情复制到另一个窗口,其中同一个数据库的复制副本存在于另一个服务器上并得到此错误。

  

类型不在列和#34;变体代码"中的锚和递归部分之间匹配。递归查询"项目"。

我最初也没有那些CAST功能,它在服务器#1上运行得很好。最后,我将collat​​e命令放在CTE的顶部,然后它可以在两台机器上运行。

我按SELECT @@VERSION

检查版本
Microsoft SQL Server 2012 (SP3) (KB3072779) - 11.0.6020.0 (X64) 
  Oct 20 2015 15:36:27 
  Copyright (c) Microsoft Corporation
  Standard Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
  (Hypervisor)

Microsoft SQL Server 2012 (SP3) (KB3072779) - 11.0.6020.0 (X64) 
  Oct 20 2015 15:36:27 
  Copyright (c) Microsoft Corporation
  Standard Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
  (Hypervisor)

它们是相同的,所以我认为这必须是一些与众不同的选项。

有人知道我在哪里看看是什么选项吗?

1 个答案:

答案 0 :(得分:1)

来自WITH doc:

  

递归成员中列的数据类型必须与锚成员中相应列的数据类型相同。

所以它应该具有相同的数据类型,长度,整理,....

在你的例子中:

WITH items AS ( 
        SELECT 1 AS lvl, 
               i.[No_] [Parent Item No_], 
               i.[No_], 
               i.[Description], 
               CAST(N'' AS NVARCHAR(20)) -- default DB collation
        FROM Item i
        LEFT JOIN KitComponent bc ON bc.[Parent Item No_] = i.[No_] 
        LEFT JOIN Item ci ON ci.[No_] = bc.[No_] 
        GROUP BY i.[No_], i.[Description], i.[Unit Price] 

        UNION ALL

        SELECT i.lvl + 1, 
               i.[No_], 
               i2.[No_], 
               i2.[Description], 
               CAST(bc.[Variant Code] AS NVARCHAR(20)) -- column collation
        FROM KitComponent bc
        JOIN items i ON i.[No_] = bc.[Parent Item No_]
        JOIN Item i2 ON i2.[No_] = bc.[No_] 
) 
SELECT * FROM items WHERE [Parent Item No_] = '4000540001';

检查

SELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation')

SELECT COLLATION_NAME,*
FROM INFORMATION_SCHEMA.COLUMNS      
WHERE table_name = 'KitComponent'
  AND column_name = 'Variant Code'