IF EXISTS Receiving Error - mysql

I am trying to run the following SQL cmd but am receiving ERROR 1064 (42000):
IF EXISTS(select 1 from namelist WHERE user='smitht' AND name='Tom Smith') BEGIN PRINT 'yes' END;
I've tested the select statement on its own and it works, so I'm not sure why I'm receiving this error.
Any ideas?

That is not how you use IF EXISTS in MYSQL. You may try this:
SELECT IF( EXISTS(
SELECT *
from namelist WHERE user='smitht' AND name='Tom Smith'))

According to the document you can't use IF statement like that, but you can use IF function:
SELECT IF (EXISTS(
select 1 from namelist WHERE user='smitht' AND name='Tom Smith'), 'yes', '')

Related

mysql error on run query

This is my query in mysql (I use phpmyadmin to execute the query).
but I can't execute....
can help me please?
SELECT count(*) into #cnt FROM `oie_option` WHERE `opt_name` =CONCAT('earning1391',pmonth('2015-09-09')))
if(#cnt <=0)then
INSERT INTO oie_option ('opt_name','opt_value') VALUES (CONCAT('earning1391',pmonth('2015-09-09')),1000);
end if;
And this is the 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 ')
if(#cnt <=0)then
insert into oie_option ('opt_name','opt_value') values(CON' at line 1
Why?
Thanks
I think you are missing a semicolon in first query.
SELECT count(*) into #cnt FROM `oie_option`
WHERE `opt_name` =CONCAT('earning1391',pmonth('2015-09-09'));
if(#cnt <=0)then
INSERT INTO oie_option ('opt_name','opt_value') VALUES
(CONCAT('earning1391',pmonth('2015-09-09')),1000);
end if;
I tryed to reproduce your situation and this is what I got:
You need to put your code inside of a strored procedure or function to use the IF statement https://stackoverflow.com/a/12954385/5308054.
Here you can see a feature request to fix it https://bugs.mysql.com/bug.php?id=48777
You could avoid using the if statement with query like this
INSERT INTO oie_option ('opt_name','opt_value')
SELECT CONCAT('earning1391',pmonth('2015-09-09')),1000
FROM oie_option
WHERE (SELECT count(*) FROM `oie_option` WHERE `opt_name`=CONCAT('earning1391',pmonth('2015-09-09')))=0
LIMIT 1;
I declared the variable and corrected.
DECLARE cnt INT DEFAULT 0;
SELECT count(*) INTO cnt FROM `oie_option` WHERE `opt_name` = CONCAT( 'earning1391', pmonth (now()));

store function creation error in mysql #1064

I tried to create one function, ie if username exist, will return random number and character as a single string, but I tried below code, throwing syntax error like below, can u help to find the issue, I know that having issue in declaring string and returning string, but unable to find the issue. Thanks to the replies in advance
DELIMITER //
create function verifyEmail(userName varchar(25))
RETURNS TEXT
BEGIN
if EXISTS(select * from userdetails where name = userName)
then
SELECT #randomPass := select concat( char(round(rand()*36)+1), char(round(rand()*36)+1), char(round(rand()*36)+1));
return #randomPass;
else
return "not_exist";
end if;
end //
DELIMITER //
#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 'select concat( char(round(rand()*36)+1), char(round(rand()*36)+1), char(round(ra' at line 6
You are missing a closing ) on this line:
SELECT #randomPass := select concat( char(round(rand()*36)+1), char(round(rand()*36)+1), char(round(rand()*36)+1);
should be
SELECT #randomPass := select concat( char(round(rand()*36)+1), char(round(rand()*36)+1), char(round(rand()*36)+1));
Hooray, finally found answers.. This below code will help to solve the solution
DELIMITER //
create function verifyEmail(userName varchar(25))
RETURNS TEXT
BEGIN
DECLARE randomPass VARCHAR(8);
if EXISTS(select id from userdetails where name = userName)
THEN
SET randomPass = concat( char(rand()*25+65),char(rand()*25+65),char(rand()*25+65),char(rand()*25+65),char(rand()*25+65),char(rand()*25+65),char(rand()*25+65),char(rand()*25+65));
return randomPass;
else
return "not_exist";
end if;
end //
DELIMITER //

using IF in MySQL (not the function)

I have what feels like a simple question, but can't seem to get it right. I'm just trying to execute a regular IF ... THEN ... logic, but can't seem to get it right:
set #var:=2;
if #var=1 THEN select 'hello';
I get:
ERROR 1064 (42000):
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 'if #var=1 THEN select 'hello'' at line 1
What am I missing?
You can use CASE instead.
SET #var:=2;
SELECT CASE WHEN #var=1 THEN 'hello' ELSE 'no hello' END;
--prints 'no hello'
SET #var:=2;
SELECT CASE WHEN #var:=1 THEN 'hello' ELSE 'no hello' END;
--prints 'hello'
I hope the idea is clear with above examples.
Edit: to address OP's additional concerns, You can incorporate selects in case statements, but you should enclose in brackets. For eg.
SET #var:=2;
SELECT CASE WHEN #var:=1 THEN (select 'hello') ELSE (select 'no hello') END;
One thing to notice is that it should return back only one value (from one row and a column)
You can, but only inside of functions, procedures and triggers like so:
DELIMITER //
DROP PROCEDURE IF EXISTS anyname//
CREATE PROCEDURE anyname()
BEGIN
IF #var1 = 1 THEN
SELECT 'hello';
END IF;
END//
SET #var1 := 1;
CALL anyname()//

mySQL If statement

I am trying to make this If Statement work, but I can't seem to make it do what I want. If I do a select #result, It'll give me the value 0, then why doesn't the IF statement work?
SET #message = '((sometihng here))';
select LEFT(#message, 1) into #firstChar;
select STRCMP(#firstChar,'(') into #result;
IF (#result = 0) THEN
SET #message = 'true';
//more selects and cals here;
END IF;
select #message;
I should get true, but I don't it shows me an error:
SQL query: IF( #result =0 ) THEN SET #message = 'true';
MySQL said:
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 'IF (#result = 0) THEN SET #message = 'true'' at line 1
try use function http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if
SELECT IF(#result = 0, 'true', '((something here))') AS message
As Max Mara pointed out, that's a good work aroud. The reason the IF wasn't working is not because the syntax is incorrect, but because flow control functions like IF ... THEN are only valid inside of stored procedures or functions, All this thanks to #TehShrike
The IF .. THEN .. ELSE syntax in MySQL is only available for procedural code (stored precudures, functions, triggers..), but not for SELECT statements.
IF ELSE USED IN STORED PROCEDURE EXAMPLE BELOW
DELIMITER //
CREATE PROCEDURE NAME(IN Number INT)
BEGIN
IF roll= 1
THEN SELECT * FROM table1 WHERE id = roll;
ELSE
SELECT * FROM table2 WHERE id = 2;
END IF;
END //
DELIMITER ;

EXECUTESQL error

Here is the following piece of code that I am trying to execute on SQL Server.
DECLARE #string NVARCHAR(MAX) = '
CREATE PROC [dbo].[Trend]
#slsID NVARCHAR(20)
AS
BEGIN
SET NOCOUNT ON
DECLARE #BeginningRange varchar(20),
#EndingRange varchar(20)
SET #EndingRange = ''12*13''
SET #BeginningRange = ''12*02''
;WITH CTE1 AS(
SELECT
dbo.Field1,dbo.Field2,dbo.Field3
FROM dbo.Table1 join dbo.Table2 where...conditions
weekNum BETWEEN (#BeginningRange) AND (#EndingRange)
)
SELECT * FROM CTE1
UNPIVOT
( numbers for type in (Field1, Field2, Field3, Field4)
) as p PIVOT
(
Sum(numbers) for
WeekNum in ([12*02],[12*03],[12*04],[12*05],[12*06],[12*07],[12*08],[12*09],[12*10], [12*11],[12*12],[12*13])
) as q
END
'
EXECUTE SP_EXECUTESQL #STRING
When I try to run this, it errors out saying that
"Incorrect syntax near the keywor 'as'"
I took this code out and executed it separately and it didn't error out. Am I missing something here?
Look like missing parentheses around the parameter to the procedure.
One trick you can use is the print out the sql statement and then try to run that - the error message might give you more info
print #STRING
PIVOT and UNPIVOT clauses each require two closing parentheses.
UNPIVOT (... FOR ... IN (...) ) AS ...
PIVOT (... FOR ... IN (...) ) AS ...
where...conditions
This won't pass a syntax check. If you have removed the actual conditions it may be that this is where your error is. And:
dbo.Table1 join dbo.Table2
has no ON clause
I saw both of these by doing a syntax check on the results of print #string which is the first step you should have taken to find the issue. I still say that based on what you gave us there is no reason at all to use dynamic SQl and it is a poor practice to use dynamic SQL if you don't need it.