Get table name from database field

I am using SQL Server Management Studio 17.0. I have a table that manages separate tables for different files, for example:

 filename | tablename
 ---------+----------
 file1    | table1
 file2    | table2

I need select from tablename, but not hardcoded. The file name comes from the Internet, and I can fist get the name of the tab, for example

select tablename 
from filetables 
where filename = "file1"

and use it to view the file table:

select * 
from (table1)

Is there any way to do this in SQL? Sort of

Select * 
from 
    (select tablename 
     from filetables 
     where filename = "file1")
+4
source share
2 answers

You cannot choose from a table that can only be determined at runtime and / or depending on some parameter. The only option is to use Dynamic SQL in this case, but do not expose yourself to SQL-Injection attacks.

, SQL.

+3
   DECLARE @v_sql        NVARCHAR(MAX),
           @v_table_name NVARCHAR(MAX),
           @v_file_name  NVARCHAR(MAX)

    SELECT @v_file_name  = 'file1' -- Populated from web proc

    SELECT @v_table_name = tablename
      FROM filetables
     WHERE filename = REPLACE(@v_file_name, '''', '') 

    SELECT @v_sql =

   'SELECT *
      FROM ' + @v_table_name + '
     WHERE filename = ''' + @v_file_name + ''''

    SELECT @v_sql -- Debug code to show you the statement prior to running

    EXEC sp_executesql @v_sql

SQL, , . , .

-1

Source: https://habr.com/ru/post/1685114/


All Articles