1

I am performing stored procedures the input option is as follows:

 Declare @table varchar (20)
 Set @query = 'Select * from' + @table + 'Where id = 1'
 Exec sp_executesql @query

The question is can it be done in some other way without the SQL being handled as varchar?

I was thinking along the lines of something similar to the following:

Declare @varchar varchar(20)
Set @tabla = 'MyTabla'
SELECT * FROM @table
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Caleb
  • 11
  • 3
  • No, you cannot refer to a table dynamically without using... dynamic SQL. Also, please be much safer than that ... see [this](https://www.mssqltips.com/sqlservertip/3637/protecting-yourself-from-sql-injection-in-sql-server-part-1/) and [this](https://www.mssqltips.com/sqlservertip/3638/protecting-yourself-from-sql-injection-in-sql-server-part-2/). – Aaron Bertrand Aug 27 '21 at 21:54
  • Ok, thanks. Only I just wanted to know if there is another way to do it – Caleb Aug 27 '21 at 23:05
  • 1
    This is sort of a weird thing to do anyway. The tables in your database probably have different schemas (different columns), so a `select * from Table1` would return a different set of columns than a `select * from Table2`. So, when your client code runs, you probably need to handle those results differently (unless you're just loading into a dynamic datagridview, or generating an HTML table based on the output schema, or some other "direct from DB to dynamic GUI" sort of thing). – allmhuran Aug 28 '21 at 16:16
  • 1
    Side notes: you should store object names in `sysname` variables (synonym for `nvarchar(128)` and you should escape them correctly with the `quotename` function – Charlieface Aug 29 '21 at 00:31

0 Answers0