I'm trying to do a SQL query on a priority matrix. So I want to pass the column name dynamically and then also filter based on a where clause that also has a dynamic value.
I've found some answers on Stackoverflow that have been useful but they've only got me so far, and now I'm a bit stuck. Can anyone see where I'm going wrong?
Query I have the issue with:
DECLARE @var1 VARCHAR(50)
DECLARE @var2 VARCHAR(50)
DECLARE @sql VARCHAR(255)
SET @var1 = 'partial impact'
SET @var2 = 'single user'
SET @sql = 'select [' + @var1 + '] from [priority matrix] where impact is ['+ @var2 + ']'
EXECUTE(@sql);
Query that isn't dynamic and works fine:
SELECT [partial impact]
FROM priorityMatrix
WHERE impact = 'single user';
Error I'm seeing when I run it:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'single user'.
Stackoverflow queries that have helped so far:
SQL Server + Dynamic Query 'Invalid Column Name' How to set variable from a SQL query?