【问题标题】:Use When Case in SQL server to Ruby On Rails在 SQL Server 中使用 When Case 到 Ruby On Rails
【发布时间】:2011-11-29 19:06:08
【问题描述】:

我在 SQL 中有这个查询

select @cd_x=
Case 
    when tp_x2='ZZZ' then  tp_x3
    when tp_x2='XXX' then  tp_x3
    else
    tp_x2
end 
from table
where id=@id

如何在 Ruby on Rails 中将此查询翻译成句子?

【问题讨论】:

  • 我假设您使用的是带有 Rails 的 ActiveRecord,而不是其他 ORM,例如 Sequel
  • 是的,我正在使用 activeRecord 我试图在语句中设置条件,但它不起作用
  • “到一个句子”是什么意思?
  • 对不起...我想在我之前创建的模型中进行查询.. Model.query (:conditions...)

标签: sql ruby-on-rails sql-server ruby activerecord


【解决方案1】:

我想你会看到类似的东西:

@cd_x = table.select("CASE WHEN tp_x2='ZZZ' THEN tp_x3 WHEN tp_x2='XXX' then tp_x3 ELSE tp_x2 END").where(:id => id)

尽管他们用它而不是一行创建了一个完整的模块,但我将其用作模型:Case Statement in ActiveRecord

【讨论】:

  • 非常感谢我会尝试这种方法
【解决方案2】:

我有一个类似的问题。我想用一个查询更新更多记录。基本上是订单排序更新,使用 CASE sql。

#List of product ids in sorted order. Get from jqueryui sortable plugin.
#product_ids = [3,1,2,4,7,6,5]

#product_ids.each_with_index do |id, index|
#  Product.where(id: id).update_all(sort_order: index+1)
#end

##CASE syntax example:
##Product.where(id: product_ids).update_all("sort_order = CASE id WHEN 539 THEN 1 WHEN 540 THEN 2 WHEN 542 THEN 3 END")

case_string = "sort_order = CASE id "      

product_ids.each_with_index do |id, index|
  case_string += "WHEN #{id} THEN #{index+1} "
end

case_string += "END"

Product.where(id: product_ids).update_all(case_string)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    相关资源
    最近更新 更多