0

Here is a case where I am running SQL select statement on local string. If I run normal select query for my tables then it works.

select * from tablesname 

But if I have following case :

declare @string nvarchar(400)

set @string = N'from tablesname'

Now if I run select * from @string , it is not working as expected.

Please suggest me for to resolve this problem, since I want to run the select statement in this way only. If I should try some other way, then suggest me that.

Thanks, Tausif.

2
  • 1
    set @string = N'from tablesname' ? Commented Aug 16, 2012 at 7:30
  • It's better practice to make a stored procedure/tvf/whatever to select from each table, rather than one that selects from any (via a parameter and dynamic sql). I'm guessing that's what you're trying to achieve anyway... Commented Aug 16, 2012 at 7:33

1 Answer 1

1

Assuming you are using MySQL since your question is tagged with it, although this set @string = N'from tablesname' suggests, that you're using MS SQL Server or something:

SET @yourDynamicTablename = 'yourTable';
SET @sql = CONCAT('SELECT * FROM ', @yourDynamicTablename );
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

You might want to put that in a stored procedure.

Your attempt wasn't working, because you can't select from a string. For further reading about prepared statements, which are also useful for avoiding SQL injection attacks, have a look in the manual.

Sign up to request clarification or add additional context in comments.

Comments

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.