Jump to content

summing using dynamic sql


Go to solution Solved by requinix,

Recommended Posts

i have this table:

MatchID | PlayerID | Goals
 2         1          4
 2         3          3
 2         13         0
 2         9          0
 2         5          0

iam trying to get total  using dynamic sql query like so:

DECLARE TotalVariable INT;
SET @l_sql_total=CONCAT(' SELECT SUM(x.Goals) into ',TotalVariable,' FROM a');

but iam getting an error:

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 'NULL' at line 1

And when I change to this:

SET @l_sql_total=CONCAT(' SELECT SUM(x.Goals) into TotalVariable FROM a');

i get this error despite the fact that it has already been declared above:

ERROR 1327 (42000): Undeclared variable: TotalVariable

how can I clear this?

Link to comment
Share on other sites

  • Solution

When it doubt, RTFM.

Because local variables are in scope only during stored program execution, references to them are not permitted in prepared statements created within a stored program. Prepared statement scope is the current session, not the stored program, so the statement could be executed after the program ends, at which point the variables would no longer be in scope. For example, SELECT ... INTO local_var cannot be used as a prepared statement. This restriction also applies to stored procedure and function parameters.

Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.