在存储过程中使用CTE进行问题

时间:2017-12-21 05:32:41

标签: sql sql-server stored-procedures common-table-expression

我有一个这样的存储过程:

CREATE PROCEDURE prtl_usp_portal_logdaily 
    @startdate DATETIME,
    @enddate DATETIME,
    @usertype int,
    @gradelist varchar(1000) = null
AS
BEGIN
    DECLARE @qry NVARCHAR(MAX)
    SET @qry=''

    IF(@usertype = 1)
    BEGIN
       ;WITH mycte AS
       (
           SELECT CAST(@startdate AS DATETIME) DateValue
           UNION ALL
           SELECT DateValue + 1
           FROM mycte   
           WHERE DateValue + 1 <= @enddate
      )

      SET @qry = N'SELECT datepart(day,DateValue) AS daycode,
   (select count(DISTINCT a.userID) from PRTL_UserAccessLog a
   inner join prtlv_familydetails b
   on a.userid=b.familyid 
   INNER JOIN STD_StudentDetails c ON b.FamilyID = c.familyid
    INNER JOIN dbo.STD_CurrentAcademicInformation d ON c.StudentID = d.StudentID
   WHERE d.GradeID IN ('+@gradelist+')
   and a.usertypeid=1 and convert(date,DateTime) = DateValue) countvalue,
   (select count(*) from prtlv_familydetails) AS total_count,
   ROUND((CAST((select count(DISTINCT a.userID) from PRTL_UserAccessLog a
   inner join prtlv_familydetails b
   on a.userid=b.familyid 
   INNER JOIN STD_StudentDetails c ON b.FamilyID = c.familyid
    INNER JOIN dbo.STD_CurrentAcademicInformation d ON c.StudentID = d.StudentID
   WHERE d.GradeID IN ('+@gradelist+')
   and a.usertypeid=1 and convert(date,DateTime) = DateValue) AS FLOAT)/CAST((select count(*) from prtlv_familydetails)AS FLOAT)),3) AS average, 
   datename(dw,DateValue) AS day_name 
   FROM    mycte';
END
---
 EXEC (@qry)
 END

GO

当我运行该程序时,我收到以下错误:

  

关键字“SET”附近的语法不正确。

谷歌搜索后,我发现如果with cte is not the first statement, semicolon should be placed before cte statement。我把分号。但它没有用。

1 个答案:

答案 0 :(得分:4)

WITH需要SELECT(或UPDATEDELETEINSERT),而不是SET,至少一个定义的公用表表达式应​​该由以下语句引用。您未WITH(或SELECTUPDATEDELETE)关注INSERT

此外,动态sql的范围将无法识别在执行查询字符串之前由过程形成的公用表表达式(cte)。

  

指定临时命名结果集,称为公用表   表达式(CTE)。这是从简单查询派生而来定义的   在单个SELECT,INSERT,UPDATE或的执行范围内   DELETE语句。该子句也可以在CREATE VIEW中使用   语句作为其定义SELECT语句的一部分。

请参阅:WITH common_table_expression