首页 > 解决方案 > where 子句中的 SQL 参数

问题描述

如果这是一个简单的问题,我深表歉意,但我觉得有些基本的东西我不理解。

我有以下脚本:

select @sql = 
    'select
     fld1
    ,' + @param1 +'
    ,fld2
from
    table
where
    column = ''y'''
exec (@sql)

它完全返回了我期望的结果,但是当我将 where 子句中的列更改为如下参数时:

select @sql = 
    'select
     fld1
    ,' + @param1 +'
    ,fld2
from
    table
where
    @param2 = ''y'''
exec (@sql)

根本不返回任何结果。我不能像这样在 where 子句中使用参数是否有根本原因?

谢谢

标签: sqlsql-server

解决方案


学习使用sp_executesql并将参数传递到查询执行中。

这看起来像:

select @sql = '
select fld1, @param1, fld2
from table
where @param2 = ''y''
';

exec sp_executesql @sql, N'@param1 ?, @param2 varchar(255)', @param1=@param1, @param2=@param2;

?类型@param1


推荐阅读