Syntax error in mysql? - mysql

I'm used to MS sql so working with mySql is sure to throw some syntax error at me that is bound to slow me down. I have the following:
declare #expensesSum DOUBLE
select #expensesSum = sum(expenseAmount) from bondsaverdb.expenses
insert into bondsaverdb.expenses
select '6','Extracash',(income - #expensesSum) from bondsaverdb.income where userName ='Dean'
The error I'm getting says:
syntax error near declare #expensesSum
Must be the way I'm declaring the variable??
Thanks in advance!

MySQL does not require (or even allow, apparently) you to declare variables, and as far as I know it will treat all objects, variables included, as strings -- so they cannot be typed in t his way. Anyway, this should work:
SET #expensesSum = (SELECT SUM(expenseAmount) FROM bondsaverdb.expenses);
INSERT INTO
bondsaverdb.expenses
SELECT
'6', 'Extracash', (income - #expensesSum)
FROM
bondsaverdb.income
WHERE
userName = 'Dean'
I'm also not sure what that '6' is for .. if that's an auto increment ID you should omit it from the INSERT altogether (and specify the other columns to write to) or leave it NULL.

MySQL is very different to SQL Server; you don't declare variables generally
SET #expensesSum = (select #expensesSum = sum(expenseAmount) from bondsaverdb.expenses);
insert into bondsaverdb.expenses
select '6','Extracash',(income - #expensesSum) from bondsaverdb.income where userName ='Dean';

Related

MySQL - phpmyadmin - swap columns

I try swap 3 columns in my table. I try this :
DELIMITER $$
CREATE PROCEDURE px()
BEGIN
DECLARE temp VARCHAR(20);
update `idsaccess` set
temp = referer,
referer = size_var,
size_var = agent,
agent = temp
WHERE agent like '%210%' ;
END $$
CALL p
It don't work. It give me that error: Unknown column 'temp' in 'field list' I do not understand that: temp is varchar value not a column. I also try remove DECLARE and PROCEDURE and just set variable with #. Like this:
set #temp = '';
update `idsaccess`
set #temp = referer,
referer = size_var,
size_var = agent
agent = #temp
WHERE agent like '%210%'
It don't work either. It give me. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax. Any idea what is wrong in my code ? And to avoid misunderstanding I don't want move columns. I just want swap SOME rows (WHERE agent like '%210%') from one column to another.
Try this after taking a backup... I tried for table I have with 2 columns and worked
UPDATE idsaccess SET referer=#tmp:=referer, referer=size_var, size_var = agent, agent = #tmp WHERE agent like '%210%';

MySQL Routines in phpmyadmin - Unresolved Declare Error

I'm using phpmyadmin Routines to write a Stored Procedure called ViewUserAccounts.
I am continuously getting ambiguous error messages.
I have one IN parameter named USERNAME of type VARCHAR(45).
The text within the definition box includes:
DECLARE TempUserID INT DEFAULT 0
SET TempUserID = (SELECT idUser FROM User WHERE User.Username = USERNAME)
SELECT * FROM Account WHERE Account.idUser = TempUserID
Well...figured it out myself!
DECLARE requires a BEGIN and END and the DECLARE statement must be directly after the BEGIN statement. In addition, all lines required a semi-colon.

MySQL Syntax : "the right syntax to use near" - right in the beginning

I am a MySQL-noob and today I tried to setup a MySQL call which is more than 5 lines long. I keep getting syntax errors which I try to fix for hours, but I don't have a clue what the problem is. Here is the code:
USE myDatabase;
DELIMITER //
CREATE PROCEDURE MYPROC()
BEGIN
SET #ID = 1;
SET #maxID = 3;
CREATE TEMPORARY TABLE resultTable(v DOUBLE, ttc DOUBLE);
WHILE (#ID < #maxID) DO
INSERT partTable1.v, partTable2.ttc
INTO
resultTable
FROM
(SELECT * FROM
(((SELECT time_sec, v FROM speedTable WHERE (trip_id = #ID)) as partTable1)
INNER JOIN
((SELECT time_sec, ttc FROM sightsTable WHERE (trip_id = #ID)) as partTable2) ON
(0.04 > abs(partTable1.time_sec - partTable2.time_sec)))
);
SET #ID := #ID + 1;
END WHILE;
END //
DELIMITER;
CALL MYPROC();
SELECT * FROM resultTable LIMIT 100;
Is there anything obvious that needs to be corrected?
Update1: Added semicolon to the "CREATE.."-statement, now first three statements are OK.
Update2: Added 3 more semicolons!
Update3: Followed the suggestion to make it a function + separate function call. Error message changed!
Update4: I fixed the issues mentioned in the two answers. Still something wrong there. See updated code above and error message below.
Updated error message:
ERROR 1064 (42000) at line 4: You have an error in your SQL syntax; check the ma
nual that corresponds to your MySQL server version for the right syntax to use n
ear ' partTable2.ttc
INTO
resultTable
FROM
(SELECT * FROM
(((SELE' at line 11
Kind Regards,
Theo
Flow control statements, of which WHILE is one, can only be used within a stored procedure, but you are attempting to use it as a plain query via the console.
If you absolutely must take this path (using mysql instead of an application language), create a store procedure with the code you want, then call it.
Creating the procedure would look like this:
DELIMITER //
CREATE PROCEDURE MYPROC()
BEGIN
WHILE (#ID < #maxID) DO
SET #partTable1 = (SELECT time_sec, v FROM speedTable WHERE (trip_id = #ID));
SET #partTable2 = (SELECT time_sec, ttc FROM sightsTable WHERE (trip_id = #ID));
INSERT v, ttc INTO resultTable FROM
(#partTable1 INNER JOIN #partTable2 ON
(0.04 > abs(partTable1.time_sec - partTable2.time_sec)));
SET #ID := #ID + 1;
END WHILE;
END//
DELIMITER ;
Then to call it:
CALL MYPROC();
See this SQLFiddle of a simplified version of this working.
Note that you do have one syntax error:
#ID = #ID + 1; -- incorrect syntax
SET #ID := #ID + 1; -- correct
Still some syntactic problems and functionality problems...
You can't use WHILE in SQL scripts. You can use WHILE only in the body of a stored routine. See http://dev.mysql.com/doc/refman/5.6/en/flow-control-statements.html
You can't use SET to assign multiple columns to a scalar. MySQL doesn't support relation-valued variables, only scalar variables. See http://dev.mysql.com/doc/refman/5.6/en/set-statement.html
You can INSERT from the results of a query with a join, but the query must be introduced with SELECT. See http://dev.mysql.com/doc/refman/5.6/en/insert-select.html
You can't use session variables as the names of tables. You would have to use a prepared statement. See http://dev.mysql.com/doc/refman/5.6/en/prepare.html But that opens a whole different can of worms, and doing it wrong can be a security vulnerability (see http://xkcd.com/327). I wouldn't recommend you start using prepared statements as a self-described MySQL-noob.
This problem is probably simpler than you're making it. You don't need a temporary table, and you don't need to read the results one row at a time.
Here's an example that I think does what you intend:
USE myDatabase
SET #ID = 1;
SET #maxID = 3;
SELECT sp.v, si.ttc
FROM speedTable AS sp
INNER JOIN sightsTable AS si
ON (sp.trip_id = si.trip_id AND 0.04 > ABS(sp.time_sec - si.time_sec))
WHERE sp.trip_id BETWEEN #ID AND #maxID;

Lua & SQL Syntax Error

I'm trying both of these ways to run a SQL query with Lua using the GMod mysqloo library.
Each query is complaining about the line with the EXISTS() having an SQL syntax error.
local SQL6 = [[INSERT INTO accounts(UniqueID,Money)
VALUES(]]..UniqueID..[[,]]..StartingCash..[[)
WHERE NOT EXISTS(SELECT 0 FROM accounts WHERE UniqueID=]]..UniqueID..[[)]]
local SQL7 = [[IF Not EXISTS (SELECT * FROM accounts WHERE UniqueID=']]..UniqueID..[[')
BEGIN
INSERT INTO accounts(UniqueID,Money)
VALUES(]]..UniqueID..[[,]]..StartingCash..[[)
END
ELSE
BEGIN
SELECT * FROM accounts WHERE UniqueID=]]..UniqueID..[[
END]]
I don't know SQL but it seems that:
you need quotes around UniqueID in line 3 and 11, as in line 4.
you probably need a space or newline before the last END.

Mysql error: Not allowed to return a result set from a function

I am trying to have a conditional change in a parameter for update statement.
I am getting the following error when I try the following function
/home/y/bin/mysql -u root < testpri.sql > out
ERROR 1415 (0A000) at line 4: Not allowed to return a result set from a function
Contents of testpri.sql are as follows:
use `zestdb`;
DROP FUNCTION IF EXISTS UPDATEPASSWD;
DELIMITER //
CREATE FUNCTION UPDATEPASSWD(n INT) RETURNS varchar(255) DETERMINISTIC
BEGIN
DECLARE mypasswd varchar(255);
IF (n = 1) THEN
SET mypasswd = '12ccc1e5c3c9203af7752f937fca4ea6263f07a5';
SELECT 'n is 1' AS ' ';
ELSE
SET mypasswd = '1a7bc371cc108075cf8115918547c3019bf97e5d';
SELECT 'n is 0' AS ' ';
END IF;>
SELECT CONCAT('mypasswd is ', mypasswd) AS ' ';
RETURN mypasswd;
END //
DELIMITER ;
CALL UPDATEPASSWD(0);
What am I missing?
I think it's actually your debugging SELECT calls.
From the docs:
Statements that return a result set can be used within a stored procedure but not within a stored function. This prohibition includes SELECT statements that do not have an INTO var_list clause...
I arrived in search of answers to the same question, and found another way to work around the issue, so that I can use the SELECT statement that is the heart and soul of the MySQL function that elicited the warning.
Consider the following snippet.
SET intNMatches = ( SELECT COUNT(*) ...
SET coerces the SELECT statement to return its one and only column, a row count, into intNMatches, a local variable cast to BIGINT. Since it contains trade secrets, I can't show the rest of the query. Suffice it to say that the query installs without causing the MySQL engine to issue a warning.