0

What is wrong in this procedure

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

and this error occur in SQL Server:

Msg 156, Level 15, State 1, Procedure Question_ReadBySort, Line 23
Incorrect syntax near the keyword 'END'.

Msg 156, Level 15, State 1, Procedure Question_ReadBySort, Line 31
Incorrect syntax near the keyword 'END'.

1
  • Have you sequentially reduced each part of the query to eliminate the culprits and zero in on the actual problem, or just here asking us to figure it out from scratch? Commented May 30, 2013 at 10:17

1 Answer 1

6

A CTE definition must be immediately followed by a statement using the CTE. For example something like

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 

You can't define different CTE definitions conditionally with IF then use them later on as you appear to be trying.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.