MySql stored procedure else if and multi queries

Raed Alsaleh picture Raed Alsaleh · Jan 6, 2013 · Viewed 32.3k times · Source

In the following stored procedure I encountered an error:

DROP PROCEDURE IF EXISTS `SP_DeleteFileInfo`;
CREATE  PROCEDURE `SP_DeleteFileInfo`(pFileID int)
Set @FileRef= null;
select filesinfo.ReferenceID into @FileRef FROM filesinfo where filesinfo.FileID =pFileID;
DELETE From filesinfo
WHERE filesinfo.FileID= pFileID;
IF EXISTS(SELECT * from filesrefrences where filesrefrences.ReferenceID= @FileRef and filesrefrences.RefrenceCount>1) then 
    update filesrefrences
    set 
        filesrefrences.RefrenceCount= filesrefrences.RefrenceCount-1
    where 
        filesrefrences.ReferenceID= @FileRef;
    SELECT @FileRef;
ELSE IF(@FileRef is Not NULL) THEN
    DELETE from filesrefrences WHERE filesrefrences.ReferenceID = @FileRef;
    SELECT -77;
ELSE
    SELECT -99;
end if;

The error encountered is :

[SQL]
 select filesinfo.ReferenceID into @FileRef FROM filesinfo where filesinfo.FileID =pFileID;
[Err] 1054 - **Unknown column 'pFileID' in 'where clause'**

What would the best solution to solve this error?

Answer

John Woo picture John Woo · Jan 6, 2013

define pFileID as IN parameter, eg

CREATE PROCEDURE SP_DeleteFileInfo(IN pFileID int)

full query,

DROP PROCEDURE IF EXISTS `SP_DeleteFileInfo`;
DELIMITER //
CREATE  PROCEDURE `SP_DeleteFileInfo`(IN pFileID int)
BEGIN
    Set @FileRef= null;
    select filesinfo.ReferenceID into @FileRef FROM filesinfo where filesinfo.FileID =pFileID;
    DELETE From filesinfo WHERE filesinfo.FileID= pFileID;
    IF EXISTS(SELECT * from filesrefrences where filesrefrences.ReferenceID= @FileRef and filesrefrences.RefrenceCount>1) then 
        update filesrefrences
        set  filesrefrences.RefrenceCount= filesrefrences.RefrenceCount-1
        where  filesrefrences.ReferenceID= @FileRef;
        SELECT @FileRef;
    ELSE 
        IF(@FileRef is Not NULL) THEN
            DELETE from filesrefrences WHERE filesrefrences.ReferenceID = @FileRef;
            SELECT -77;
        ELSE
            SELECT -99;
        END IF;
    END IF;
END //
DELIMITER ;