|  | Posted by Plamen Ratchev on 06/27/07 17:30 
Here are a few notes that will help you understand the common table expressions and why you get the error:
 
 - It is required to terminate the statement before the WITH keyword defining
 the common table expression with a semicolon. It is because the WITH keyword
 has other uses. In your case if you end the select statement in the line
 before WITH using ; it will work.
 - I am not sure if you understand how CTEs work. CTEs are not materialized
 and work pretty much like derived tables (with more functionality, like the
 recursion used in this method). They only get defined before the statement
 the uses them, so you can reference the CTE only in that statement. There is
 a lot more to it, and if you decide to use this method I would suggest to
 read more on CTEs in SQL Server Books OnLine.
 - If you need to materialize the result of the CTE, you can use INSERT to
 insert the data into a temporary table, or just define a view based on the
 CTE (or you could also create a function based on the CTE).
 
 Here is a complete example using the approach to define a view based on the
 CTE:
 
 CREATE TABLE F_ADS_MANAGERS
 (
 MANAGER_KEY VARCHAR(255) NULL,
 DIRECT_REPORTS_CN VARCHAR(255) NULL
 );
 
 INSERT INTO F_ADS_MANAGERS (MANAGER_KEY, DIRECT_REPORTS_CN)
 VALUES ('CN=Marilette',
 'CN=Robert D,OU=TechnologyGroup,DC=strayer,DC=edu|
 CN=Robert Camarda,OU=TechnologyGroup,DC=strayer,DC=edu|
 CN=Michelle C,OU=TechnologyGroup,DC=strayer,DC=edu|
 CN=Magnolia B,OU=TechnologyGroup,DC=strayer,DC=edu|
 CN=Lee K,OU=TechnologyGroup');
 
 GO
 
 CREATE VIEW ManagersWithReports
 (manager_key, direct_report)
 AS
 WITH Managers
 (manager_key, direct_reports_cn, start_pos, end_pos)
 AS
 (
 SELECT manager_key,
 direct_reports_cn + '|',
 1,
 CHARINDEX('|', direct_reports_cn + '|')
 FROM F_ADS_MANAGERS
 UNION ALL
 SELECT manager_key,
 direct_reports_cn,
 end_pos + 1,
 CHARINDEX('|', direct_reports_cn, end_pos + 1)
 FROM Managers
 WHERE CHARINDEX('|', direct_reports_cn, end_pos + 1) > 0
 )
 SELECT manager_key,
 SUBSTRING(direct_reports_cn,
 start_pos,
 end_pos - start_pos) AS direct_report
 FROM Managers
 WHERE end_pos > 0;
 
 GO
 
 SELECT manager_key,
 direct_report
 FROM ManagersWithReports;
 
 GO
 
 DROP VIEW ManagersWithReports;
 DROP TABLE F_ADS_MANAGERS;
 
 GO
 
 
 HTH,
 
 Plamen Ratchev
 http://www.SQLStudio.com
  Navigation: [Reply to this message] |