Select in IF statement, MySQL - mysql

I'm trying to do something like this in My MySQL stored proc:
if val > SELECT numericalValue FROM table where userId=theUserId then ..
Is it ok to do that, or do I have to store numericalValue in a temporary?

You can have a select statement within an if statement.
It needs to be in parentheses and it must evaluate to a single row each time, so it works well for sums and counts, and if you are returning a field's value, you will want to use LIMIT 1
You could also use a variable, that would also work.

You shouldn't have to, but it would make things more convenient if you plan to reuse the selection elsewhere in your code.
Also, you should use the following syntax as a guideline:
CREATE PROCEDURE sp_condition(IN var1 INT)
BEGIN
IF (val > SELECT numericalValue FROM table where userId='theUserId')
THEN SELECT 'greater';
ELSE SELECT 'less than or equal';
END IF;
END|

Related

IF STATEMENT IN MYSQL INSERT is not working

Please, I do not understand why it is not working:
SET #key = (SELECT customer.key_stamp FROM customer WHERE customer.key_stamp = "0000");
CASE WHEN (#key > 0) THEN
INSERT INTO transaction
(transaction.to, transaction.key, transaction.type, transaction.cost_bitcoin, transaction.quantity)
VALUES ("0000", "f5rwsd", 2, 0.0075,
(500000 +
(
(SELECT bonus.amount
FROM bonus
WHERE 500000 BETWEEN bonus.min_quantity AND bonus.max_quantity
) / 500000
) * 100))
END;
I tried the CASE STATEMENT, but it still does not work, and i can't understand the issue.
Please help.
CASE is not a valid MySQL statement. (It's not a valid statement outside the context of a MySQL stored program.)
"Why it is not work"... is because it's not valid SQL.
A CASE expression can be used in a SQL statement where an expression is allowed. (In SQL, an expression returns a value of a particular datatype.)
As an example of using a CASE expression in a SQL statement, something like this:
SELECT CASE WHEN #key > 0 THEN 'somevalue' ELSE 'othervalue' END AS foo
in fact now i use just an sql functions, and it work now, all work, switch case mysql, if else statement mysql, and loops too, like while do, or LOOP ITERATE, all work, just need use it in sql functions, or sql procedure.

Is it possible to use a variable or parameter in a MySQL view?

I'm trying to create a View as following:
CREATE VIEW v_MyView
AS
SET #par_count := 0; -- XXX Working in SELECT, but not in a View !? XXX
SELECT
q1.day,
q1.count_per_day,
(#par_count := #par_count + q1.count_per_day) AS count_sum -- sums up count_per_day
FROM
(SELECT
DATE(registration_date_time_obj) AS day,
COUNT(Date(registration_date_time_obj)) AS count_per_day
FROM tbl_registration_data
GROUP BY day
ORDER BY day
) AS q1
;
The select statement itself works fine, just creating a view fails in MySQL since it doesn't accept user variables/parameters within it's declaration i guess.
Is there a way to still create this view with a workaround for the parameter?
Anyways, i'm able to create a similar procedure for the select statement, but that doesn't really solve the problem since i can't call the procedure in another select statement...
Thanks for your suggestions and solutions! (:
MySQL documentation is pretty clear that variables are not allowed:
The SELECT statement cannot refer to system variables or user-defined variables.
Within a stored program, the SELECT statement cannot refer to program parameters or local variables.
You can do what you want using a correlated subquery:
SELECT DATE(registration_date_time_obj) AS day,
COUNT(Date(registration_date_time_obj)) AS count_per_day,
(SELECT COUNT(*)
FROM tbl_registration_data rd2
WHERE rd2.registration_date_time_obj <= date_add(date(rd.registration_date_time_obj), interval 1 day)
FROM tbl_registration_data rd
GROUP BY day
ORDER BY day;
Please read the documentation on VIEWS >> https://dev.mysql.com/doc/refman/5.5/en/create-view.html
A view definition is subject to the following restrictions:
The SELECT statement cannot contain a subquery in the FROM clause.
The SELECT statement cannot refer to system variables or user-defined variables.
Within a stored program, the SELECT statement cannot refer to program
parameters or local variables.
The SELECT statement cannot refer to prepared statement parameters.
Any table or view referred to in the definition must exist. After the
view has been created, it is possible to drop a table or view that
the definition refers to. In this case, use of the view results in an
error. To check a view definition for problems of this kind, use the
CHECK TABLE statement.
The definition cannot refer to a TEMPORARY table, and you cannot
create a TEMPORARY view.
You cannot associate a trigger with a view.
Aliases for column names in the SELECT statement are checked against
the maximum column length of 64 characters (not the maximum alias
length of 256 characters).

Mapping MySql views to JPA Entitites, which unique id to use?

So I'v been using views instead of result queries as entities in my project and I know I'm not alone, so, my question:
What do you use to act as and #Id when working with views? Sometime the answer to that question will be trivial, but sometimes when you don't have a unique field that stands out, what do you guys do?
Right now I'm including more fields that I need in a particular view, so I can have a mix of fields that are unique together, and I use the #Id annotation on each of those, and so far it's been working great.
It seems to be so contextual, I'v been asking myself if there is a more standard way of doing it.
I don't think there is a standard way, but here is the approach that seems worths trying .
Idea is to generate unique "id" values (analog of rownum ) on the fly for the view . A bit modified version of function from Create a view with column num_rows - MySQL (modification done in order to reset rownum):
delimiter //
CREATE FUNCTION `func_inc_var_session`( val int) RETURNS int
NO SQL
NOT DETERMINISTIC
begin
if val = 0 THEN set #var := -1; end if;
SET #var := IFNULL(#var,0) + 1;
return #var;
end
//
Say we have a view definition (oversimplified for illustration purposes)
CREATE VIEW v_test1
SELECT a.field1
FROM test_table a
Modifying it to
CREATE VIEW v_test1
SELECT a.field1, func_inc_var_session(0) as rownum
FROM test_table a
would do the job; however, running select * from v_test within one session multiple times will give you sequential rownums, e.g. first time it starts with 1, second time with number of records in the view, etc.
To reset rownum I create another view (because of mysql view limitation - it cannot have subquery in FROM ) :
CREATE VIEW v_reset AS SELECT func_inc_var_session(1) ;
Now we can do
CREATE VIEW v_test1
SELECT a.field1, func_inc_var_session(0) as rownum
FROM test_table a, v_reset
(FROM clause processed first, func_inc_var_session(1) will be executed just once during the query, so it will reset rownum) .
I hope it helps.

How do I store a value from a SELECT statement in a variable in a MySQL Stored Procedure?

This may be a super easy question to answer, but I am unsure how to do this correctly.
Here is my query within the procedure:
SELECT COUNT(barcode) AS count FROM movieitems;
How do I store the return value of this statement (for example, the value in count is 5) into a variable? I want to be able to access the count value throughout the rest of my procedure.
In a stored procedure do this:
SELECT COUNT(barcode) AS count into #myVar FROM movieitems;
SELECT #someVariable := COUNT(barcode) FROM movie ...
You can then use #someVariable in other queries.
E.g.
SELECT * FROM some_table WHERE some_field > #someVariable;
And you can also manipulate the variable using SET:
SET #someVariable = #someVariable + 1;

IF condition in MYsql not giving proper result

This is code of mysql stored procedure:
BEGIN
DECLARE sms INT(100);
SET sms=(SELECT COUNT(1) FROM tbl_intofone_alert_transaction WHERE smsid='sms_id');
IF(sms<=>0) THEN
INSERT INTO tbl_intofone_alert_transaction(MSISDN,Message,Tag,SenderID,InTime,deliverystatus,
memberid,smsid,updatetime,submit_type,wu_id,DeviceID)
VALUES(mob,msg,tag,sender,NOW(),'0',memid,sms_id,NOW(),'NULL','NULL',DevId);
END IF;
END$$
IF CONDITION in above code doing insertion for all the cases . what i have done wrong here?
it must be
IF(sms<=0) THEN //sms less then or equal 0
or
IF(sms>=0) THEN //sms bigger then or equal 0
<=> this is not comparaison in mysql
obs
VALUES(mob,msg,tag,sender,NOW(),'0',memid,sms_id,NOW(),'NULL','NULL',DevId);
most of those values i dont know what they are , they looks wrong
they must be variables that u get them from your code.
in this code there is only NOW() and NULL which are right
Are you sure that you want to search for the string literal 'sms_id' here?
SELECT COUNT(1) FROM tbl_intofone_alert_transaction WHERE smsid='sms_id'
Probably you meant to use the value of the sms_id variable:
SELECT COUNT(1) FROM tbl_intofone_alert_transaction WHERE smsid = sms_id