Variable name in select statement

I have several tables for storing various information about files, such as thumbs, images, data tables, ...

I am writing a stored procedure to get the file name of a specific identifier. sort of:

    CREATE PROCEDURE get_file_name(
    @id int,
    @table nvarchar(50)
    )as
    if @table='images'
        select [filename] from images
        where id = @id
    if @table='icons'
        select [filename] from icons
        where id = @id
....

How can I rewrite this procedure with a statement case whenor just use the table name as a variable?

+4
source share
3 answers

You cannot use the case .. when you need to switch between the table in the FROM clause (as you can in the conditionalORDER BY ). i.e. as follows:

select * from 
    case when 1=1
      then t1
      else t2
    end;

will not work.

, SQL. , , , @id :

-- Validate @table is E ['images', 'icons', ... other valid names here]
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'select [filename] from **TABLE** where id = @id';
SET @sql = REPLACE(@sql, '**TABLE**', @table);

sp_executesql @sql, N'@id INT', @id = @id;

Sql, , unparameterized, (, @table), Sql Injection. , , @table , , @table .

+5

SQL EXECUTE it

DECLARE @sql AS NCHAR(500)
SET @sql=
    'SELECT [filename] '+
    ' FROM '+@table+
    ' WHERE id = @id'
EXECUTE(@sql)
+3
CREATE PROCEDURE get_file_name(
    @id int,
    @table nvarchar(50)
    )as

DECLARE @SQL nvarchar(max);
SET @SQL = 'select [filename] from ' + @table + ' where id = ' + @id
EXECUTE (@SQL)
+1

All Articles