MYSQL stored procedure, case - mysql

I've consulted this page: http://dev.mysql.com/doc/refman/5.1/en/case.html as well as this one, but can't get a simple procedure to work....
UPDATE:
To clearify what I want to do: I want to select all rows from a table where the field id is either 1, 0 or could be either of them. This is specified by an input parameter to the procedure, which takes values 0,1 or 2.
So if _id = 0 I want:
select * from TABLE where id = 0
If _id = 1 I want:
select * from TABLE where id = 1
And if _id = 2 I want:
select * from TABLE where id in (0,1)
I was hoping I could get the rest of it to work by myself if I only got the simple case-statement below to work...
What I want to do is something like:
begin
select * from TABLE where
case _id
when 0 then id=0
else id = 1
end as id
end
which gives error "You have an error in your SQL syntax".
I've also tried:
begin
select * from TABLE where
case _id
when 0 then id=0
else id=1
end case
end
which gives the same error. Obviously I've got the wrong syntax somewhere, but I can't figure out where... Can anyone help me out?
Thanks,
Niklas

Try this:
begin
select *,
case _id
when 0 then 0
else 1
end as id
from table
end
When used as part of a SELECT query, WHEN is not a statement, it's a control flow function.
You can also express this as:
begin
select *, _id != 0 as id
from table
end

build the query to look like this... mySQL case have a different syntax from C and Java...
set #input=2;
select * from foo
where
case when #input =2 then value in ( 1, 0) else
value = #input end;
live demo with sql fidle

Related

mysql SELECT 0 or 1 when LIKE is found

I'm looking for a way to return a 0/1 when a LIKE is found.
I had it working with a CASE IF statement on a different query which uses a MATCH AGAINST. But I can't seem to get this working.
for example: this worked in the SELECT part of the query.
SELECT *, (CASE WHEN IF((MATCH (name) AGAINST ("rubert" IN BOOLEAN MODE))>=1, 1, 0) = 1 THEN 1 ELSE 0 END) as r2....
But i'm looking for a 0 or a 1 against a LIKE.
eq.
SELECT *, (CASE WHEN IF (name LIKE "%rubert%") == FOUND) THEN 1 ELSE 0 END) as found FROM....
Have a feeling i'm really close, but seem not to get it exactly...
You're overcomplicating it.
SELECT name LIKE '%rubert%' FROM...
In MySQL, all booleans are represented as 1 or 0, and LIKE returns a boolean. No work needed.
The reason your MATCH query needs an IF is the fact that MATCH returns a float, not a boolean; otherwise, this would be enough:
SELECT MATCH name AGAINST ('rubert' IN BOOLEAN MODE) AS score FROM...
To whittle it down though, you're going through both IF and CASE, which is totally too much, as this is enough:
SELECT IF(MATCH name AGAINST ('rubert' IN BOOLEAN MODE) > 1, 1, 0) AS goodenough FROM...
You can wrap it by function
USE `test`;
DROP function IF EXISTS `is_exists`;
DELIMITER $$
USE `test`$$
CREATE FUNCTION `test`.`is_exists` (q varchar(50))
RETURNS INTEGER
BEGIN
DECLARE is_exist INT(11);
DECLARE que varchar(50);
SELECT CONCAT("%",q,"%") INTO que;
SELECT count(*) into is_exist FROM `test`.`users` WHERE `fname` LIKE que;
IF is_exist >0 THEN
RETURN 1;
ELSE
RETURN 0;
END IF;
END;$$
DELIMITER ;
And than
SELECT is_user_exists("your query");
Good luck!

Add ELSE in SELECT statement MySQL

So what Im trying is to add ELSE or the kind of condition that adds the exeception to the current rule. I have this before insert trigger right now:
SET new.perfId = (SELECT cust.webId FROM cust where cust.regTime=new.regTime);
I would like to add an ELSE to that statement, something like:
SET new.perfId = (SELECT cust.webId FROM cust where cust.regTime=new.regTime) ELSE blabla
How should this be set in order query is correct?
Thank you.
If you mean, that your condition is that the select doesn't return null, you can use coalesce().
SET new.perfId = COALESCE((SELECT cust.webId FROM cust where cust.regTime=new.regTime), 'blabla');
COALESCE() returns the first of its parameters which isn't NULL.
You could use COALESCE:
From the docs:
Returns the first non-NULL value in the list, or NULL if there are no
non-NULL values.
mysql> SELECT COALESCE(NULL,1);
-> 1
mysql> SELECT COALESCE(NULL,NULL,NULL);
-> NULL
You would end up with:
SET new.perfId = (SELECT COALESCE(cust.webId,"BLABLA")
FROM cust where cust.regTime=new.regTime);

SQL query with variable ,IF & select staement

