参数作为where子句中的列名

时间:2013-09-26 13:18:30

标签: sql sql-server-2008

是否可以通过将参数保存在where子句中来获取值,如下所示:

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'

非常感谢您的知识和帮助。

1 个答案:

答案 0 :(得分:3)

您可以使用动态SQL:

Declare @SQL VARCHAR(4000)
SET @SQL = 'SELECT * FROM BORVALIDATION WHERE ' + @COLUMNNAME + '= ''BBNAME''';
EXEC(@SQL);