mysql SELECT 0 or 1 when LIKE is found - mysql

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!

Related

PL/SQL Function, how to use SELECT INTO clause to declare variables from an existing table?

I would like to create a PL/SQL Function that calculates the age of any person from an existing table "Family tree" (Familienbaum), based on their Name. The Table has the needed Values Name, BirthYear (Geburtsjahr), YearOfDeath (Sterbejahr), etc.
Now I want to calculate the age of the person in two ways:
If the Person has a YearOfDeath, it should subtract the BirthYear from the YearofDeath to calculate
If the Person has no YearOfDeath, it should subtract the BirthYear from the Current System Year of the Oracle SQL Server
So far I have tried using the SELECT INTO clause to declare the variables needed for the calculation from the table Family Tree (Familienbaum):
CREATE OR REPLACE FUNCTION BerechneAlter(Person VARCHAR2)
RETURN INTEGER IS
BEGIN
SELECT Name, Sterbejahr, Geburtsjahr FROM Familienbaum
WHERE Person = Name;
RETURN (CASE
WHEN Sterbejahr IS NULL THEN (year(curDate()) - Geburtsjahr)
WHEN Sterbejahr IS NOT NULL THEN (Sterbejahr - Geburtsjahr)
END);
END BerechneAlter;
The SELECT INTO clause is giving me a lot of problems, does anyone know what needs to be changed in the syntax?
I also tried using cursors, but it seems more complicated than needed:
create or replace FUNCTION BerechneAlter(Person VARCHAR2)
RETURN INTEGER IS
Sterbejahr INTEGER;
Geburtsjahr INTEGER;
CURSOR SJ IS SELECT familienbaum.sterbejahr FROM familienbaum WHERE familienbaum.name=Person;
CURSOR GJ IS SELECT familienbaum.geburtsjahr FROM familienbaum WHERE familienbaum.name=Person;
BEGIN
OPEN SJ;
FETCH SJ INTO Sterbejahr;
CLOSE SJ;
OPEN GJ;
FETCH GJ INTO Geburtsjahr;
CLOSE GJ;
RETURN (CASE
WHEN Sterbejahr IS NULL THEN (2022 - Geburtsjahr)
WHEN Sterbejahr IS NOT NULL THEN (Sterbejahr - Geburtsjahr)
END);
END BerechneAlter;
If you are using a SQL SELECT statement within an anonymous block or function or procedure, etc (in PL/SQL - between the BEGIN and the END keywords) you must select INTO something so that PL/SQL can utilize a variable to hold your result from the query. It is important to note here that if you are selecting multiple columns, (which you are by "SELECT Name, Sterbejahr, Geburtsjahr"), you must specify multiple variables or a record to insert the results of your query into.
for example:
SELECT 1
INTO v_dummy
FROM dual;
SELECT 1, 2
INTO v_dummy, v_dummy2
FROM dual;
It is also worth pointing out that if your SELECT , ... FROM.... will return multiple rows, PL/SQL will throw an error. You should only expect to retrieve 1 row of data from a SELECT INTO.
In your case, it would look something like this (note - I haven't confirmed that your logic is correct, also note that I don't know your datatypes so you'll have to work on that bit too):
CREATE OR REPLACE FUNCTION BerechneAlter(p_person VARCHAR2)
RETURN INTEGER IS
v_name VARCHAR2(100);
v_sterbejahr VARCHAR2(100);
v_geburtsjahr VARCHAR2(100)
BEGIN
SELECT Name, Sterbejahr, Geburtsjahr
INTO v_name, v_sterbejahr, v_geburtsjahr
FROM Familienbaum
WHERE Name = p_person;
RETURN (CASE
WHEN v_sterbejahr IS NULL THEN (year(curDate()) - v_geburtsjahr)
WHEN v_sterbejahr IS NOT NULL THEN (v_sterbejahr - v_geburtsjahr)
END);
END BerechneAlter;
I think the function's logic is overcomplicated. You can get data and calculate age in an SQL statement, so only one var is needed.
create or replace function get_age(p_name varchar2) return number
is
l_aelter number;
begin
select nvl(sterbejahr, to_char(sysdate, 'YYYY')) - geburtsjahr aelter
into l_aelter
from familienbaum
where name = p_name;
return l_aelter;
end;
If using plsql is not required, you might wanted to use a standalone SQL statement to perform all the calculations you need:
select nvl(sterbejahr, to_char(sysdate, 'YYYY')) - geburtsjahr aelter
from familienbaum
where name = p_name;

How to make uppercase only the odd indexes of a string in MySQL?

I'm trying to make only the odd indexes of a string in uppercase (whereas the even indexes to be in lowercase) in MySQL.
For example: StackOverflow -> StAcKoVeRfLoW or hello -> HeLlO.
I found a way to this by extracting a letter at a time using the mid function, then concatenating based on which index the letter is at:
SET #x='hello';
SELECT #x as Initial,
Concat(ucase(mid(#x,1,1)),lcase(mid(#x,2,1)),ucase(mid(#x,3,1)),lcase(mid(#x,4,1)),ucase(mid(#x,5,1)))
as Final;
However I'm interested if there is a way to simplify this, since if the string would be larger then we would have some problems. So basically is there a way to modify it to something like:
Concat(ucase(mid(#x,odd index,1)),lcase(mid(#x,even index,1)))?
This is probably most simply done in your application, but can be achieved in MySQL. For MySQL 8+ you can use a recursive CTE to extract the individual letters from the string and GROUP_CONCAT to put them back together, changing the case on an alternating basis:
WITH RECURSIVE INITIAL AS (
SELECT 'StackOverflow' AS x
),
CTE AS (
SELECT 1 AS upper, SUBSTRING(x, 1, 1) AS letter, SUBSTRING(x, 2) AS remainder
FROM INITIAL
UNION ALL
SELECT 1 - upper, SUBSTRING(remainder, 1, 1), SUBSTRING(remainder, 2)
FROM CTE
WHERE LENGTH(remainder) > 0
)
SELECT GROUP_CONCAT(CASE WHEN upper THEN UPPER(letter) ELSE LOWER(letter) END SEPARATOR '') AS new
FROM CTE
Output:
StAcKoVeRfLoW
In versions lower than 8, you can use a user-defined function:
DELIMITER //
CREATE FUNCTION AlterCase(initial TEXT)
RETURNS TEXT
DETERMINISTIC
BEGIN
DECLARE i INT DEFAULT 1;
DECLARE l CHAR(1);
DECLARE new TEXT DEFAULT '';
WHILE i <= LENGTH(initial) DO
SET l = SUBSTRING(initial, i, 1);
SET new = CONCAT(new,
CASE WHEN i % 2 = 1 THEN UPPER(l) ELSE LOWER(l) END);
SET i = i + 1;
END WHILE;
RETURN new;
END //
DELIMITER ;
And call it as
SELECT AlterCase('StackOverflow')
Output:
StAcKoVeRfLoW
Note the function will work in MySQL 8+ too.
Demo on dbfiddle

use local variables in mysql IF statement

I modified the statements as below, but still errors at the line with the DECLARE statement.
BEGIN
DECLARE searchresult int(11);
SET searchresult=(Select count(*) from wbsimsynuqsql where SimBase='a cappella');
IF searchresult >0 THEN
Select * from simsyn1sql where BaseID = (Select Distinct BaseID from wbsimsynuqsql where SimBase='a cappella')
ELSE
Select * from simsyn1sql where BaseID = (Select Distinct BaseID from wbsimsynuqsql where SimSyn='a cappella')
END IF;
END
I am using the expression below in PHPMYADMIN with the intent to use it later in a PHP/MySQL application. It gives an error relating to the DECLARE statement in line 1.
I've looked at example declarations in MySQL and I don't see an error, but I'm doing something wrong and would appreciate a correction/suggestion.
DECLARE searchresult int(11);
SET searchresult=(Select count(*) from wbsimsynuqsql where SimBase='a cappella');
IF searchresult >0
{Select * from simsyn1sql where BaseID = (Select Distinct BaseID from wbsimsynuqsql where SimBase='a cappella')}
[ ELSE
{Select * from simsyn1sql where BaseID = (Select Distinct BaseID from wbsimsynuqsql where SimSyn='a cappella')} ]
END IF;
DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.
like inside a CREATE PROCEDURE you can use DECLARE
Your IF statement is missing a THEN
and remove the square brackets ([]) and the curly braces ({})
If your subquery returns more than one BaseID you might have to use IN instead of =
sqlfiddle

MYSQL stored procedure, case

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

how to calculate within a procedure by the result of two queries

I have a Table called TblOrders.the fields are FldSlNo, FldStrategyID, FldTradeServerName, FldBaseDir, FldBinaryStartTime, FldInstrumentID, FldOrderNumber, FldBuySell, FldDisplayQuantity, FldRemainingQuantity, FldTotalTradeQuantity, FldLastTradePrice, FldLastTradeQuantity, FldPrice, FldOrderTime, FldReferenceText and FldOrderStatusID. Now I have a procedure called ProfitCalculation.
the procedure is given below:
delimiter //
CREATE PROCEDURE ProfitCalculation
(
IN instrument INT(20) ,
OUT profit float(10,2)
)
BEGIN
DECLARE buy DECIMAL(10,2);
DECLARE sell DECIMAL(10,2);
DECLARE oprofit DECIMAL(8,2);
SELECT SUM(FldLastTradeQuantity*FldPrice)
FROM TblOrders
WHERE FldInstrumentID = instrument AND FldBuySell = 'b' AND FldLastTradePrice != 0 AND FldLastTradeQuantity != 0 group by FldInstrumentID INTO buy;
SELECT SUM(FldLastTradeQuantity*FldPrice)
FROM TblOrders
WHERE FldInstrumentID = instrument AND FldBuySell = 's' AND FldLastTradePrice != 0 AND FldLastTradeQuantity != 0 group by FldInstrumentID INTO sell;
SELECT (sell-buy) INTO oprofit;
SELECT oprofit INTO profit;
END
//
delimiter ;
It always return null.
Is there have any solution for this problem.
Please help me out..
Thanks in advance
First, on both of the queries, you're specifying a GROUP BY, but expecting a single result. Since you're already including the grouped field in the where clause, this is not necessary.
Secondly, try running the individual statements (without the 'INTO' statement) - my guess is that at least one of them is returning NULL, causing the output to be null. If you would prefer zero to NULL as an output with an empty recordset, wrap the SUM() statement in COALESCE, as in:
SELECT COALESCE(SUM(FldLastTradeQuantity*FldPrice), 0)
This way, if one of the two statements return NULL, the other one will still work.
Specifying the conditions FldLastTradePrice != 0 AND FldLastTradeQuantity != 0 are unnecessary, as they'd be handled within the SUM statement.