How can I create an SQL select query to return variable as true(1) if a column value exists in a table else false(0).
I want to use this variable in my scripts so that
if variable=1
execute A
ELSE
execute B
In Oracle you can use something like this
SELECT
CASE nvl(length(column1), 0)
WHEN 0 THEN 0
ELSE 1
END AS column1
FROM yourTableName;
You can try this...
IF ((SELECT COUNT(*) FROM TableName WHERE FieldName = 'Whatever') <> 0)
-- Execute something if column value exists
ELSE
-- Execute something if column value does not exist
SELECT CASE WHEN EXISTS(SELECT 1 FROM tableName WHERE fieldName='value') THEN 1;
ELSE 0;
END
INTO variable
--that is PostgreSQL

mysql trigger with select from database and update a column

I have this trigger. If the incoming log agrees with input filter, than is not saved into database. But, I want to keep number of "hits" of each Primitive_filter. I have a column named hit_rate, which is int(30). Is there some way how to do that? Maybe specific error? Or sth else? Thx for help.
UPDATE Primitive_filters SET hit_rate = hit_rate + 1 where Primitive_filters.id = ???;
trigger
delimiter //
CREATE TRIGGER inputFilter
before insert
on Logs
for each row
begin
declare msg varchar(255);
IF (SELECT COUNT(*) FROM Primitive_filters, Primitive_in_filter, Filters WHERE
Filters.name = "input" AND Filters.id = Primitive_in_filter.id_filter AND Primitive_in_filter.id_primitive = Primitive_filters.id AND
(Primitive_filters.id_host LIKE CONCAT('%',(SELECT host FROM Hosts WHERE id = new.id_host),'%') OR Primitive_filters.id_host IS NULL) AND
(Primitive_filters.facility LIKE CONCAT('%',new.facility,'%') OR Primitive_filters.facility IS NULL) AND
(Primitive_filters.priority LIKE CONCAT('%',new.priority,'%') OR Primitive_filters.priority IS NULL) AND
(Primitive_filters.program LIKE CONCAT('%',new.program,'%') OR Primitive_filters.program IS NULL) AND
(new.msg REGEXP Primitive_filters.msg OR Primitive_filters.msg IS NULL)) > 0 THEN CALL raise_error; END IF;
END //
delimiter ;
This is NOT the answer to your question.
It's only a hint how to fix a potentially serious performance problem in your code.
Don't use this:
IF (SELECT COUNT(*) FROM ... giant query ...) > 0
THEN CALL raise_error;
END IF;
Use this instead:
IF EXISTS (SELECT 1 FROM ... giant query ...)
THEN CALL raise_error;
END IF;
The former condition calculates a count ... it must read all rows returned by the query
If the query returns billion rows, it must reads them all --> because you asked give me a count of rows.
Then, after the query return the count, there is a check: if the query returns at least one row, then do something.
The latter condition stops executing the query when the query returns first row, saving time and resources.

MySQL 5.5 Query Based on IF statement

I've been battling with this for too long so I'm here to ask for help...
I have a MySQL stored procedure that I want to do the following:
given an 'id' and a 'username' for a given record
if id does not exist in table then create record
else if id exists and username is not the same as what exists then update record
else do nothing
I've tried the following:
BEGIN
DECLARE doCreate INT;
DECLARE doUpdate INT;
SELECT COUNT(*) INTO doCreate FROM app_user WHERE id=1;
IF (doCreate > 0) THEN
SELECT COUNT(*) INTO doUpdate FROM app_user WHERE id=1 AND username='other';
END IF
IF(doCreate = 0) THEN ---SYNTAX ERROR ON THIS LINE---
SELECT 'CREATE';
ELSE IF(doUpdate = 0) THEN
SELECT 'UPDATE';
ELSE
SELECT 'NOTHING';
END IF
END
I've also tried replacing the if-elseif-else block with a case statement but get the same result...
CASE ---ERROR ON THIS LINE---
WHEN doCreate = 0 THEN
SELECT 'CREATE';
WHEN doUpdate = 0 THEN
SELECT 'UPDATE';
ELSE
SELECT 'NOTHING';
END
I seem to get a syntax error on anything that comes after the first END IF, so that's the first problem that occurs...
Any help would be appreciated - I'm sure there's a better way to do this.
I believe you'll need to terminate the END IFs with ;, and internally ELSEIF should be one word. Otherwise, another END IF is needed, but not found.
IF (doCreate > 0) THEN
SELECT COUNT(*) INTO doUpdate FROM app_user WHERE id=1 AND username='other';
END IF; /* terminate with ; */
IF(doCreate = 0) THEN
SELECT 'CREATE';
ELSEIF(doUpdate = 0) THEN
SELECT 'UPDATE';
ELSE
SELECT 'NOTHING';
END IF; /* terminate with ; */
Look over the MySQL IF/ELSE syntax reference for various usage examples.