Raed Alsaleh Raed Alsaleh - 4 months ago 45
SQL Question

MySql stored procedure else if and multi queries

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

I had to add an additional "End IF" to cover "Else IF" statement the full query be like this :

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;