;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是一个值类型吗?
答案 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';