0

How can I get data from chosen table of my database? I'm going to work with database in c# application and I have the database includes that tables:

  1. MyTable1;
  2. MyTable2;
  3. ...

And I have tbl variable that is equal to tbl = "MyTable2";. I want to execute the code as following:select * from tbl


I try to execute this code:

SELECT   *
FROM     (
          SELECT TABLE_NAME
          FROM   information_schema.tables
          WHERE TABLE_NAME = 'MyTable1'
          );

But the code returned error that Every derived table must have its own alias


I want to get all data from table whose name is equal to my variable (tbl) and its value can also be changed. How can I do it?

1
  • @ADyson That won't do the job, because dynamic SQL is needed to build a query this way. Commented Apr 22, 2019 at 16:18

3 Answers 3

1

You might be able to do this using a prepared statement in MySQL:

SELECT TABLE_NAME
INTO @table
FROM information_schema.tables
WHERE TABLE_NAME = 'MyTable1';

SET @query = CONCAT('SELECT * FROM ', @table);
PREPARE stmt FROM @query;
EXECUTE stmt;
Sign up to request clarification or add additional context in comments.

1 Comment

You don't need to run the first query with PREPARE/EXECUTE, you can just run the query normally and store its result in the @table variable.
0
SELECT   *
FROM     (
      SELECT TABLE_NAME
      FROM   information_schema.tables
      WHERE TABLE_NAME = 'MyTable1'
      ) AS Blah

1 Comment

That solves the table alias issue, but it doesn't do what the OP wants, which is to substitute the table name and query from that table.
0

Try this:

DECLARE @SELECT nvarchar(500)
SET @SELECT = 'SELECT * FROM ' + @tbl
EXECUTE sp_executesql @SELECT

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.