CTE与函数中的临时表

时间:2012-08-13 11:43:10

标签: sql-server common-table-expression

Create FUNCTION [dbo].[GetAllChildSpaces] 
(
    @CustomSpaceId varchar(40),
    @Userid int 
)
RETURNS NVARCHAR(MAX)
AS
BEGIN   
    DECLARE @Totalspace NVARCHAR(MAX)
    DECLARE  @tblTotalSpace table (CustomSpaceId NVARCHAR(40))

    WITH Hierachy (CustomSpaceId) AS 
     ( 
     SELECT  CustomSpaceId FROM  CV_CustomSpace e 
     UNION ALL 
     SELECT  e1.CustomSpaceId FROM  CV_CustomSpace e1 INNER JOIN Hierachy p  ON e1.ParentID = p.CustomSpaceId 
     ) 

  INSERT INTO @tblTotalSpace (CustomSpaceId)

  SET @Totalspace=( 
      SELECT STUFF((SELECT ',' + CAST(CustomSpaceId as varchar(50)) 
      FROM @tblTotalSpace FOR XML PATH('')) ,1,1,'') AS TotalSpaceID
  )

  DROP TABLE @tblTotalSpace

  return @Totalspace  
 END 

我收到了一个错误:

  

关键字'with'附近的语法不正确。如果这个陈述是   公用表表达式,xmlnamespaces子句或更改跟踪   context子句,前一个语句必须以a结尾   分号。

任何人都可以解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

用分号

终止前一个语句
Create FUNCTION [dbo].[GetAllChildSpaces] ( @CustomSpaceId varchar(40), @Userid int ) RETURNS NVARCHAR(MAX) AS BEGIN
DECLARE @Totalspace NVARCHAR(MAX) 
DECLARE @tblTotalSpace table (CustomSpaceId NVARCHAR(40)); -- Here

WITH Hierachy (CustomSpaceId) AS 
...

为了保持一致性和清晰度,使用分号终止所有语句并没有什么坏处。

答案 1 :(得分:1)

在WITH

之前加上分号
;with  Hierachy (CustomSpaceId) AS 
 ( .............