2011-12-19 52 views
1
;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」類型不錨和列遞歸部分之間的匹配’。我知道我可以用「CAST(NULL AS uniqueidentifier)」替換「NULL AS SomeId」來修復它。但是,爲什麼當parentCompanyId不需要知道它是一個int時,錨點需要知道它是唯一標識符?是否因爲uniqueidentifier是一個對象而int是一個值類型?遞歸CTE具有唯一標識符必須在錨

回答

3

NULL默認假定爲int這就是爲什麼您不必明確投射那一個。

您可以從

SELECT NULL AS FOO INTO BAR; 

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

感謝你的答案看到這一點。幫助我理解 – Arion 2011-12-19 14:51:08