StoredProcedure not workng correctly - mysql

What I am doing here is I am updating my records when my record_id=0 and activity_id=0 condition fails..But what result I am getting is It is updating all the records regardless of the condition WHERE activity_id = Activity_ID (in Update tms_activity Line)
This is he procedure I wrote in MySql
CREATE PROCEDURE `EmpTimeSheet_SaveTasks`(IN user_ID INT(11),
IN date DATE,
IN record_ID INT(11),
IN task_ID INT(10),
IN Hours double,
IN Description longtext,
IN Updated_By_ID INT(11),
IN Project_ID INT(11),
IN Project_Name Varchar(50),
IN Task_Name Varchar(50),
IN Activity_ID INT(11),
IN Deleted_ID Varchar(100)
)
BEGIN
IF record_ID = 0 THEN
INSERT IGNORE INTO tms_timesheet(user_id, date, is_freezed) VALUES (user_ID,date,0);
SET #ID = (SELECT record_id FROM tms_timesheet WHERE user_id= user_ID and date=date);
INSERT INTO tms_activity (timesheet_id, task_id, hours, description, updated_on, updated_by_id,project_id,project_name,task_name ) VALUES (#ID ,task_ID,Hours ,Description, CURRENT_TIMESTAMP( ) ,user_ID,Project_ID,Project_Name ,Task_Name );
ELSE IF Activity_ID = 0 THEN
INSERT INTO tms_activity ( timesheet_id, task_id, hours, description, updated_on, updated_by_id,project_id,project_name,task_name ) VALUES (record_ID ,task_ID,Hours ,Description, CURRENT_TIMESTAMP( ) ,user_ID, Project_ID ,Project_Name,Task_Name);
ELSE
UPDATE tms_activity SET task_id=task_ID, hours=Hours, description=Description, updated_on=CURRENT_TIMESTAMP( ), updated_by_id=user_ID,project_id=Project_ID,task_name=Task_Name,project_name=Project_Name *****WHERE activity_id = Activity_ID;*****
END IF;
END IF;
IF Deleted_ID!='' THEN
DELETE FROM tms_activity where activity_id in (Deleted_ID);
END IF;
END

I solved it myself actually the solution was quiet weird for me because when I changed my parameter name from Activity_ID to ActivityID,It WORKED..I dont know the reason how It happened and WHy..But it solved my error

Maybe the problem is the var name.
Try to changing "Activity_ID" to "vActivity_ID".

Related

SQL - Procedure function

Trying to create a Procedure to (Insert, Delete and, Update) values in employee_details.
CREATE DEFINER=`root`#`localhost` ALTER PROCEDURE `alter_employeedetails`(in employee_id int(11), employee_name VARCHAR(30), employee_join_date date,
employee_desgination varchar(30), employee_salary bigint(20), employee_address varchar(30),
employee_contact varchar(30), employee_email_id varchar(30)
BEGIN
IF #StatementType = 'Insert'
BEGIN
insert into employee_details values
(employee_id, employee_name, employee_join_date, employee_desgination, employee_salary, employee_address, employee_contact, employee_email_id)
END
IF #StatementType = 'Update'
BEGIN
UPDATE employee_details SET
(employee_name = #employee_name, employee_join_date = #employee_join_date, employee_designation = #employee_desgination,
employee_salary = #employee_salary, employee_address = #employee_address, employee_contact = #employee_contact, employee_email_id = #employee_email_id)
WHERE employee_id = #employee_id
END
else IF #StatementType = 'Delete'
BEGIN
DELETE FROM employee_details where employee_id = #employee_id
END
end
Quite a few errors in that code...
You forgot to prefix all the parameters with the "#" symbol.
Forgot to include "#StatementType" as a parameter.
Update had brackets around it.
You cannot specify int(11) (employee_id) or bigint(20)
(salary). It's either int / bigint (you don't specify the length
for int/bigint datatypes). And is salary correct as bigint? MSSQL has a "money"
datatype, or you could use decimal(8,2) or something similar. You
might be multiplying the salary by 100 to shift the decimal place for
all I know?
When inserting, do you really want to insert a employee Id? This would normally be an auto-incrementing primary key
Insert statement missing the fields you were populating. Required if using the "values" keyword like you had specified.
Hopefully this is closer to what you want.
ALTER PROCEDURE alter_employeedetails
(#StatementType as varchar(25), #employee_id int, #employee_name VARCHAR(30), #employee_join_date date,
#employee_designation varchar(30), #employee_salary bigint, #employee_address varchar(30),
#employee_contact varchar(30), #employee_email_id varchar(30))
AS
BEGIN
IF #StatementType = 'Insert'
BEGIN
insert into employee_details
(employee_id, employee_name, employee_join_date, employee_designation, employee_salary, employee_address, employee_contact, employee_email_id)
values
(#employee_id, #employee_name, #employee_join_date, #employee_designation, #employee_salary, #employee_address, #employee_contact, #employee_email_id)
END
ELSE IF #StatementType = 'Update'
BEGIN
UPDATE employee_details
SET
employee_name = #employee_name,
employee_join_date = #employee_join_date,
employee_designation = #employee_designation,
employee_salary = #employee_salary,
employee_address = #employee_address,
employee_contact = #employee_contact,
employee_email_id = #employee_email_id
WHERE employee_id = #employee_id
END
ELSE IF #StatementType = 'Delete'
BEGIN
DELETE FROM employee_details where employee_id = #employee_id
END
END

Stored Procedure in mySQL workbench (INSERT INTO error)

I'm running into an error in my stored procedure, and after numerous YT videos and forums, I still have no clue where I'm going wrong. Given what I'm trying to do, it all seems to look correct.
Here's the deal. I take in some information to buy some stock, I use an IF to make sure that I have enough money to make the purchase, I then insert the purchase information into my TRADES table and update the cash balance in ACCOUNTS to reflect the spending of $$.
I can't even test to see if it works correctly because it won't run. The only error I'm getting is at INSERT INTO, in which it says error: INTO (into) is not valid input at this position
I have done ALL of my insert statements the exact same way, and have no idea why this particular syntax is incorrect? Any help would be greatly appreciated! Below are two approaches, both with errors.
CREATE PROCEDURE `BUY` (TID INT,ID INT, CASH INT, T_NAME VARCHAR(4) ,
TCOUNT INT, TBUYDATE DATE, TBUYPRICE INT )
BEGIN
IF (ACCOUNT.CASH_BALANCE >= (TCOUNT * TBUYPRICE),
INSERT INTO TRADES (TRADE_ID, ACCOUNT_ID, TRADE_NAME, TRADE_COUNT, TRADE_BUYDATE, TRADE_BUYPRICE)
VALUES (TID, ID, T_NAME, TCOUNT, TBUYDATE, TBUYPRICE)
AND UPDATE ACCOUNT.CASH_BALANCE
WHERE ACCOUNT.ACCOUNT_ID = ID
SET ACCOUNT.CASH_BALANCE = (ACCOUNT.CASH_BALANCE - (TCOUNT * TBUYPRICE)),
NULL
)
END
I have also tried the following, however I get an error on END missing subclause or other elements before end
CREATE PROCEDURE `BUY` (TID INT,ID INT, CASH INT, T_NAME VARCHAR(4) , TCOUNT
INT, TBUYDATE DATE, TBUYPRICE INT )
BEGIN
IF (ACCOUNT.CASH_BALANCE >= (TCOUNT * TBUYPRICE))
THEN
INSERT INTO TRADES (TRADE_ID, ACCOUNT_ID, TRADE_NAME, TRADE_COUNT,
TRADE_BUYDATE, TRADE_BUYPRICE)
VALUES (TID, ID, T_NAME, TCOUNT, TBUYDATE, TBUYPRICE);
UPDATE ACCOUNT.CASH_BALANCE
SET ACCOUNT.CASH_BALANCE = (ACCOUNT.CASH_BALANCE - (TCOUNT * TBUYPRICE))
WHERE ACCOUNT.ACCOUNT_ID = ID;
ELSE #noinsert
END
There are multiple errors/corrections:
The Delimiter command was not used, so he gets confused on the end of statement and the end of the procedure definition
The account table needs to be selected in an exists statement
I've used a local variable l_cash instead of repeating TCOUNT * TBUYPRICE (Not an error).
The ELSE statement was not necessary and an END IF; was missing.
Update statement corrected.
Here is the corrected code:
DELIMITER $$
CREATE PROCEDURE `BUY` (TID INT,ID INT, CASH INT, T_NAME VARCHAR(4) , TCOUNT
INT, TBUYDATE DATE, TBUYPRICE INT)
BEGIN
DECLARE l_cash INT DEFAULT 0;
SET l_cash = TCOUNT * TBUYPRICE;
IF EXISTS(SELECT 1 FROM Account WHERE ACCOUNT_ID = ID AND CASH_BALANCE >= l_cash) THEN
INSERT INTO TRADES (TRADE_ID, ACCOUNT_ID, TRADE_NAME, TRADE_COUNT,
TRADE_BUYDATE, TRADE_BUYPRICE)
VALUES (TID, ID, T_NAME, TCOUNT, TBUYDATE, TBUYPRICE);
UPDATE ACCOUNT
SET CASH_BALANCE = (CASH_BALANCE - l_cash)
WHERE ACCOUNT_ID = ID;
END IF;
END$$
DELIMITER ;

Insert into Table Variable getting Column name or number of supplied values does not match table definition

DECLARE #myTemp TABLE (Item Varchar(10) Not Null,
[Description Varchar(30) Not Null,
LonDescription Varchar(50),
[Level] Char(1),
LevelDesc Varchar(15),
GID Varchar(16),
[Min] Int,
[Max] Int,
QTY Int,
QoO Int)
FETCH NEXT FROM cAreaLocationItems Into #citem,#cDesc,#cLDesc,#cLVL,#cLVLDesc,#cGID,#cMin,#cMax,#cqty
IF ##FETCH_STATUS <> 0 -- We're out of items
BREAK
WHILE ##FETCH_STATUS = 0
Begin
Declare #QoO Int
SELECT #QoO = SUM(QtyReqd - QtyActual)
FROM abc.tblorders
WHERE (ItemNumber = #cItem) AND (Status <> '4') And
Bin = #Location
GROUP BY ItemNumber, UPC, [Level], Description, Bin
If #QoO = Null
Set #QoO = 0
Insert into #myTemp values(#cItem,#cDesc,#cLDesc,#clvl,#cLVLDesc,#cGid,#cMin,#cMax,#cQTy,#QoO)
FETCH NEXT FROM cAreaLocationItems Into #citem,#cDesc,#cLDesc,#cLVL,#cLVLDesc,#cGID,#cMin,#cMax,#cqty
end
Get the error executed stored procedure on the insert into #myTemp table variable defined above. Table says 10 columns and insert has ten values. Any help?
Try to specify the column names in the insert query like this:
Insert into #myTemp (Item Varchar,[Description,LonDescription,Level],LevelDesc,GID,[Min],[Max],QTY,QoO) values(#cItem,#cDesc,#cLDesc,#clvl,#cLVLDesc,#cGid,#cMin,#cMax,#cQTy,#QoO)
It helps you to avoid error when you add new column into the table

mysql stored procedure checking if record exists

I created the following stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `add_summit`(IN `assoc_code` CHAR(5), IN `assoc_name` CHAR(50), IN `reg_code` CHAR(2), IN `reg_name` CHAR(100), IN `code` CHAR(20), IN `name` CHAR(100), IN `sota_id` CHAR(5), IN `altitude_m` SMALLINT(5), IN `altitude_ft` SMALLINT(5), IN `longitude` DECIMAL(10,4), IN `latitude` DECIMAL(10,4), IN `points` TINYINT(3), IN `bonus_points` TINYINT(3), IN `valid_from` DATE, IN `valid_to` DATE)
BEGIN
declare assoc_id SMALLINT(5);
declare region_id SMALLINT(5);
declare summit_id MEDIUMINT(8);
-- ASSOCIATION check if an association with the given code and name already exists
SELECT id INTO assoc_id FROM association WHERE code = assoc_code LIMIT 1;
IF (assoc_id IS NULL) THEN
INSERT INTO association(code, name) VALUES (assoc_code, assoc_name);
set assoc_id = (select last_insert_id());
END IF;
-- REGION check if a region with the given code and name already exists
SET region_id = (SELECT id FROM region WHERE code = reg_code AND name = reg_name AND association_id = assoc_id);
IF (region_id IS NULL) THEN
INSERT INTO region(association_id, code, name) VALUES (assoc_id, reg_code, reg_name);
set region_id = (select last_insert_id());
END IF;
-- SUMMIT check if a summit with given parameters already exists
SET summit_id = (SELECT id FROM summit WHERE association_id = assoc_id AND region_id = region_id);
IF (summit_id IS NULL) THEN
INSERT INTO summit(code, name, sota_id, association_id, region_id, altitude_m, altitude_ft, longitude,
latitude, points, bonus_points, valid_from, valid_to)
VALUES (code, name, sota_id, assoc_id, region_id, altitude_m, altitude_ft, longitude, latitude,
points, bonus_points, valid_from, valid_to);
END IF;
END$$
basically, it should check if a record exists in some tables and, if it doesn't, it should insert it and use the inserted id (auto increment).
The problem is that even if the record exists (for instance in the association table), assoc_id keeps returning null and that leads to record duplication.
I'm new to stored procedures so I may be doing some stupid errors. I've been trying to debug this SP for hours but I cannot find the problem.
A newbie mistake.
I forgot to specify the table name in the field comparison and that leads to some conflicts with param names (for example the param name).
A good idea is to specify some kind of prefix for parameters (like p_) and always specify the name of the table in the SP.

Procedure that store updated history of table in another table

I have two tables Person with PersonId, Name,Address,Mobile and PersonLog with Id,Name,Address,Mobile,FK_PersonId. I am trying store the old data in PersonLog and Person to be updated.
This is my procedure, but it is only updating Person and not storing selected(edited) data from Person into PersonLog :
CREATE PROCEDURE [dbo].[UpdateInsertPerson]
(
#PersonId int,
#PersonName nvarchar(40),
#Address nvarchar(60),
#Mobile nvarchar(15)
)
AS
BEGIN
INSERT INTO
dbo.PersonLog(PersonName, Address, Mobile, FK_PersonId)
SELECT
Person.PersonId, Person.PersonName, Person.Address, Person.Mobile
FROM
dbo.Person JOIN dbo.PersonLog ON PersonLog.FK_PersonId = Person.PersonId;
UPDATE
dbo.Person
SET
PersonName = #PersonName,
Address = #Address,
Mobile = #Mobile
WHERE
PersonId = #PersonID;
END
Any help?
I might suggest these changes... but I don't know what you're after exactly. Or your data.
I highly suggest adding a modified date to your PersonLog table....
alter table PersonLog add Modified_DT datetime default getdate()
this code works for me...
CREATE PROCEDURE UpdateInsertPerson (
#PersonId int,
#PersonName nvarchar(40) = null,
#Address nvarchar(60) = null,
#Mobile nvarchar(15) = null
)
AS
BEGIN
INSERT INTO PersonLog (FK_PersonId, PersonName, Address, Mobile)
SELECT Person.PersonID,
Person.PersonName,
Person.Address,
Person.Mobile
FROM Person
WHERE Person.PersonId=#PersonID;
UPDATE Person
SET PersonName = case when #PersonName is not null then #PersonName else PersonName end,
Address = case when #Address is not null then #Address else Address end,
Mobile = case when #Mobile is not null then #Mobile else Mobile end
WHERE PersonId = #PersonID;
END
insert into Person values (1,'kim','123 main st','555-555-5555');
exec UpdateInsertPerson 1,'kim';
exec UpdateInsertPerson 1,'ryan';
exec UpdateInsertPerson 1,'taco';
select * from personlog
select * from Person
that way will not insert a brand new person. this way will... for this to work, your Person.PersonID must be set like this: PersonID int IDENTITY(1,1) primary key.
ALTER PROCEDURE UpdateInsertPerson (
#PersonId int = null,
#PersonName nvarchar(40) = null,
#Address nvarchar(60) = null,
#Mobile nvarchar(15) = null
)
AS
BEGIN
INSERT INTO PersonLog (FK_PersonId, PersonName, Address, Mobile)
SELECT Person.PersonID,
Person.PersonName,
Person.Address,
Person.Mobile
FROM Person
WHERE Person.PersonId=#PersonID;
UPDATE Person
SET PersonName = case when #PersonName is not null then #PersonName else PersonName end,
Address = case when #Address is not null then #Address else Address end,
Mobile = case when #Mobile is not null then #Mobile else Mobile end
WHERE PersonId = #PersonID;
-- this inserts into Person if they didn't already exist
IF ##ROWCOUNT = 0
BEGIN
INSERT Person (PersonName, Address, Mobile) VALUES (#PersonName, #Address, #Mobile);
END
END
The procedure is not working as you are joining PersonLog with Person table in the select statement. As initially this table is empty the condition PersonLog.FK_PersonId = Person.PersonId is false and nothing gets inserted (as FK_PersonId is NULL)
I don't see any purpose of joining the 2 tables to insert the record in Log table. just remove the join condition and include a where clause as Person.PersonId=#PersonID