I need help in creating a procedure with a constraint, when inserting staff member a manager to be specific he/she needs to be assigned to one clinic and one clinic only, thus when trying to insert a another manager to the same clinic it should create a trigger, that a manager has been assigned already to that clinic. Here's my code for inserting my variables :
CREATE DEFINER=`root`#`localhost` PROCEDURE `insert_staff`(in staff_num char(4),in First_name varchar(40),in surname varchar(30),in street varchar(20), in city varchar(20), in state varchar(2),in zipcode varchar(20),in Phone_no varchar(20),in Date_of_birth date,in gender_ char(1), in ID_no int(13),in Positon varchar(10),in salary_ double,in ClinicNo char(5))
BEGIN
set sql_safe_updates=0;
set foreign_key_checks=0;
insert into staff(staffNo,sFName,sLname,sStreet,sCity,sState,sZipCode,sTelNo,DOB,gender,ID,position,salary,clinicNo)
values(staff_num,First_name,surname,street,city,state,zipcode,Phone_no,Date_of_birth,gender_,ID_no,Positon,salary_,ClinicNo);
END
Following would check before inserting by selecting. If does not exist, record is inserted.
CREATE DEFINER=`root`#`localhost` PROCEDURE `insert_staff`(in staff_num char(4),in First_name varchar(40),in surname varchar(30),in street varchar(20), in city varchar(20), in state varchar(2),in zipcode varchar(20),in Phone_no varchar(20),in Date_of_birth date,in gender_ char(1), in ID_no int(13),in Positon varchar(10),in salary_ double,in ClinicNo char(5))
BEGIN
set sql_safe_updates=0;
set foreign_key_checks=0;
IF ( Position = 'Manager' AND EXISTS (select * from staff where clinicNo = ClinicNo and Positon='Manager')) THEN
//Handle your case
ELSE
insert into staff(staffNo,sFName,sLname,sStreet,sCity,sState,sZipCode,sTelNo,DOB,gender,ID,position,salary,clinicNo)values(staff_num,First_name,surname,street,city,state,zipcode,Phone_no,Date_of_birth,gender_,ID_no,Positon,salary_,ClinicNo);
END IF;
END
Related
How do i make an if statment that ROLLBACK: if the studentbrukernavn (students username) already exist, and if the klassekode (classcode) does not exist
DELIMITER $$
DROP PROCEDURE IF EXISTS OPPRETT_STUDENT$$
CREATE PROCEDURE OPPRETT_STUDENT
(
IN bilde_bildenr INT,
IN bilde_filnavn VARCHAR(30),
IN bilde_beskrivelse VARCHAR(30),
IN student_brukernavn VARCHAR(30),
IN student_fornavn VARCHAR(30),
IN student_etternavn VARCHAR(30),
IN student_klassekode VARCHAR(30)
)
BEGIN
START TRANSACTION;
INSERT INTO bilde
VALUES (bilde_bildenr,
CONCAT('bilder/',student_brukernavn,'.jpg'),
CONCAT('bilde av ',student_fornavn,' ',student_etternavn)
);
INSERT INTO student VALUES (student_brukernavn, student_fornavn, student_etternavn, student_klassekode, bilde_bildenr);
COMMIT;
END$$
DELIMITER ;
IF NOT EXISTS(SELECT query) THEN
ELSE
END IF;
Hope this helps
I have created a store procedure in MySQL (MariaDB) to UPDATE a specific row (just one row) but the row count after the UPDATE returns a value different than one (no rows updated) when all parameter values are the same than last same excecution, i mean when values did not change since previous execution.
Hope you understand that im trying to say When i pass the same parameter values than the last query executed before the procedure returns row count different than 1. its looks like the UPDATE doesn't work because there is nothing to change (all parameters are the same than the before execution) this is my MySQL mariaDB script
CREATE PROCEDURE sp_actualizarOpFicha3(
IN _numero INT,
IN _tipo INT,
IN _status_op INT,
IN _status_vta VARCHAR(1),
IN _fecha DATE,
IN _hora VARCHAR(5),
IN _paciente VARCHAR(40),
IN _cirujano VARCHAR(5),
IN _operacion VARCHAR(5),
IN _centro VARCHAR(5),
IN _vendedor VARCHAR(5),
IN _asistente VARCHAR(5),
IN _observ VARCHAR(80),
IN _observ1 VARCHAR(80),
IN _observ2 VARCHAR(80),
IN _obs_ctro VARCHAR(80),
IN _rut_cli VARCHAR(11),
IN _nom_cli VARCHAR(50),
IN _lista_p INT,
IN _n_informe INT,
IN _n_ocompra VARCHAR(15),
IN _sucursal VARCHAR(5),
IN _estado VARCHAR(1),
IN _obs_desp1 VARCHAR(80),
IN _proceso INT,
IN _sub_proc INT,
IN _req_asist INT,
IN _desp_insum INT,
OUT _res_up INT,
OUT mensaje VARCHAR(30) )
BEGIN
DECLARE countRow INT;
START TRANSACTION;
UPDATE mae_opera
SET tipo=_tipo, status_op=_status_op, status_vta=_status_vta, fecha=_fecha,
hora=_hora, paciente=_paciente,
cirujano=_cirujano, operacion=_operacion, centro=_centro,
vendedor=_vendedor, asistente=_asistente, observ=_observ,
observ1=_observ1, observ2=_observ2, obs_ctro=_obs_ctro,
rut_cli=_rut_cli, nom_cli=_nom_cli,
lista_p=_lista_p, n_informe=_n_informe, n_ocompra=n_ocompra,
sucursal=_sucursal, obs_desp1=_obs_desp1, estado=_estado,
proceso=_proceso, sub_proc=_sub_proc, req_asist=_req_asist,
desp_insum=_desp_insum
WHERE numero = _numero;
SET countRow = ROW_COUNT();
IF countRow = 1 THEN
COMMIT;
SET mensaje = 'Se actualizó correctamente la OP ';
ELSE
ROLLBACK;
SET mensaje = 'Ocurrió un error al intentar actualizar la OP ';
END IF;
In my Mysql , I have written below stored procedure to insert data into user table,
DELIMITER $$
DROP PROCEDURE IF EXISTS `CreateUser1`$$
CREATE PROCEDURE `CreateUser1`(
IN Email VARCHAR(50),
IN Password1 VARCHAR(50),
IN FirstName VARCHAR(50),
IN LastName VARCHAR(50),
IN AlternateEmail VARCHAR(50),
IN PhoneNumber VARCHAR(50),
IN Token VARCHAR(500)
)
BEGIN
IF NOT EXISTS( SELECT user_id FROM `um.user` WHERE `email`=Email)THEN
INSERT INTO `um.user`(site_id,email,PASSWORD,alternate_email,first_name,last_name,contact_number,
created_on,updated_on,is_active,token,is_verified_email)
VALUES
(1, Email1 , Password1 ,AlternateEmail, FirstName , LastName ,PhoneNumber,UTC_TIMESTAMP(),UTC_TIMESTAMP(),1,Token,0);
END IF;
END$$
DELIMITER ;
When i test this procedure as below,
CALL `CreateUser1`('ab1#ansys.com' , 'abcdefgh' ,'abc#gmail.com', 'sa' , '' ,'123456789','hasghsdfhgfhgfhdgfhdsgsh');
SELECT * FROM `um.user` WHERE email='ab1#ansys.com';
It does nothing.
It doesn't insert data into table, I figured out the issue .
The isssue is in parameter "Email".
But when I change the parameter "Email" to "Email12" , it worked as expected.
But I don't want to change in parameter as it will be a change in my API as well,
Now i want to solve this issue in sp level as well, I have tried below changes as well in SP which also doesn't works,
Set #userEmail=Email;
IF NOT EXISTS( SELECT user_id FROM `um.user` WHERE `email`=#userEmail)THEN
Any suggestions
Regards
Sangeetha
You may also qualify their identifiers. See 9.2.1 Identifier Qualifiers.
...
/*
-- You can also use Alias
SELECT `user_id`
FROM `um.user` `uu`
WHERE `uu`.`email` = `Email`
*/
IF NOT EXISTS (SELECT `user_id`
FROM `um.user`
WHERE `um.user`.`email` = `Email`) THEN
...
SQL Fiddle demo unqualified
SQL Fiddle demo qualified
Try this if you want to handle your issue within the stored procedure itself, without changing the name of parameter,
DELIMITER $$
DROP PROCEDURE IF EXISTS `CreateUser1`$$
CREATE PROCEDURE `CreateUser1`(
IN Email VARCHAR(50),
IN Password1 VARCHAR(50),
IN FirstName VARCHAR(50),
IN LastName VARCHAR(50),
IN AlternateEmail VARCHAR(50),
IN PhoneNumber VARCHAR(50),
IN Token VARCHAR(500)
)
BEGIN
DECLARE Email1 VARCHAR(50);
SET Email1 = Email;
IF NOT EXISTS( SELECT user_id FROM `um.user` WHERE `email`=Email1)THEN
INSERT INTO `um.user`(site_id,email,PASSWORD,alternate_email,first_name,last_name,contact_number,
created_on,updated_on,is_active,token,is_verified_email)
VALUES
(1, Email1 , Password1 ,AlternateEmail, FirstName , LastName ,PhoneNumber,UTC_TIMESTAMP(),UTC_TIMESTAMP(),1,Token,0);
END IF;
END$$
DELIMITER ;
This is because in MySQL, the parameter name passed to a Stored Procedure should not be the same as Column Name. Hope this solves your problem :)
I want to declare a variable and then assign a value of select query to that particular variable and then I need to pass that variable in an insert statement . So I tried the below code,
DROP PROCEDURE IF EXISTS `pro_damagestockdao` $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `pro_damagestockdao`(
IN damage_date date,
IN damage_inv_no varchar(12),
IN damage_inv_date date,
IN damage_dist_name varchar(30),
IN damage_contact_no varchar(15),
IN damage_item_code varchar(30),
IN damage_item_name varchar(30),
IN damage_batch_no varchar(15),
IN damage_mfr_name varchar(50),
IN damage_expiry_date date,
IN damage_pur_qty int(11),
IN damage_qty int(11),
IN damage_unit_price double(10,2),
IN damage_unit_vat double(4,2),
IN damage_unit_discount double(4,2),
IN damage_sub_total double(10,2),
IN damage_total_amount double(10,2),
IN damage_remarks varchar(1000),
IN functionality varchar(20),
out flag int
)
BEGIN
DECLARE selCnt int;
DECLARE dqty int;
SET dqty = (SELECT free FROM purchase_invoice p WHERE p.invoice_no = damage_inv_no);
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK;
SET flag=0;
START TRANSACTION;
if(functionality='save') then
INSERT INTO damage_stocks
(damage_stock_date,invoice_no,invoice_date,dist_name,contact_no,item_code,item_name,batch_no,qty,damaged_qty,unit_price,unit_vat,unit_discount,sub_total,total_amount,remarks) VALUES
(damage_date,damage_inv_no,damage_inv_date,damage_dist_name,damage_contact_no,0,damage_item_name,damage_batch_no,dqty,damage_qty,damage_unit_price,damage_unit_vat,damage_unit_discount,damage_sub_total,damage_total_amount,damage_remarks);
But it fails.. You see, I declared a variable dqty and then I passed it to the insert statement.
It is not problem to declaration. It is assign problem
try this query
SELECT free into dqty FROM purchase_invoice p WHERE p.invoice_no = damage_inv_no;
The following code works fine for me:
DELIMITER $$
USE `test`$$
DROP PROCEDURE IF EXISTS `pro_damagestockdao`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `pro_damagestockdao`(
IN damage_date DATE,
IN damage_inv_no VARCHAR(12),
IN damage_inv_date DATE,
IN damage_dist_name VARCHAR(30),
IN damage_contact_no VARCHAR(15),
IN damage_item_code VARCHAR(30),
IN damage_item_name VARCHAR(30),
IN damage_batch_no VARCHAR(15),
IN damage_mfr_name VARCHAR(50),
IN damage_expiry_date DATE,
IN damage_pur_qty INT(11),
IN damage_qty INT(11),
IN damage_unit_price DOUBLE(10,2),
IN damage_unit_vat DOUBLE(4,2),
IN damage_unit_discount DOUBLE(4,2),
IN damage_sub_total DOUBLE(10,2),
IN damage_total_amount DOUBLE(10,2),
IN damage_remarks VARCHAR(1000),
IN functionality VARCHAR(20),
OUT flag INT)
BEGIN
DECLARE selCnt INT;
DECLARE dqty INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK;
SET dqty = (SELECT free FROM purchase_invoice p WHERE p.invoice_no = damage_inv_no);
SET flag = 0;
START TRANSACTION;
IF(functionality = 'save') THEN
INSERT INTO damage_stocks (damage_stock_date, invoice_no, invoice_date, dist_name, contact_no, item_code, item_name, batch_no, qty,damaged_qty, unit_price, unit_vat, unit_discount, sub_total, total_amount, remarks)
VALUES (damage_date, damage_inv_no, damage_inv_date, damage_dist_name, damage_contact_no, 0, damage_item_name, damage_batch_no, dqty,damage_qty, damage_unit_price, damage_unit_vat, damage_unit_discount, damage_sub_total, damage_total_amount, damage_remarks);
END IF;
END$$
DELIMITER ;
With this SP call:
CALL `pro_damagestockdao`("2015-06-23","rx45","2015-06-20","DistName","DContactNo","DamageItemCode","damage_item_name","damage_batch_no","damage_mfr_name", "2015-07-01", 10, 5, 15.2, 7.66, 9.88, 99.00, 150.22, "No remarks", "save", #sorin);
What error do you get?
Do you get an error when trying to create the stored procedure or when you call it?
I'm actually trying to insert value into table using a procedure.This is my table code
create table employeeTable(
employeeId varchar(20),
employeeName varchar(20),
qualification varchar(20),
cadre varchar(15),
age numeric(3),
sex char(1),
occupation varchar(10),
dateOfBirth date,
address varchar(50),
city varchar(15),
employeePhoto blob,
constraint pk_employeeId_employeeTable primary key(employeeId)
);
My insert procedure is
delimiter //
create procedure insertEmployee(in employeeId varchar(20),in employeeName varchar(20),
in qualification varchar(20),in cadre varchar(15),in age numeric(3),in sex char(1),
in occupation varchar(10),in dateOfBirth date,in address varchar(50),in city varchar(15),
in employeePhoto blob)
begin
insert into employeetable values(upper(employeeId),employeeName,qualification,
cadre,age,sex,occupation,
str_to_date(dateOfBirth,'%d-%m-%Y'),address,city,employeePhoto);
end;//
delimiter ;
And I'm trying to call this procedure with following parameters
call insertEmployee('A001','Murugan','Phd','Manager',12,'M','service','30-07-1994',
'30,PNG nagar,pollachi','Coimbatore',null);
But values are not getting inserted and it's showing an error #1048 - Column 'dateOfBirth' cannot be null..
What is the problem here??
delimiter //
create procedure insertEmployee(in employeeId varchar(20),in employeeName varchar(20),
in qualification varchar(20),in cadre varchar(15),in age numeric(3),in sex char(1),
in occupation varchar(10),in dateOfBirth varchar(15),in address varchar(50),in city varchar(15),
in employeePhoto blob)
begin
insert into employeetable values(upper(employeeId),employeeName,qualification,
cadre,age,sex,occupation,
str_to_date(dateOfBirth,'%d-%m-%Y'),address,city,employeePhoto);
end;//
delimiter ;
Try this procedure. You were accpeting the dateOfBirth as a date object in the parameter list. It should have been a VARCHAR as that is how it is passed to the procedure.