简体   繁体   English

是否可以在SQL中对运算符进行参数化?

[英]Is it possible to parametrize an operator in SQL?

Is it possible, in any SQL dialect, to parametrize an operator? 在任何SQL方言中,是否有可能对运算符进行参数化?

I want to be able to do the following: 我希望能够做到以下几点:

if(x == y)
{
     operator = '<=';
}
else
{
     operator = '=';
}

And then use that in a prepared statement: 然后在准备好的声明中使用它:

SELECT a FROM b WHERE number :operator 10

I can't get this done in MySQL (what I'm using), but I'm wondering whether this is possible in any dialect. 我无法在MySQL(我正在使用的)中完成这项工作,但我想知道这是否可以在任何方言中使用。

No, you can't make an operator a parameter directly, and the other examples show you ways around it, by passing in a string that represents your choice of a code branch. 不,您不能直接将运算符作为参数,其他示例通过传入表示您选择的代码分支的字符串来向您展示它的方法。

The important thing to remember about SQL statement preparation is that nothing that is executable may be parametrized. 关于SQL语句准备要记住的重要一点是,可执行的任何内容都不能参数化。 The only thing that can have placeholders is an actual value. 唯一可以拥有占位符的是实际值。 Anything that would affect how the statement would be compiled cannot be a parameter. 任何会影响语句编译方式的内容都不能成为参数。

(at least : SQL server) You can do it as a string and then (至少:SQL服务器)您可以将其作为字符串然后执行

  • Use a "select case" in your command 在命令中使用“选择案例”

    CASE input_expression WHEN when_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END Searched CASE expression: CASE WHEN Boolean_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END CASE input_expression WHEN when_expression THEN result_expression [... n] [ELSE else_result_expression] END搜索CASE表达式:CASE WHEN Boolean_expression THEN result_expression [... n] [ELSE else_result_expression] END

    WHERE CASE WHEN @operator='<=' THEN number<=10 ELSE number=10 END 如果@operator ='<='那么情况那么数<= 10 ELSE数= 10结束

  • Building Dynamic SQL 构建动态SQL

You can make the parameter mean the inclusion of the range below the number: 您可以使参数表示包含数字下方的范围:

if(x == y) {
  less = 1
} else {
  less = 0;
}

Use the parameter in an expression: 在表达式中使用参数:

SELECT a FROM b WHERE (number < 10 and :less = 1) or (number = 10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM