SQL Server – How to add column dynamically in where clause
In this post, we will learn with example how to add the column dynamically in where clause.
Example:
For demo we have table as shown in the snapshot
Basically we want to execute following script (i.e. Script: 1) but column name (i.e. FIRST_NAME) added dynamically in where clause.
Script: 1
SELECT * FROM EMPLOYEE WHERE FIRST_NAME = 'VARINDER'
Created a table and insert the column name value (i.e. FIRST_NAME) as shown in the snapshot
Now we will execute the Script: 1 in which we add the column dynamically in where clause
DECLARE @COL VARCHAR(15) DECLARE @SQL VARCHAR(1000) SELECT @COL = column1 from TEMP_Table SET @SQL = ' SELECT * from EMPLOYEE WHERE ' + @Col + ' = ' + '''VARINDER''' EXEC(@SQL)
If you have any suggestion/comment please share.