简体   繁体   中英

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). 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. For simplicity reason, I have simplified the SQL statement to isolate my question.

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:

SELECT * FROM sample_table WHERE foreign_id = 5

How do I have to change the SQL statement to make this work?

Try

SELECT * 
FROM sample_table 
WHERE (foreign_id = #{id} and #{id} is not null)
   OR (foreign_id is null and #{id} is null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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