I'm trying to pass user-inputted data to a SQL 'sp_executesql' (Dynamic SQL) statement in order to build a string for the 'SELECT','FROM', and 'WHERE' statements.
I know that SQL Server won't accept a table name or a column name as a parameter. However I was wondering if it was possible to take user-inputted values, store them in a locaL-SQL variable and then use the local variable in the 'FROM' clause?
I know this code would work:
set @tableName = 'SalesData'
set @monthNo = 2
set @sql = N'
select SalesPerson
from ' + @tableName + '
where mon = @monthNo'
exec sp_executesql @sql, N'@monthNo int', @monthNo
But, would this code run?
set @tableName = @ValueTypedByUser
set @monthNo = 2
set @sql = N'
select SalesPerson
from ' + @tableName + '
where mon = @monthNo'
exec sp_executesql @sql, N'@monthNo int', @monthNo