Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a Select to a variable in a stored procedure

I try to create a procedure in my Oracle Database and can't achieve to assign the result of a query to my variables. Here is what i'm trying to debug :

create or replace
PROCEDURE PCD_COMBAT (identifier_perso NUMBER, identifier_advers NUMBER) AS

ATT_PERSO NUMBER;
OFF_PERSO NUMBER;
DEF_ADVERS NUMBER;

BEGIN

OFF_PERSO := SELECT OFFENSE_PERSO FROM PERSONNAGE WHERE ID_PERSO = identifier_perso;
DEF_ADVERS := SELECT DEFENSE_ADVERSAIRE FROM PERSONNAGE WHERE ID_ADVERSAIRE = identifier_advers;
ATT_PERSO := OFF_PERSO - DEF_ADVERS;
IF ATT_PERSO < 1 { ATT_PERSO := 1 };

END PCD_COMBAT;

It clearly says in Oracle Developper that my Select doesnt please him and can't figure out why. Oracle library, forums and code samples I read didnt help much.

like image 767
Mathieu M. Gélinas Avatar asked Apr 28 '13 05:04

Mathieu M. Gélinas


2 Answers

You need to use SELECT INTO. Also there are no braces in PL/SQL you need to use THEN and END IF. I am not quite sure what you do with the result. Do you want to give it back? Then you need a FUNCTION. It should look something like this (untested):

create or replace
FUNCTION PCD_COMBAT (identifier_perso NUMBER, identifier_advers NUMBER) 
RETURN NUMBER
AS
  ATT_PERSO NUMBER;
  OFF_PERSO NUMBER;
  DEF_ADVERS NUMBER; 
BEGIN     
  SELECT OFFENSE_PERSO 
    INTO OFF_PERSO 
    FROM PERSONNAGE 
   WHERE ID_PERSO = identifier_perso;
  SELECT DEFENSE_ADVERSAIRE 
    INTO DEF_ADVERS 
    FROM PERSONNAGE 
   WHERE ID_ADVERSAIRE = identifier_advers;

  ATT_PERSO := OFF_PERSO - DEF_ADVERS;
  IF ATT_PERSO < 1 THEN 
     ATT_PERSO := 1;
  END IF

  RETURN ATT_PERSO;

END PCD_COMBAT;
like image 179
hol Avatar answered Oct 15 '22 02:10

hol


I don't think you can assign values to variables like that. Try SELECT INTO like this:

create or replace
PROCEDURE PCD_COMBAT (identifier_perso NUMBER, identifier_advers NUMBER) AS

ATT_PERSO NUMBER;
OFF_PERSO NUMBER;
DEF_ADVERS NUMBER;

BEGIN


SELECT OFFENSE_PERSO INTO OFF_PERSO FROM PERSONNAGE WHERE ID_PERSO = identifier_perso;
SELECT DEFENSE_ADVERSAIRE INTO DEF_ADVERS FROM PERSONNAGE WHERE ID_ADVERSAIRE = identifier_advers;
ATT_PERSO := OFF_PERSO - DEF_ADVERS;
IF ATT_PERSO < 1 { ATT_PERSO := 1 };

END PCD_COMBAT;
like image 28
TonyB Avatar answered Oct 15 '22 03:10

TonyB