Post has been published on Varinder Sandhu 's Blog
Post has been published on http://www.varindersandhu.in/2012/12/04/sql-server-how-to-add-column-dynamically-in-where-clause/
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
add column dynamically in where clause
Basically we want to execute following script (i.e. Script: 1) but column name (i.e. FIRST_NAME) added dynamically in where clause.
<!-- google_ad_client = "pub-2404605494811633"; google_alternate_color = "FFFFFF"; google_ad_width = 468; google_ad_height = 60; google_ad_format = "468x60_as"; google_ad_type = "text_image"; google_ad_channel =""; google_color_border = "FFFFFF"; google_color_link = "0000FF"; google_color_bg = "FFFFFF"; google_color_text = "000000"; google_color_url = "008000"; google_ui_features = "rc:6"; //-->
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
add column dynamically in where clause
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.












