[英]SQL with parameters: … where column_name IS NULL || where column_name = value
I have a method in Ruby on Rails (or any other programming language), where I'm calling quit a complex SQL statement (Common Table Expressions (STE) SQL statement).我在 Rails(或任何其他编程语言)上的 Ruby 中有一个方法,我正在调用退出复杂的 SQL 语句(公用表表达式(STE)Z9778840A0100CB30C9822876741B0B5A 语句)。 To make the statement a bit more generic, I've wrapped the SQL statement in a rails method, where I can pass in a parameter.为了使语句更通用,我将 SQL 语句包装在 rails 方法中,我可以在其中传入参数。 For simplicity reason, I have simplified the SQL statement to isolate my question.为简单起见,我简化了 SQL 语句以隔离我的问题。
def sql_statement(id = 'null')
tree_sql = <<-SQL
SELECT * FROM sample_table WHERE foreign_id = #{id}
SQL
find_by_sql(tree_sql)
end
So if I call the method WITHOUT a parameter, I want it to execute所以如果我调用没有参数的方法,我希望它执行
SELECT * FROM sample_table WHERE foreign_id IS NULL
and if I pass a parameter (like the value 5), it executes the following:如果我传递一个参数(如值 5),它会执行以下操作:
SELECT * FROM sample_table WHERE foreign_id = 5
How do I have to change the SQL statement to make this work?我如何更改 SQL 语句才能使其正常工作?
Try尝试
SELECT *
FROM sample_table
WHERE (foreign_id = #{id} and #{id} is not null)
OR (foreign_id is null and #{id} is null)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.