具有uniqueidentifier的递归CTE必须在锚中具有值

时间:2011-12-19 14:20:18

标签: sql sql-server-2008 tsql

;WITH Companies(pkCompanyID,name,parentCompanyID,SomeId) AS

        (
            SELECT
                tblCompany.pkCompanyID,
                tblCompany.name,
                NULL,--this is a int with no value and it works in the anchor
                NULL AS SomeId--But this uniqueidentifier do not work why?
            FROM
                tblCompany
            WHERE
                tblCompany.fkCompToCompID IS NULL
            UNION ALL
            SELECT
                tblCompany.pkCompanyID,
                tblCompany.name,
                tblCompany.fkCompToCompID,
                NEWID()
            FROM
                tblCompany
                JOIN Companies ON tblCompany.fkCompToCompID=Companies.pkCompanyID
        )
        SELECT
            *
        FROM
            Companies

因此,此函数将给出错误:“类型在递归查询”公司“”列“SomeId”中的锚和递归部分之间不匹配。我知道我可以通过将“NULL AS SomeId”替换为“CAST(NULL AS uniqueidentifier)”来修复它。但是,当parentCompanyId不需要知道它是一个int时,为什么锚需要知道它是一个uniqueidentifier?是因为uniqueidentifier是一个对象而int是一个值类型吗?

1 个答案:

答案 0 :(得分:3)

默认情况下,

NULL假定为int,这就是您不必明确强制转换该值的原因。

你可以从

看到这一点
SELECT NULL AS FOO INTO BAR;

SELECT DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME='FOO'AND TABLE_NAME='BAR';