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.
Related
WHAT
I'm on MySQL 5.6 and my account only has permissions for SELECT and USAGE (as found using the SHOW GRANTS command).
Presumably because of this using DECLARE before SELECT returns a generic syntax error.
WHY
I want to use variables to both make the code easier to read and maintain.
Below you can see variable #isOwn is needed in WHERE clause and the day differences could be shortened (note: DATEDIFF didn't work for me in WHERE for some reason)
QUESTION
Being able to declare the variables before SELECT would simplify everything.
Am I doing something wrong or can I not do this because of my minimal permissions?
CODE EXAMPLE
DECLARE #test INT = 5 -- <<< syntax error
SELECT
CASE
WHEN #isOwn := sp.`name` LIKE 'TST %'
THEN 'O' ELSE 'S'
END AS 'Group',
st.`name` AS 'Type',
COUNT(st.`name`) AS 'Count',
DATE(MIN(os.endTime)) AS 'From',
CASE
WHEN #isOwn
THEN TO_DAYS(CURRENT_DATE) - TO_DAYS(MIN(os.endTime)) - 3 + 1
ELSE TO_DAYS(CURRENT_DATE) - TO_DAYS(MIN(os.endTime)) - 28 + 1
END AS 'DO'
FROM tdb.orders AS os
LEFT OUTER JOIN tdb.shipment_type AS st
ON (st.ID = os.shipmentType_ID)
LEFT OUTER JOIN tdb.suppliers AS sp
ON (sp.ID = os.supplier_ID)
WHERE
os.proof IS NULL
AND os.endTime IS NOT NULL
AND ((
sp.`name` NOT LIKE 'TST %' AND
(TO_DAYS(CURRENT_DATE) - TO_DAYS(os.endTime)) >= 3
) OR (
sp.`name` NOT LIKE 'TST %' AND
(TO_DAYS(CURRENT_DATE) - TO_DAYS(os.endTime)) >= 28
))
AND YEAR(os.endTime) = YEAR(CURRENT_DATE)
GROUP BY
CASE
WHEN sp.`name` LIKE 'TST %'
THEN 'O' ELSE 'S'
END,
st.`name`
Use SET keyword instead of DECLARE. The latter is only needed in stored procedures and functions, to define local variables.
You need an user variable, which is different, for example it is not required to define it and it has no strict type. User variables have # prefix, local variables don't. But you can still access it, even from stored procedures/functions.
Also, as commented, you need to separate the two statements (SET and SELECT) with a delimiter ; (or perhaps call them as two statements on the same connection).
Is
IF(CS2_PDM_D_Mini IS NULL,0,CS2_PDM_D_Mini)
equal
COALESCE(CS2_PDM_D_Mini),0)
Because of Postgres doesn't understand IF, I have plenty of MySQL IF statements into one SQL query, to transmute into a thing that PostgreSQL accepts
If you want to mock up Mysql IF format, use CASE WHEN THEN END, like here:
t=# select case when CS2_PDM_D_Mini is null then 0 else CS2_PDM_D_Mini end ;
Check out docs for both CASE and COALESCE:
The COALESCE function returns the first of its arguments that is not
null
IF is pl/PgSql statement
I want to run a case statement that runs different SELECT Statements Based on a condition in Spark SQL but not able to get the Syntax Right .
My SQL statement looks like this
registerTable(sql="SELECT CASE WHEN typedKeyword > '' THEN (SELECT * FROM `temp.sdf0` WHERE originalKeyword > ''AND keyword > '' AND deviceType = 'devicetype' ) ELSE (SELECT * FROM `temp.tes` WHERE originalKeyword > ''AND keyword > '' ) END ",alias="temp.test")
I don't know if CASE statement is supported in spark SQL so How can one achieve this
I've worked in nearly a dozen SQL and SQL-like dialects and I've never seen syntax like that. It looks like there's a core misunderstanding of what SQL clauses are supposed to do what.
The SELECT clause is for describing a projection of scalar elements. In many dialects you can issue subqueries - sometimes even correlated subqueries - in this clause, but you always must apply an operator that converts the result into a scalar value. For example:
SELECT (CASE WHEN EXISTS (SELECT foo FROM tbl) THEN 1 ELSE 0 END)
Here the "EXISTS" operator converts the uncorrelated subquery into a scalar boolean, so it's legal.
The lack of a FROM clause in the top level query is also a big red flag. It, or some analogue like Oracle's "dual", is legal in about half of the dialects I've seen, but if what you're trying to do is dynamically switch between two queries, you're almost certainly doing it wrong. juergen is right - what you probably meant to do is use 2 different queries.
I need to query data from a second table, but only if a rare set of conditions in the primary table is met:
SELECT ..., IF(a AND b AND c AND (SELECT 1 FROM tableb ...)) FROM tablea ...
a, b, and c conditions are almost always false, so my thinking is the subquery will never execute for most rows in the result set and thus be way faster than a join. But that would only true if the IF() statement short circuits.
Does it?
Thanks for any help you guys can provide.
The answer is YES.
The IF(cond,expr_true,expr_false) within a mysql query is short-circuited.
Here a test, using #variables to prove the fact:
SET #var:=5;
SELECT IF(1 = 0, (#var:=#var + 1), #var ); -- using ':=' operator to modify 'true' expr #var
SELECT IF(1 = 1, #var, (#var:=#var + 1) ); -- using ':=' operator to modify 'false' expr #var
SELECT #var;
The result is '5' from all three SELECT queries.
Had the IF() function NOT short circuited, the result would be a '5' from SELECT #1, and '6' from SELECT #2, and a '7' from the last "select #var".
This is because the 'true' expression is NEVER executed, in select #1 and nor is the false expression executed for select #2.
Note the ':=' operator is used to modify an #var, within an SQL query (select,from, and where clauses). You can get some really fancy/complex SQL from this. I've used #vars to apply 'procedural' logic within a SQL query.
-- J Jorgenson --
With J. Jorgenson's help I came up with my own test case. His example does not try to short circuit in the condition evaluation, but using his idea I came up with my own test and verified that MySQL does indeed short-circuit the IF() condition check.
SET #var:=5;
SELECT IF(1 = 0 AND (#var:=10), 123, #var); #Expected output: 5
SELECT IF(1 = 1 AND (#var:=10), #var, 123); #Expected output: 10
On the second example, MySQL is properly short-circuiting: #var never gets set to 10.
Thanks for the help J. Jorgenson!
It depends.
IF doesn't short-circuit such that it can be used to avoid truncation warnings with GROUP_CONCAT, for example in:
set ##group_concat_max_len = 5;
select if(true or #var:=group_concat('warns if evaluated'), 'actual result', #var);
the result will be 'actual result' but you'll get a warning:
Warning (Code 1260): Row 1 was cut by GROUP_CONCAT()
which is the same warning you get with less trivial GROUP_CONCAT expressions, such as distinct keys, and without the IF at all.
Try it in the SQL analyzer. If you want to be on the safe side and not have to trust the database to work one way (and not to change that behavior ever in new versions), just make two queries and do the IF programmatically.
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|