【问题标题】:How to use select with a parameter in SQL如何在 SQL 中使用带参数的 select
【发布时间】:2021-03-17 03:51:12
【问题描述】:

我正在尝试选择@max_disease_name 参数(我从过程中返回)作为列名:

select  
    Customer_id, Age 
from 
    [INPUT_DATA ] 
where 
    Gender ='Female' and @max_disease_name = 'Yes' 
order by 
    age asc

但是,SQL 似乎找不到匹配的列,就好像列名甚至不存在一样。

但是,当我像这样硬编码列的名称时,它确实有效:“HighBlood”:

select  
    Customer_id, Age 
from 
    [INPUT_DATA ]  
where 
    Gender ='Female' and
    HighBlood = 'yes'
order by 
    age asc

关于如何在不硬编码“HighBlood”的情况下使其工作的任何建议?

【问题讨论】:

标签: sql database select parameters procedure


【解决方案1】:

简单的答案是参数可以替换查询中的常量。它不能替代以下任何一项:

  • 列名。
  • 一个表名。
  • 列或表别名。
  • 一个函数名。
  • 操作员。
  • 一个 SQL 关键字。

要做你想做的事,你需要使用动态 SQL。即,将 SQL 构造为字符串,然后执行 SQL。这可以用 Python 或 R 等应用程序语言来处理,也可以经常用数据库的脚本语言来处理。

确切的语法因数据库而异。作为伪代码,它看起来像:

set @sql = '
select  Customer_id, Age 
from [INPUT_DATA ] 
where  Gender ='Female' and @max_disease_name = 'Yes' 
orderby  age asc';

set @sql = replace(@sql, '@max_disease_name', @max_disease_name);

execute @sql;

两个重要说明:

  • 语法因数据库而异。
  • 代码会受到 SQL 注入攻击,因此在使用动态 SQL 来修改查询字符串时需要非常小心。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    相关资源
    最近更新 更多