Rails中与数据库无关的SQL字符串串联 [英] Database-independent SQL String Concatenation in Rails

查看:58
本文介绍了Rails中与数据库无关的SQL字符串串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Rails查询中进行数据库端字符串连接,并以与数据库无关的方式进行。

I want to do a database-side string concatenation in a Rails query, and do it in database-independent way.

SQL-92指定双引号( || )作为串联运算符。不幸的是,MS SQL Server似乎不支持它。它使用 + 代替。

SQL-92 specifies double-bar (||) as the concatenation operator. Unfortunately it looks like MS SQL Server doesn't support it; it uses + instead.

我猜测Rails的SQL语法抽象解决了特定于db的运算符问题了。如果确实存在,我该如何使用它?

I'm guessing that Rails' SQL grammar abstraction has solved the db-specific operator problem already. If it does exist, how do I use it?

推荐答案

我遇到了同样的问题,但从未提出过任何建议。进入Rails。所以我写了这个小方法。

I had the same problem and never came up with anything that was built into Rails. So I wrote this little method.

# Symbols should be used for field names, everything else will be quoted as a string
def db_concat(*args)

  adapter = configurations[RAILS_ENV]['adapter'].to_sym
  args.map!{ |arg| arg.class==Symbol ? arg.to_s : "'#{arg}'" }

  case adapter
    when :mysql
      "CONCAT(#{args.join(',')})"
    when :sqlserver
      args.join('+')
    else
      args.join('||')
  end

end

我认为有人应该真正编写某种可以自动格式化简单SQL的SQL Helper插件使用当前适配器的正确函数或运算符的表达式。也许我会自己写一个。

I'm thinking somebody should really write some sort of SQL helper plugin that could automatically format simple SQL expressions based using the correct functions or operators for the current adapter. Maybe I'll write one myself.

这篇关于Rails中与数据库无关的SQL字符串串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