SQL错误:语法错误不正确

时间:2013-05-30 10:14:45

标签: sql sql-server

此程序有什么问题

CREATE PROCEDURE [dbo].[Question_ReadBySort] 
-- Add the parameters for the stored procedure here
(
    @PageNumber int,
    @Gid bigint,
    @Sorttype int,
    @Df int
)
AS
BEGIN
    if @Gid=0
      BEGIN
       With Cust AS 
          (SELECT * ,
           ROW_NUMBER() OVER (order by q_id DESC) as RowNumber 
           from tbl_Question
           where q_del=0)
      END
    ELSE
        BEGIN
        With Cust AS 
           (SELECT * ,
           ROW_NUMBER() OVER (order by q_id DESC) as RowNumber 
           from tbl_Question
           where q_del=1)
        END
END
GO

并在SQL Server中发生此错误:

  

Msg 156,Level 15,State 1,Procedure Question_ReadBySort,Line 23
  关键字“END”附近的语法不正确。

     

Msg 156,Level 15,State 1,Procedure Question_ReadBySort,Line 31
  关键字“END”附近的语法不正确。

1 个答案:

答案 0 :(得分:6)

CTE定义必须紧跟一个使用CTE的声明。例如

之类的东西
WITH Cust
     AS (SELECT *,
                ROW_NUMBER() OVER (ORDER BY q_id DESC) AS RowNumber
         FROM   tbl_Question
         WHERE  q_del = CASE
                          WHEN @Gid = 0 THEN 0
                          ELSE 1
                        END)
SELECT *
FROM   Cust 

您无法使用IF有条件地定义不同的CTE定义,然后在您尝试尝试时使用它们。