5

Why I'm getting this error?

CREATE DEFINER=`root`@`localhost` PROCEDURE `selectrecords`(tablename varchar(50))
begin
set @table_name=tablename;
set @sql_text=concat('Select * from @table_name');
prepare statement from @sql_text;
execute statement;
deallocate prepare statement;
end

Error:

....to use near '@table_name' at line 1

My code is correct but I don't understand why....

7
  • I don't think you can use variables for table names in dynamic sql. In Oracle you sure can't at all. I think you have to concatenate, see JW's answer Commented Mar 28, 2013 at 15:10
  • @Sebas: What if I am using "delete frrom....where" , JW's answer is still acceptable? Commented Mar 28, 2013 at 16:59
  • yes, I think he pretty much answered all your questions. Commented Mar 28, 2013 at 17:06
  • I'm getting error with this: "set @sql_text = concat('Delete from ', tablename, 'WHERE id = pid');" "pid int"--> is included in parameter..Any help? Commented Mar 28, 2013 at 17:08
  • add a space before WHERE Commented Mar 28, 2013 at 17:11

1 Answer 1

4

I think you mean,

CREATE PROCEDURE `selectrecords`(tablename varchar(50))
begin
    set @sql_text = concat('Select * from ', tablename);
    prepare statement from @sql_text;
    execute statement;
    deallocate prepare statement;
end

even in dynamic sql, you cannot parameterized table names as well as column names so your only choice is to concatenate in with the string. Only values can be place in a place holder.


UPDATE 1

CREATE PROCEDURE `selectrecords`(tablename varchar(50))
begin
    set @val = idnumber;
    set @sql_text = concat('Select * from ', tablename, ' WHERE id = ?');
    prepare statement from @sql_text;
    execute statement USING @val;
    deallocate prepare statement;
end
Sign up to request clarification or add additional context in comments.

8 Comments

What if I want to include the id in parameter? Let us say I want to query like this "Delete from tablename where id =idnumber" ?
SET @sql = 'Delete from tablename where id = ?' you can place the value of idnumber in a placeholder.
I mean I am still using that code above but this time with where clause . How to concat including where ?
Thanks! You are really a geek :)
One more thing, I want to include 'id int' in my parameter and delete a record in my database, is this right? "SET @sql=concat('Delete from', tablename,' Where id=pid');
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.