I am new to MySQL Stored Procedure. I am writing a code that has a combination or cursors and CASEs.
I have a labeled loop in the cursor. Is it possible to call that labeled loop inside conditions of my CASEs
EDIT:
DROP PROCEDURE IF EXISTS ETOOLS_LATEST.SP_QueryTermsAndConditions;
COMMIT;
DELIMITER $$
CREATE PROCEDURE ETOOLS_LATEST.SP_QueryTermsAndConditions (
IN P_IN_ACCEPTED_BY VARCHAR(32),
OUT P_OUT_ACCEPTED_VERSION VARCHAR(10),
OUT P_OUT_CATEGORY VARCHAR(20),
OUT P_OUT_CURRENT_VERSION VARCHAR(10),
OUT P_OUT_FORCE_ACCEPT BOOLEAN
)
BEGIN
DECLARE noMoreRows BOOLEAN;
DECLARE loopCounter INT DEFAULT 0;
DECLARE rowCount INT DEFAULT 0;
DECLARE acceptedVersion INT(10);
DECLARE currentVersion INT(10);
DECLARE latestGeneral VARCHAR(10);
DECLARE latestBooking VARCHAR(10);
DECLARE curTnc CURSOR
FOR
SELECT a.version AS accepted_version,
a.category,
(
SELECT version
FROM apptermsandconditions c
WHERE is_latest IS True
AND c.category = a.category
) AS current_version
FROM ETOOLS_LATEST.apptermsandconditions a,
ETOOLS_LATEST.usertermsandconditions b
WHERE b.accepted_version = a.id
AND b.accepted_by = P_IN_ACCEPTED_BY;
DECLARE
CONTINUE HANDLER
FOR NOT FOUND
SET noMoreRows = TRUE;
SELECT VERSION
INTO latestGeneral
FROM ETOOLS_LATEST.AppTermsAndConditions
WHERE is_latest IS TRUE
AND CATEGORY = 'General';
SELECT VERSION
INTO latestBooking
FROM ETOOLS_LATEST.AppTermsAndConditions
WHERE is_latest IS TRUE
AND CATEGORY = 'Booking';
OPEN curTnc;
SELECT FOUND_ROWS()
INTO rowCount;
cursorLoop: LOOP
FETCH curTnc
INTO P_OUT_ACCEPTED_VERSION,
P_OUT_CATEGORY,
P_OUT_CURRENT_VERSION;
IF noMoreRows THEN
CLOSE curTnc;
LEAVE cursorLoop;
END IF;
IF P_OUT_ACCEPTED_VERSION <> P_OUT_CURRENT_VERSION THEN
SET P_OUT_FORCE_ACCEPT = 1;
ELSE
SET P_OUT_FORCE_ACCEPT = 0;
END IF;
SELECT P_OUT_ACCEPTED_VERSION,
P_OUT_CATEGORY,
P_OUT_CURRENT_VERSION,
P_OUT_FORCE_ACCEPT;
SET loopCounter = loopCounter + 1;
END LOOP cursorLoop;
CASE rowCount
WHEN 0
THEN
SELECT null, 'General', latestGeneral, 1;
SELECT null, 'Booking', latestBooking, 1;
WHEN 1
THEN
CASE P_OUT_CATEGORY
WHEN 'General'
THEN
SELECT null, 'Booking', latestBooking, 1;
WHEN 'Booking'
THEN
SELECT null, 'General', latestGeneral, 1;
END CASE;
WHEN 2
THEN
SELECT null;
END CASE;
END $$
DELIMITER ;
CALL SP_QueryTermsAndConditions('333333', #P_OUT_ACCEPTED_VERSION, #P_OUT_CATEGORY, #P_OUT_CURRENT_VERSION, #P_OUT_FORCE_ACCEPT);
Related
I need to write a stored procedure using mysql.
In the repeat loop showing below, if I use something as:
SET VDATEI=(SELECT A.DATEI FROM STAFF_CONVENIOS A WHERE
A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1);
the stored procedure works well and I get a result set.
But, I need select into multiple variables. Something as:
SELECT
A.DATEI, A.DIAI, A.HORAI
INTO
VDATEI, VDIAI, VHORAI
FROM
STAFF_CONVENIOS A
WHERE
A.CONV_ID = CONVE AND A.STAFF_ID = MED
LIMIT 1;
In this case my stored procedure is broken I get no result set.
How to use select into to multiple variables into stored procedure with temporary tables?
My stored procedure is similar to:
CREATE PROCEDURE P_GETHORARIOS(
IN `MED` BIGINT,
IN `DATAREF` DATE,
IN `ESPEC` BIGINT,
IN `CONVE` BIGINT
)
BEGIN
DECLARE BDONE,BTEMP, BOCUP INT;
DECLARE DIA;
DECLARE VDIA,OK TINYINT;
DECLARE VDURACAO TINYINT;
DECLARE VDATEI DATE;
DECLARE VDIAI TINYINT;
DECLARE VHORAI TIME;
DECLARE VHORA, VHORAI,VHORAF TIME;
DECLARE CURS CURSOR FOR SELECT DIA,COALESCE(A.DURACAO,30) AS DURACAO, A.HINI FROM STAFF_ESCALA A
WHERE A.DIA=DIA;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET BDONE = 1;
DROP TEMPORARY TABLE IF EXISTS TBLRESULTS;
CREATE TEMPORARY TABLE IF NOT EXISTS TBLRESULTS (
DATA_AG DATE,
DIA TINYINT,
HORA TIME );
SET DIA=DAYOFWEEK(DATAREF);
OPEN CURS;
SET BDONE = 0;
REPEAT
SET OK=TRUE;
FETCH CURS INTO VDIA,VDURACAO,VHORAI;
-- SET VDATEI=(SELECT A.DATEI FROM STAFF_CONVENIOS A WHERE A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1);
SELECT A.DATEI, A.DIAI,A.HORAI INTO VDATEI, VDIAI,VHORAI FROM STAFF_CONVENIOS A WHERE A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1;
SET BTEMP=IF(VDATEI IS NULL,TRUE,FALSE);
SET OK=OK AND BTEMP ;
IF (OK) THEN
INSERT INTO TBLRESULTS VALUES (DATAREF,VDIA,VHORA);
ELSE INSERT INTO TBLRESULTS VALUES (VDATEI,VDIAI,VHORAI);
END IF;
UNTIL BDONE END REPEAT;
CLOSE CURS;
SELECT A.* FROM TBLRESULTS;
END
I have posted a sample of my problem. Here is the real stored procedure:
CREATE DEFINER=`SYSDBA`#`%` PROCEDURE `P_GETHORARIOS`(
IN `MED` BIGINT,
IN `DATAREF` DATE,
IN `ESPEC` BIGINT,
IN `CONVE` BIGINT
)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE BDONE INT;
DECLARE BTEMP TINYINT;
DECLARE BOCUP TINYINT;
DECLARE DIA BIGINT;
DECLARE VDIA TINYINT;
DECLARE VDURACAO TINYINT;
DECLARE VHORA, VHORAI,VHORAF TIME;
DECLARE VMED_ID BIGINT;
DECLARE VESPEC_ID BIGINT;
DECLARE VCONV_ID BIGINT;
DECLARE OK TINYINT;
DECLARE VNOMEESPEC,VNOMEMED VARCHAR(100);
DECLARE CURS CURSOR FOR SELECT DIA,COALESCE(A.DURACAO,30) AS DURACAO, A.HINI, A.HFIM, A.STAFF_ID,B.NOME AS NOMESTAFF, A.ESPEC_ID,C.NOME AS NOMEESPEC
FROM STAFF_ESCALA A
LEFT JOIN STAFF B ON B.ID=A.STAFF_ID
LEFT JOIN ESPECIALIDADES C ON C.ID=A.ESPEC_ID
WHERE A.DIA=DIA;
-- DECLARE CURS CURSOR FOR SELECT HINI, HFIM FROM STAFF_ESCALA;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET BDONE = 1;
DROP TEMPORARY TABLE IF EXISTS TBLRESULTS;
CREATE TEMPORARY TABLE IF NOT EXISTS TBLRESULTS (
DATA_AG DATE,
DIA TINYINT,
HORA TIME,
MED_ID BIGINT,
NOME_MED VARCHAR(100),
ESPEC_ID BIGINT,
NOME_ESPEC VARCHAR(100)
);
SET DIA=DAYOFWEEK(DATAREF);
OPEN CURS;
SET BDONE = 0;
REPEAT
SET OK=TRUE;
FETCH CURS INTO VDIA,VDURACAO,VHORAI,VHORAF,VMED_ID,VNOMEMED,VESPEC_ID,VNOMEESPEC;
IF (MED IS NOT NULL) THEN
SET OK=IF(MED=VMED_ID,TRUE,FALSE) ;
END IF;
IF (ESPEC IS NOT NULL) THEN
SET OK=OK AND IF(ESPEC=VESPEC_ID,TRUE,FALSE) ;
END IF;
IF (CONVE IS NOT NULL) THEN
-- SET #EOK=(SELECT 1 FROM STAFF_CONVENIOS A WHERE A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1);
SELECT 1 INTO #EOK FROM STAFF_CONVENIOS A WHERE A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1;
SET BTEMP=IF(#EOK IS NULL,TRUE,FALSE);
SET OK= OK AND BTEMP ;
END IF;
IF (OK) THEN
SET VHORA=VHORAI;
IF (VDURACAO IS NULL) THEN
SET VDURACAO=30;
END IF;
WHILE (VHORA <= VHORAF) DO
SET BOCUP=(SELECT 1 FROM AGENDA_STAFF A WHERE A.DATA_MARCADA=DATAREF AND A.HORA_MARCADA=VHORA);
IF (BOCUP IS NULL) THEN
INSERT INTO TBLRESULTS VALUES (DATAREF,VDIA,VHORA,VMED_ID,VNOMEMED,VESPEC_ID,VNOMEESPEC);
END IF;
SET VHORA=ADDTIME(VHORA, VDURACAO * 100);
END WHILE;
SET VHORA=ADDTIME(VHORA, VDURACAO * (-100));
IF (VHORA < VHORAF) THEN
SET VHORA=VHORAF;
SET BOCUP=(SELECT 1 FROM AGENDA_STAFF A WHERE A.DATA_MARCADA=DATAREF AND A.HORA_MARCADA=VHORA);
IF (BOCUP IS NULL) THEN
INSERT INTO TBLRESULTS VALUES (DATAREF,VDIA,VHORA,VMED_ID,VNOMEMED,VESPEC_ID,VNOMEESPEC);
END IF;
END IF;
END IF;
UNTIL BDONE END REPEAT;
CLOSE CURS;
SELECT A.* FROM TBLRESULTS A LEFT JOIN AGENDA_STAFF B ON B.STAFF_ID=A.MED_ID AND B.HORA_MARCADA=A.HORA AND B.DATA_MARCADA=A.DATA_AG;
END
//
The problem is with the lines:
-- SET #EOK=(SELECT 1 FROM STAFF_CONVENIOS A WHERE A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1);
SELECT 1 INTO #EOK FROM STAFF_CONVENIOS A WHERE A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1;
If I use "SET #EOK..." all works well.
If I use SELECT 1 INTO #EOK.. the problem appears.
More info with data
Expected result from call p_gethorarios(7,'2017-11-20',47,21)
"data_ag";"dia";"hora";"med_id";"nome_med";"espec_id";"nome_espec"
"2017-11-20";"2";"08:30:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"09:00:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"09:30:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"10:00:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"08:30:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"09:00:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"09:30:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"10:00:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
STAFF-ESCALA TABLE
ID;STAFF_ID;DIA;HINI;HFIM;ESPEC_ID;DURACAO;CREATION_TIME;MODIFICATION_TIME;LAST_USER_MODIF
25;7;2;08:00:00;10:00:00;50;;18/11/2017 21:44:02;;1
26;7;6;08:00:00;10:00:00;50;;18/11/2017 21:55:27;;1
27;7;4;08:00:00;10:00:00;50;;18/11/2017 21:55:27;;1
28;7;5;08:00:00;10:00:00;50;;18/11/2017 21:56:36;;1
35;7;3;08:00:00;10:00:00;47;;19/11/2017 19:10:29;;1
36;7;5;08:00:00;10:00:00;47;;19/11/2017 19:10:29;;1
38;7;2;08:00:00;10:00:00;47;;19/11/2017 19:10:29;;1
You may have to use user/session variables (the #xyz kind). The documentation does not explicitly state such, but it only shows examples with them.
https://dev.mysql.com/doc/refman/5.7/en/select-into.html
If it is an issue with the NOT FOUND handler getting triggered from something other than the cursor, you could try structuring your code something like this (very pseudocode):
FETCH
WHILE( NOT DONE )
BEGIN
DO STUFF
SET DONE = FALSE
FETCH
END
DELIMITER $$
CREATE PROCEDURE `remove_schedule_duplicate` ()
BEGIN
BLOCK1 : BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE schedule_id CHAR(36);
DECLARE gamePk INTEGER;
DECLARE keep_entry TINYINT(1);
DECLARE scheduleDuplicate CURSOR FOR SELECT game_pk FROM schedule where is_active = 1 group by game_pk,home_team_id,away_team_id,venue_id having count(game_pk) > 1 limit 2;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN scheduleDuplicate;
get_schedule_duplicate: LOOP
FETCH scheduleDuplicate INTO gamePk;
IF finished = 1 THEN
LEAVE get_schedule_duplicate;
END IF;
**BLOCK2 : BEGIN
DECLARE block_finished INTEGER DEFAULT 0;
DECLARE blockDuplicate CURSOR FOR SELECT id FROM schedule where game_pk = gamePk and is_active = 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET block_finished = 1;
OPEN blockDuplicate;
block_schedule_duplicate: LOOP
FETCH blockDuplicate INTO schedule_id;
IF block_finished = 1 THEN
LEAVE block_schedule_duplicate;
END IF;
IF keep_entry = 0 THEN
UPDATE schedule set is_active = 0 where id = schedule_id;
END IF;
END LOOP block_schedule_duplicate;
CLOSE blockDuplicate;
END BLOCK2;**
END LOOP get_schedule_duplicate;
CLOSE scheduleDuplicate;
END BLOCK1;
END
$$
The problem is Innerloop first time execute well after that block_finished always be 1 so. always it quits the inner block.
How to resolve this issue. What i do ? Some one help me to resolve the issue.
I have Changed My Stored procedure like this:
DELIMITER $$
CREATE PROCEDURE `remove_schedule_duplicate`()
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE schedule_id,temp CHAR(36) DEFAULT NULL;
DECLARE gamePk INTEGER;
DECLARE keep_entry TINYINT(1);
DECLARE scheduleDuplicate CURSOR FOR SELECT game_pk,id FROM schedule where game_pk in (SELECT game_pk FROM schedule where is_active = 1 group by game_pk,home_team_id,away_team_id,venue_id having count(game_pk) > 1) and is_active = 1 order by game_pk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN scheduleDuplicate;
get_schedule_duplicate: LOOP
FETCH scheduleDuplicate INTO gamePk,schedule_id;
IF finished = 1 THEN
LEAVE get_schedule_duplicate;
END IF;
IF ((temp IS NULL) AND (gamePk IS NOT NULL)) OR ((temp IS NOT NULL) AND (temp <> gamePk)) THEN
SET temp = gamePk;
SET keep_entry = 1;
#ELSE IF temp IS NOT NULL AND temp = gamePk THEN
ELSE
SET keep_entry = 0;
END IF;
IF keep_entry = 0 THEN
UPDATE schedule set is_active = 0 where id = schedule_id;
END IF;
END LOOP get_schedule_duplicate;
CLOSE scheduleDuplicate;
END$$
DELIMITER ;
delimiter %%
create procedure getFileID(in fname varchar(100), out fId int)
begin
select ID from File
where Name = fname
into fId;
end %%
delimiter ;
delimiter $$
create procedure FileINFO(in fname varchar(100))
begin
declare SMS_done, Par_don boolean default false;
declare SMSID int;
declare SMSName varchar(100) default "";
declare SMSCode varchar(100) default "";
declare ParamName varchar(100) default "";
declare fId int default 0;
call getFileID(fname, fId);
declare c1 cursor for select ID, Code, Name from SMSTemplate where F_ID = fId;
declare continue handler for not found set SMS_done = true;
open c1;
SMS_loop : loop
fetch from c1 into SMSID, SMSCode, SMSName;
if SMS_done then
close c1;
leave SMS_loop;
end if;
block2 : begin
declare c2 cursor for
select Name from ParameterType where ST_ID = SMSID;
declare continue handler for not found set Par_done = true;
open c2;
Par_loop : loop
fetch from c2 into ParamName;
if SMS_done then
set SMS_done = false;
close c2;
leave Par_loop;
end if;
insert into FileDetails
(FileName, SMSName, SMSCode, ParamName)
values
(fname, SMSName, SMSCode, ParamName);
end loop Par_loop;
end block2;
end loop SMS_loop;
select * from FileDetails;
end $$
delimiter ;
and i get that error
ERROR 1064 (42000): You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for
the right syntax to use
near 'declare c1 cursor for select ID, Code, Name from SMSTemplate where F_ID = fId;' at line 10
for starters get the declares all grouped together at the top.
Also there is no such thing as fetch into so those two things were fixed.
Par_don / Par_done had a typo in the declare.
Also, for sanity, have a drop if exist for the stored proc right above each one, so it is easily scripted and maintained.
drop procedure if exists FileINFO;
delimiter $$
create procedure FileINFO(in fname varchar(100))
begin
declare SMS_done, Par_done boolean default false;
declare SMSID int;
declare SMSName varchar(100) default "";
declare SMSCode varchar(100) default "";
declare ParamName varchar(100) default "";
declare fId int;
declare c1 cursor for select ID, Code, Name from SMSTemplate where F_ID = fId;
declare continue handler for not found set SMS_done = true;
call getFileID(fname, fId );
open c1;
SMS_loop : loop
fetch c1 into SMSID, SMSCode, SMSName;
if SMS_done then
close c1;
leave SMS_loop;
end if;
block2 : begin
declare c2 cursor for
select Name from ParameterType where ST_ID = SMSID;
declare continue handler for not found set Par_done = true;
open c2;
Par_loop : loop
fetch from c2 into ParamName;
if SMS_done then
set SMS_done = false;
close c2;
leave Par_loop;
end if;
insert into FileDetails
(FileName, SMSName, SMSCode, ParamName)
values
(fname, SMSName, SMSCode, ParamName);
end loop Par_loop;
end block2;
end loop SMS_loop;
select * from FileDetails;
end $$
delimiter ;
Does the table SMSTemplate have a field F_ID??
If not, that could be why you're getting this error.
I have the mysql version 5.5.38.
When I call a procedure that call a function inside there, handler condition its activated into function and raise up to procedure. I need that handler condition on function not affect the process on procedure. Included the function and procedure.
function:
DELIMITER $$
CREATE FUNCTION FUNCTION_HOURLY_GAS_CHANGE(INI_DATE DATETIME, TANK INT)
RETURNS INT
NOT DETERMINISTIC
BEGIN
DECLARE END_GAL INT;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET END_GAL = -1;
SET END_GAL = 0;
SELECT GALLONS INTO END_GAL
FROM TLS_TEMP_DATA WHERE FK_TANK = TANK
AND DATE LIKE CONCAT(DATE_FORMAT(DATE_ADD(DATE_FORMAT(INI_DATE, '%Y-%m-%d %H'), INTERVAL 1 HOUR), '%Y-%m-%d %H'),':%')
AND REQUEST_TYPE = 1;
RETURN END_GAL;
END $$
DELIMITER ;
procedure:
DELIMITER $$
CREATE PROCEDURE HOURLY_GAS_CHANGE(IN dateReport char(50), IN tank INT)
BEGIN
DECLARE COMPLETELOOP INT DEFAULT 0;
DECLARE INI_DATE DATETIME;
DECLARE INI_GAL INT;
DECLARE END_GAL INT;
DECLARE DIFF INT;
DECLARE V_HOUR CHAR(50);
DECLARE V_INI_GAL CHAR(50);
DECLARE V_END_GAL CHAR(50);
DECLARE V_DIFF CHAR(50);
DECLARE INITIALDATA CURSOR FOR
SELECT
DATE, GALLONS FROM TLS_TEMP_DATA WHERE FK_TANK = tank
AND (DATE BETWEEN CONCAT(dateReport, ' 00:00:00') AND CONCAT(dateReport, ' 23:59:59')) AND REQUEST_TYPE = 1
ORDER BY ID;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET COMPLETELOOP = 1;
DROP TEMPORARY TABLE IF EXISTS HOURLYGASCHANGE;
CREATE TEMPORARY TABLE HOURLYGASCHANGE(
`HOUR_DATA` CHAR(50) NOT NULL,
`INI_GAL` CHAR(50) NOT NULL,
`END_GAL` CHAR(50) NOT NULL,
`DIFF` CHAR(50) NOT NULL)
ENGINE=MEMORY;
OPEN INITIALDATA;
READ_LOOP: LOOP
FETCH INITIALDATA INTO INI_DATE, INI_GAL;
IF COMPLETELOOP THEN
LEAVE READ_LOOP;
END IF;
SET END_GAL = 1;
SET END_GAL = FUNCTION_HOURLY_GAS_CHANGE(INI_DATE, tank);
IF END_GAL > 0 THEN
SET DIFF = (END_GAL - INI_GAL);
SET V_DIFF = CAST(DIFF AS CHAR(50));
SET V_END_GAL = CAST(END_GAL AS CHAR(50));
ELSE
SET V_DIFF = 'N/A';
SET V_END_GAL = 'NOT UPDATED';
END IF;
SET V_INI_GAL = CAST(INI_GAL AS CHAR(50));
SET V_HOUR = CAST(DATE_FORMAT(INI_DATE, '%H') AS CHAR(50));
INSERT INTO HOURLYGASCHANGE VALUES(V_HOUR, V_INI_GAL, V_END_GAL, V_DIFF);
END LOOP;
close INITIALDATA;
SELECT * FROM HOURLYGASCHANGE;
END $$
DELIMITER ;
I can't fix the problem, but I found a solution to replace the function, I capture empty result into IFNULL function and now I can set a specific value when select show me a empty result.
SELECT (
IFNULL(
(
SELECT ENDTLS.GALLONS
FROM TLS_TEMP_DATA ENDTLS
WHERE ENDTLS.FK_TANK = tank
AND ENDTLS.DATE LIKE ONCAT(DATE_FORMAT(DATE_ADD(DATE_FORMAT(INI_DATE, '%Y-%m-%d %H'), INTERVAL 1 HOUR), '%Y-%m-%d %H'),':%')
AND ENDTLS.REQUEST_TYPE = 1
)
, -1)
) INTO END_GAL;
This procedure does not return 2, it always returns 1. How to return 1 when insert happens, and return 2 when an update happens?
It is perfectly insert and update but return value always 1.
CREATE PROCEDURE [dbo].[sp_SaveEmployeeDetails]
#employeeID int
,#first_name varchar(255)
,#middle_name varchar(255)
,#last_name varchar(255)
,#gender varchar(255)
,#date_of_birth date
,#EntryBy varchar(255)
--,#ActionStatus int = NULL OUTPUT
AS
BEGIN
SET NOCOUNT OFF;
DECLARE #ActionStatus int;
IF NOT EXISTS(Select * From employees
Where employeeID =#employeeID)
BEGIN
INSERT INTO [dbo].[employees] ([first_name], [middle_name], [last_name], [gender], [date_of_birth], [EntryBy], [EntryDate])
VALUES (#first_name, #middle_name, #last_name, #gender, #date_of_birth, #EntryBy, getdate())
SET #ActionStatus = 1;
END
ELSE
BEGIN
UPDATE employees
SET [first_name] = #first_name,
[middle_name] = #middle_name,
[last_name] = #last_name,
[gender] = #gender,
[date_of_birth] = #date_of_birth,
[EntryBy] = #EntryBy,
[EntryDate] = getdate()
WHERE
employeeID = #employeeID
SET #ActionStatus = 2;
END
RETURN #ActionStatus;
--also try SELECT #ActionStatus;
END
The value you return here
RETURN #ActionStatus;
...might be set to a variable directly, its the procedure's "own" return value. Look at this example:
CREATE PROCEDURE dbo.TestReturn(#IntValue INT)
AS
BEGIN
IF #IntValue=0
RETURN 0;
ELSE
RETURN 1;
END
GO
DECLARE #RetVal INT;
EXEC #RetVal = dbo.TestReturn -1;
SELECT #RetVal;
EXEC #RetVal = dbo.TestReturn 0;
SELECT #RetVal;
EXEC #RetVal = dbo.TestReturn 1;
SELECT #RetVal;
GO
DROP PROCEDURE dbo.TestReturn;
It comes back with 1-0-1 as expected.
But this return value is bound to INT and is meant to reflect execution states (like error codes, success level...) In your case this seems to be the case...
If you think about output of any other data use OUTPUT parameters.
CREATE PROCEDURE dbo.TestReturn(#IntValue INT, #TestPrm VARCHAR(100) OUTPUT)
AS
BEGIN
IF #IntValue=0
BEGIN
SET #TestPrm='Value was 0'
RETURN 0;
END
ELSE
BEGIN
SET #TestPrm='Value was something else';
RETURN 1;
END
END
GO
DECLARE #RetVal INT;
DECLARE #RetVarchar VARCHAR(100);
EXEC #RetVal = dbo.TestReturn -1,#RetVarchar OUTPUT;
SELECT #RetVal,#RetVarchar;
EXEC #RetVal = dbo.TestReturn 0,#RetVarchar OUTPUT;
SELECT #RetVal,#RetVarchar;
EXEC #RetVal = dbo.TestReturn 1,#RetVarchar OUTPUT;
SELECT #RetVal,#RetVarchar;
GO
DROP PROCEDURE dbo.TestReturn;