Search code examples
sqlcursorsybaseprocedure

Cursor "fetch next from" - syntax error near from


I want to create procedure that shows me products with 20% discount using cursor. After compiling code below I'm getting error message "Syntax error near "FROM" line 14. I'm using Sybase. Can anyone help me with this? Here is my code:

CREATE  PROCEDURE "ProduktyPoZnizce20procent2"( /* @parameter_name parameter_type [= default_value] [OUTPUT], ... */ )
AS
BEGIN
    declare @IDPR INTEGER 
    declare @typ  VARCHAR(30)
    declare @model varchar(30)
    declare @cena   float

DECLARE ProductCursor CURSOR FOR
SELECT IDProduct from Product

Open ProductCursor

FETCH NEXT FROM ProductCursor
INTO @IDPR

while(@@FETCH_STATUS = 0)
    BEGIN 
        select @typ = Product.product_type, @model=Product.name, @cena = Product.price * 0.8
        from Product
        where @IDPR = Product.IDProduct

        print(cast(@typ as nvarchar(30)) + ' ' + cast(@model as nvarchar(30)) + ' = ' + cast(@cena as varchar(10)))

        FETCH NEXT FROM ProductCursor INTO @IDPR

    END

close ProductCursor
DEALLOCATE CURSOR ProductCursor

END

Solution

  • OK. There was 2 mistakes in my code: I wasn't going forward with my cursor. Proper syntax to send my cursor to the next line is

    FETCH NEXT ProductCursor
    INTO @IDPR
    

    and it should be called at the before loop and in loop.

    Next thing was to properly print result on the screen. Since

    print(cast(@typ as nvarchar(30)) + ' ' + cast(@model as nvarchar(30)) + ' = ' + cast(@cena as varchar(10)))
    

    does not give anything on the screen it must be replaced by

    message (cast(@typ as nvarchar(30)) + ' ' + cast(@model as nvarchar(30)) + ' = ' + cast(@cena as varchar(10))) type status to client
    

    Whole code now looks like this:

    CREATE  PROCEDURE "ProduktyPoZnizce20procent2"( /* @parameter_name parameter_type [= default_value] [OUTPUT], ... */ )
    AS
    BEGIN
        declare @IDPR INTEGER 
        declare @typ  VARCHAR(30)
        declare @model varchar(30)
        declare @cena   float
    
    DECLARE ProductCursor CURSOR FOR
    SELECT IDProduct from Product
    
    Open ProductCursor
    
    FETCH NEXT ProductCursor
    INTO @IDPR
    
    while(@@FETCH_STATUS = 0)
        BEGIN 
            select @typ = Product.product_type, @model=Product.name, @cena = Product.price * 0.8
            from Product
            where @IDPR = Product.IDProduct
    
            message(cast(@typ as nvarchar(30)) + ' ' + cast(@model as nvarchar(30)) + ' = ' + cast(@cena as varchar(10))) type status to client
    
    
        FETCH NEXT ProductCursor
        INTO @IDPR
    
        END
    
    close ProductCursor
    DEALLOCATE CURSOR ProductCursor
    
    END