0

Is it possible to get values by keeping parameter in where clause like below :

DECLARE  @COLUMNNAME VARCHAR(50)
-- setting required column name 
SET @COLUMNNAME = (select name from sys.columns where OBJECT_ID = 
    (SELECT OBJECT_ID FROM SYS.objects WHERE name = 'BORVALIDATION') AND column_id = 2) 
--PRINT @COLUMNNAME (we do get the column name)
SELECT * FROM BORVALIDATION WHERE @COLUMNNAME = 'BBNAME'

Your knowledge and help is highly appreciated.

Kermit
  • 33,827
  • 13
  • 85
  • 121
HMcompfreak
  • 161
  • 2
  • 3
  • 20
  • 1
    Like using dynamic SQL? – Kermit Sep 26 '13 at 13:20
  • 1
    It's not very clear what exactly you are asking here. Can you restate the question? – EkoostikMartin Sep 26 '13 at 13:22
  • the code is taking column name of table in parameter(@columnname), e.g. column name is Column2 im trying to write SELECT * FROM BORVALIDATION WHERE @COLUMNNAME (i.e. Column2) = 'BBNAME' – HMcompfreak Sep 26 '13 at 13:56
  • Possible duplicate of [Can I pass column name as input parameter in SQL stored Procedure](https://stackoverflow.com/questions/10092869/can-i-pass-column-name-as-input-parameter-in-sql-stored-procedure) – Tab Alleman Sep 05 '18 at 14:40

1 Answers1

3

You can use dynamic SQL:

Declare @SQL VARCHAR(4000)
SET @SQL = 'SELECT * FROM BORVALIDATION WHERE ' + @COLUMNNAME + '= ''BBNAME''';
EXEC(@SQL);
rs.
  • 26,707
  • 12
  • 68
  • 90