while creating a procedure in MYSQL i am facing a problem as, condition runs 'IF' statement and runs 'ELSE' statements too. just because an insert statement inside 'IF'.
insert into Userverified (UserID, Mobile, PIN,uname,unameid)
select NextUserID(),Mobile,PIN,null,null from UserNotVerified where Mobile=p_Mobile;
always results--- "result 00" ---why?
if i remove this
insert into Userverified (UserID, Mobile, PIN,uname,unameid)
select NextUserID(),Mobile,PIN,null,null from UserNotVerified where Mobile=p_Mobile;
works fine.
im using PhpMyAdmin and new with MYsql.
code attached here as---
CREATE procedure test
(
p_Mobile varchar(13),
p_LastOTP varchar(6)
)
begin
if ((select count(*) from UserVerified where mobile=p_Mobile)=0)
then
insert into Userverified (UserID, Mobile, PIN,uname,unameid)
select NextUserID(),Mobile,PIN,null,null from UserNotVerified where Mobile=p_Mobile;
if((select count(*) from uwallet where mobile=p_Mobile)=0)
then
insert into UserWallet (WalletID,Mobile,JoinAmount,WinAmount,ReferAmount,TotalAmount,DateModified)
select nextwalletid(),p_Mobile,0,0,0,0,now();
end if;
select 1 as result;
else
select '00' as result;
end if;
end;
Related
I'm trying to create a after insert trigger on vitamin to insert the new data into vitamin_variety with cross join select statement that I created. But somehow when new rows are inserted, the trigger does not insert that new rows into vitamin_variety. I use select statements with join and it works good on it's own but when I use it to insert into select statement, it does nothing.
My code
BEGIN
INSERT INTO
vitamin_variety (extreme_name,regular_name, price_variety_extreme,price_variety_regular)
SELECT sel_extreme.name as `extreme_name`,sel_regular.name as `regular_name`,sel_extreme.ext,sel_regular.reg FROM
(SELECT sel.name as `name`,sel.id as `id`,sel.extreme as `ext` FROM
(SELECT new.vitamin_name as `name`,new.vitamin_id as `id`,CASE WHEN new.vitamin_name LIKE 'extreme%' THEN new.price END AS `extreme`
FROM vitamin) AS sel
WHERE sel.extreme IS NOT NULL) AS sel_extreme
CROSS JOIN
(SELECT sel.name as `name`,sel.id as `id`, sel.regular as `reg` FROM
(SELECT new.vitamin_name as `name`,new.vitamin_id as `id`,CASE WHEN new.vitamin_name NOT LIKE 'extreme%' THEN new.price END AS `regular`
FROM vitamin) AS sel
WHERE sel.regular IS NOT NULL) AS sel_regular
WHERE sel_regular.id <= sel_extreme.id
END
EDITED
Here's the FIDDLE
I have two tables DailyVisits and TotalSum My goal is to add DailyVisits to TotalSum with a stored procedure/query that I'll run at the end of the day.
DailyVisits
UserId,PageId,Visits
1,1,32
2,123,34
4,12,213
5,1,1
TotalSum
UserId,PageId,TotalVisits
1,1,300
1,41,2
3,12,213
5,1,653
and so on.
I tried two approaches but I can't get my head around a solution.
Below my queries to achieve this, if you have another suggestion/query simple enough to understand, I appreciate your help.
Approach1:
delimiter $$
CREATE PROCEDURE UPSERT_DAILYSUM()
BEGIN
IF EXISTS (SELECT Id, PageId FROM DailyVisits) THEN
UPDATE TotalSum TotalVisits = TotalVisits + (SELECT Visits FROM DailyVisits);
ELSE INSERT INTO TotalSum (UserId,PageId,TotalVisits)
VALUES (SELECT Id,PageId,Visits);
END IF
END $$
delimiter ;
Approach2:
INSERT INTO TotalSum (UserId,PageId,TotalVisits) VALUES(SELECT * FROM DailyVisits)
ON DUPLICATE KEY UPDATE (PageId,TotalVisits)
VALUES(SELECT PageId,Visits FROM DailyVisits)
This is what I'm struggling with: How will I get distinct values when key does not exist? Can I use RIGHT JOIN (or LEFT JOIN) and check for NULL values, and then add right (or left) table?
same as you need like this:
The problem is i dont know what you want to do in update and insert portion:
delimiter $$
CREATE PROCEDURE UPSERT_DAILYSUM()
BEGIN
Declare idvar int(50) DEFAULT 0;
Declare pageidvar int(50) DEFAULT 0;
SELECT Id, PageId INTO idvar,pageidvar FROM DailyVisits;
if(LENGTH(idvar)>0 THEN
UPDATE TotalSum TotalVisits = TotalVisits + (SELECT Visits FROM DailyVisits);
ELSE
INSERT INTO TotalSum (UserId,PageId,TotalVisits) VALUES (SELECT Id,PageId,Visits);
END $$
delimiter ;
I must perform the following situation down, but when you run got the error:
SQL Error (1064): 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 'INTO produto_seriais(serial_id) VALUES( SELECT id
FROM seriais WHERE serial =' at line 5
SELECT CASE WHEN (
SELECT COUNT(id) FROM seriais WHERE serial = '2020'
) > 1
THEN
(INSERT INTO produto_seriais(serial_id) VALUES(
SELECT id FROM seriais WHERE serial = '2020'
))
ELSE (
INSERT INTO seriais (serial) VALUE('2020');
SET #last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO produto_seriais (serial_id) VALUES (#last_id_in_table1);
)
END;
The case is as follows:
I'll get in "serial" table by serial "X". If it already exists, unless your ID in the "produto_seriais" table. If there is (serial), I will save the same, recover your ID and save to "produto_seriais". Any suggestions for how to do this?
Important Note: This routine will run will be thousands of times each execution (10,000 or more, depending on the quantity of serial).
P.s.: Sorry for my bad english.
Try a stored procedure
DELIMITER //
CREATE PROCEDURE sp_produto_seriais(IN `p_serial_id`)
IF EXISTS (SELECT * FROM seriais WHERE serial = p_serial_id )
BEGIN
INSERT INTO produto_seriais (serial_id)
SELECT id
FROM seriais
WHERE serial = p_serial_id
END
ELSE
BEGIN
INSERT INTO seriais (serial) VALUE(p_serial_id);
INSERT INTO produto_seriais (serial_id) VALUES (LAST_INSERT_ID());
END //
DELIMITER ;
usage:
CALL sp_produto_seriais('2020')
You could use the if exists..else statement.
If exists (select * from ....)
Begin
Insert into ... Select id from table
End
Else
Begin
Insert..
End
Please fill .... with your statements. You could use the link here to convert it for MySQL.
Convert if exists for MySQL
How do I show a message from a stored procedure?
What is the right syntax to display a message saying whether or not rows exist?
In SQL Server it's PRINT to show a message bat in WORKBENCH...
CREATE PROCEDURE `new_proced` (
in myid int(3)
)
BEGIN
if not exists (select id from table where id = myid)
then
show message 'Row no exists';
else
show message 'Row exists';
end if;
END
Not entirely sure why you would want to do something like that, but you could do something like this:
...
then
select 'YOUR MESSAGE HERE'
else
select 'YOUR OTHER MESSAGE HERE'
end if
Or you could select 1 or 0, might be a little better...
There is no Proper output statement provide in MySQL like in Oracle, we have DBMS_OUTPUT.PUT_LINE. So, to display any messages on the console, you can use SELECT statement as:
SELECT message;
Eg:
SELECT "WELCOME TO MySQL";
For debugging info from stored procedure in MySQL,there are following options through which you can do this.
1.Write into the file externally:
select "your_message" as log into outfile '/temp/brajesh.txt';
2.Use select command to print message:
select "result_message";
3.Use select command to print additional information with message:
select concat("Hello ! :", result);
4.Create addition table temp and push all message into it:
insert into temp select concat(result);
Example
drop procedure if exists display_name_procedure;
delimiter //
create procedure display_name_procedure(IN name_val varchar(65))
begin
declare result varchar(65);
set result := display_name_function(name_val);
create table if not exists temp (name_val varchar(65) not null);
insert into temp select concat(result);
select "penguin" as log into outfile '/temp/brajesh.txt';
select concat("Hello ! :", result);
end//
delimiter ;
DELIMITER //
create procedure
insert_data_student1(student_name varchar(50),email varchar(50),group_id int)
begin
if not exists(select email from student where email="email")
then
insert into student(student_name,email,group_id) values (student_name,email,group_id);
else
select 'all reday exists';
end if;
end //
DELIMITER ;
Consider the following table:
CREATE TABLE [dbo].[OrderingTest](
[ColKey] [int] IDENTITY(1,1) NOT NULL,
[Col0] [int] NULL,
[Col1] [int] NOT NULL,
[Col2] [int] NOT NULL
) ON [PRIMARY]
... and the following batch:
BEGIN
INSERT INTO OrderingTest(Col0,Col1,Col2)
VALUES (1,NULL,3);
SELECT SCOPE_IDENTITY();
END;
The Test table does not allow NULL values in Col1, so the insert will fail. I was hoping to test for failure using the value of SCOPE_IDENTITY() at this point. However, instead of seeing the SELECT SCOPE_IDENTITY() produce a single row with a NULL column as output, execution of the batch terminates after the failed insert and the SELECT SCOPE_IDENTITY() line is never executed.
UPDATE:
I was incorrect the result of SCOPE_IDENTITY() was displayed in the Results pane. I was confused, because SSMS switched the Messages pane into focus instead of the Results pane (since an error occurred).
However the latest value of the identity column, ColKey, is displayed instead of NULL after a failed INSERT. I thought SCOPE_IDENTITY() is supposed to return NULL if an INSERT fails.
I tried these commands:
BEGIN
DECLARE #theKey INT
BEGIN TRY
INSERT INTO OrderingTest(Col0,Col1,Col2)
VALUES (1,NULL,3);
SELECT #theKey = SCOPE_IDENTITY();
END TRY
BEGIN CATCH
SET #theKey = - 1
END CATCH
select #theKey
END;
And the following
BEGIN
DECLARE #theKey INT
SET #theKey = 1
INSERT INTO OrderingTest(Col0,Col1,Col2)
VALUES (1,NULL,3);
SELECT #theKey = SCOPE_IDENTITY();
select #theKey
END;
In both cases, the SELECT #theKey was executed, although in the second example, an error message was displayed to the print window. Note that in your example, you are trying to insert into the TEST table, rather than OrderingTest table. This will produce an error and not run the SELECT. Are you sure your example is right?
Note that in this example, SCOPE_IDENTITY returns the identity from the last successful INSERT, not NULL
BEGIN
INSERT INTO OrderingTest(Col0,Col1,Col2) VALUES (1,2,3);
INSERT INTO OrderingTest(Col0,Col1,Col2) VALUES (1,NULL,3);
SELECT SCOPE_IDENTITY();
END;