mysql declaring and setting variables. syntax errors - mysql

I thought this would be a simple task but i cannot figure out why this gives me an error in my syntax. Any help is appreciated.
DECLARE #usernameid VARCHAR(20);
declare #UserIDParam VARCHAR(20);
SET #usernameid = 'myid';
SET #UserIDParam =
(SELECT userid
FROM tblusers
WHERE unid = usernameid);
SELECT *
FROM tblusers
WHERE tblusers.userID = #useridparam

One doesn't DECLARE user variables: one just uses them. (You DECLARE local variables e.g. in a procedure).

Related

sql trigger unable to set variable from select

I know its asked question ,however I have tried few amendments but to no solution .
My trigger:
BEGIN
DECLARE bookid INT;
DECLARE roomtype varchar(20);
DECLARE amount INT;
DECLARE m_count INT;
DECLARE curr_m varchar(20);
SET #bookid := NEW.id;
SET roomtype := (SELECT title FROM pm_booking_room WHERE id_booking=#bookid);
SET amount := (SELECT amount from pm_booking_payment WHERE id_booking=#bookid);
SET #curr_m:= (MONTHNAME(NOW()));
SET #m_count:= (SELECT count(*) FROM pm_report WHERE month=#curr_m);
INSERT INTO `pm_report`(`month`, `room_type`, `amount`) VALUES(#curr_m,#roomtype,#amount);
END
whwn I check table, it inserts, but only #curr which is month name. Rest it inserts NULL
I tried
SET #roomtype SELECT title FROM pm_booking_room WHERE id_booking=#bookid but still same,NULL .
Also tried SET #roomtype := (SELECT title FROM pm_booking_room WHERE id_booking=#bookid); but still NULL.
I am using PhpMyadmin to create :
Please help.
Please be aware that roomtype and #roomtype are two different variables.
The variables you declare with the local variable DECLARE statement have a scope within the body of one stored routine. They are never spelled with a # sigil.
The user-defined variables with the # sigil have a scope of a MySQL session. You don't need to declare these kinds of variables. Just setting the variable to a value implicitly creates the variable.
You cannot SET roomtype = ... and expect that string to be read from the #roomtype variable. Nor vice-versa.
You appear to declare local variables, so you should use them consistently. But in some cases, your variable names are the same as column names, which will result in ambiguity if you use the variables in SQL statements that also reference tables with those columns. So you should adopt a naming convention to keep them distinct.
BEGIN
DECLARE v_bookid INT;
DECLARE v_roomtype varchar(20);
DECLARE v_amount INT;
DECLARE v_count INT;
DECLARE v_month varchar(20);
SET v_bookid := NEW.id;
SET v_roomtype := (SELECT title FROM pm_booking_room WHERE id_booking=v_bookid);
SET v_amount := (SELECT amount from pm_booking_payment WHERE id_booking=v_bookid);
SET v_month:= (MONTHNAME(NOW()));
SET v_count:= (SELECT count(*) FROM pm_report WHERE month=v_month);
INSERT INTO `pm_report`(`month`, `room_type`, `amount`) VALUES(v_month,v_roomtype,v_amount);
END
(This code is not tested, so apologies if there are any mistakes. It is meant only to demonstrate using non-sigil variables consistently.)

MySQL select from dynamic database and table query

Stored Proc Definition:
DECLARE dbName varchar(255);
DECLARE tableName varchar(255);
DECLARE fullPath varchar(255);
DECLARE conditions varchar(255);
SET dbName = idbname;
SET tableName = itablename;
SET fullPath = CONCAT("'",dbName,"'",'.',"'",tableName,"'");
SET checkExists = 0;
I am creating a stored proc where the dbname and tablename are dynamic, however I am stuck on the select aspect of this query.
I am trying to repalce the _test.user with values passed into the stored proc.
SELECT count(*) INTO checkExists FROM `_test`.`user` WHERE id = 1;
However this line throws an error
SELECT count(*) INTO checkExists FROM fullPath WHERE id = 1;
Error:
Procedure execution failed
1146 - Table 'dbname.fullpath' doesn't exist
I have also tried CONCAT() like this
set conditions = CONCAT('SELECT count(*) INTO ',checkExists, ' FROM ', fullPath, ' WHERE id=', 1);
However I can't figure out even how to use this in a select? Help is appreciated.
I like to do these modifications using replace(). Something like this:
replace(replace('SELECT count(*) INTO checkExists FROM `<dbname>`.`<tname>` WHERE id = 1',
'<tname>', v_tablename
), '<dbname>', v_databasename
)
You may also want to use v_fullpath somewhere. I'm not really sure what query you actually want to create.
I'm not sure why you have a variable called checkExists, when it seems to be the destination file. However, I would suggest that you prepend all your local variables with something to distinguish them from column names.

Stored procedure not updating table as expected

I am running a stored procedure on my MySQL database and it says it runs fine, no errors come back, but when I check the table it's supposed to have updated nothing has changed.
When I manually run each individual part of the procedure it works fine, I get back what I expect. All the selects run fine.
I'm fairly new in dealing with stored procedures so I'm not sure how to debug this. Can I get it to output the different stages it's at so I can make sure it gets to the update query? Can I check the results of the queries it's running?
I googled the issue but I didn't find anything helpful. The manual only had information on how to set the procedure up, not how to debug it when it wasn't working (unless I missed something).
This is my whole procedure:
DELIMITER //
CREATE PROCEDURE QuestionStatistics(IN quizId INT(11))
BEGIN
DECLARE bDone INT;
DECLARE qqId INT;
DECLARE totalAnswers INT;
DECLARE totalCorrect INT;
DECLARE totalValue INT;
DECLARE curs CURSOR FOR SELECT qqId FROM quizQuestions WHERE qqQuizId = quizId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
OPEN curs;
SET bDone = 0;
REPEAT
FETCH curs INTO qqId;
SELECT COUNT(*)
FROM quizAnswers
WHERE qaQuizQuestionId = qqId
AND qaIsMarked = 1
INTO totalAnswers;
SELECT COUNT(*)
FROM quizAnswers
WHERE qaQuizQuestionId = qqId
AND qaIsCorrect = 1
INTO totalCorrect;
SELECT SUM(qaValue)
FROM quizAnswers
WHERE qaQuizQuestionId = qqId
AND qaIsMarked = 1
INTO totalValue;
UPDATE quizQuestions
SET qqAveragePoints = ROUND(totalValue / totalAnswers, 2),
qqPercentageCorrect = ROUND(100 * totalCorrect / totalAnswers)
WHERE qqId = qqId;
UNTIL bDone END REPEAT;
CLOSE curs;
END//
DELIMITER ;
I'd appreciate it if anyone could point me in the right direction on how to debug this, or if they could spot the issue.
You can debug your procedure using debugger feature in dbForge Studio for MySQL (try trial version).
I suggest you to optimize your queries, e.g. use one SELECT query instead of three ones -
SELECT
COUNT(IF(qaIsMarked = 1, 1, NULL)),
COUNT(IF(qaIsCorrect = 1 , 1, NULL)),
SUM(IF(qaIsMarked = 1, qaValue, 0)
INTO totalAnswers, totalCorrect, totalValue
FROM
quizAnswers
WHERE
qaQuizQuestionId = qqId;
To avoid errors - do not use the same names for parameters, variables and object names like columns.
Also, try to avoid using cursors at all, write one complex UPDATE query.

SELECT INTO local variable undeclared?

I have the following in an sql file I am executing...
DECLARE rowcount INT;
SELECT COUNT(*) INTO rowcount
FROM VRG_PROBLEM_ACCOUNT PA
WHERE NEW.CustName = PA.CustNAME
AND NEW.AreaCode = PA.AreaCode
AND NEW.PhoneNumber = PA.PhoneNumber;
And yet I'm getting
ERROR 1327 (42000): Undeclared variable: rowcount
In another file I am doing the same type of SELECT...INTO localvariable and it works.
Local variables can only be declared inside of stored routines. You can use #-variables instead, which don't need to be declared at all:
SELECT COUNT(*) INTO #rowcount
FROM ...
How about re-writing your query a bit?
DECLARE rowcount INT;
SET rowcount = (
SELECT COUNT(*)
FROM VRG_PROBLEM_ACCOUNT PA
WHERE PA.CustNAME = NEW.CustName
AND PA.AreaCode = NEW.AreaCode
AND PA.PhoneNumber = NEW.PhoneNumber);
UPDATE 1*
I do not know your full code, but please keep in mind that DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.

Using #variable in mysql used as command in vb.net

I've used this type of query under VB.NET 2008, but everytime I run it, it always gives me a fatal error and it's telling me to declare the #variable I've used.
Below is the sample code:
select js.year, js.week, js.rem_balance,
case when js.rem_balance = 0
then #prev_rem_balance
else js.rem_balance
end as rem_balance_zero_or_prev,
#prev_rem_balance := js.rem_balance
from test_jos_stock js
inner join (SELECT #prev_rem_balance := 0) as t
order by year,week;
You need to declare the parameter before your select statement:
DECLARE #prev_rem_balance INT; --or whatever datatype it is
Then set it to be a specific value:
SET #prev_rem_balance = 1234;