This question already has answers here:
Can I pass column name as input parameter in SQL stored Procedure

(9个答案)


2年前关闭。




我的 SQL 逻辑需要一些帮助,我已经工作(和研究)了 2 天,但成功率为零。

我的目标是尝试将变量从 ASP 页传递到存储过程,该过程将该变量用作 where 子句中列名的条件。

例如(我的查询的简化版本):
@strDept nvarchar(10), @strUser nvarchar(30)
-- The asp page will pass f18 to @strDept & Ted Lee to strUser
-- f18 is the column name in my database that I need in the where.

select x, y, z from table1 where @strDept in (@strUser)
-- and this is the select statement, notice the where clause.

存储过程确实执行,但它不返回任何值,我知道它将 @strDept 视为文字 nvarchar 而不是列名。

所以我想我的问题是,如何让 SQL Server 2005 将我的 @sqlDept 变量视为列名?

最佳答案

如果这是一个公司内部的应用程序,为什么每个人都在反复迭代并把 SQL 注入(inject)打败…… 使用动态 SQL 非常简单。
如果您对这些只是内部用户感到满意,那么它非常简单。这是概念。您本质上是编写一个 SQL 语句,该语句写入一个真正是 SQL 语句的字符串,然后执行它。

CREATE Procedure myDynamicProcedure
@strDept nvarchar(10),
@strUser nvarchar(30)

as

BEGIN

1. 声明一个变量来存储 SQL 语句。
 DECLARE @SQL varchar(max)

2.将您的@SQL变量设置为SELECT语句。基本上,您正在构建它,以便它返回您想要编写的内容。像这样:
   SET @SQL = 'select x, y, z from table1 where' + @strDept +
 ' in ' + @strUser

3. 执行@SQL 语句,它将与您运行的完全一样:
SELECT x,y,z from table1 where f18 = 'Ted Lee'
EXEC (@SQL)
END

10-07 19:11
查看更多