代码之家  ›  专栏  ›  技术社区  ›  Geoff Lanotte

将ORDER BY语句拆分为数组

  •  1
  • Geoff Lanotte  · 技术社区  · 15 年前

    我试图将SQL查询的ORDER BY语句拆分为一个数组。第一种倾向是:

    order_by.split(',')
    

    但这不适用于以下order by语句:

    SUBSTRING('test',1,3) ASC, SUBSTRING('test2', 2,2 ) DESC
    

    上述语句的预期输出为:

    ["SUBSTRING('test',1,3) ASC", "SUBSTRING('test2', 2,2 ) DESC"]
    

    3 回复  |  直到 15 年前
        1
  •  0
  •   Jamie Wong    15 年前

    其他逗号分开。

    编辑

    def in_brackets(str,pos)
      cnt = 0
      str[pos,str.length].each_char do |c|
        if c == '('
          cnt += 1
        elsif c == ')'
          cnt -= 1
        end
      end
    
      return cnt != 0
    end
    
    def split_on_some_commas(str) 
      offset = -1
      split_pts = []
    
      while (offset = str.index(",",offset+1))
        if !in_brackets(str,offset)
          split_pts << offset
        end
      end
    
      split_pts << str.length
    
      pos = 0
    
      ret = []
      split_pts.each do |pt|
        ret << str[pos..(pt-1)].strip
        pos = pt+1
      end
    
      return ret
    end
    
    puts split_on_some_commas("SUBSTRING('test',1,3) ASC, SUBSTRING('test2', 2,2 ) DESC, SUBSTRING('test2', 2,2 ) DESC").inspect
    
        2
  •  1
  •   Aaron Butacov    15 年前

    最简单的方法是执行preg\u replace\u回调,用占位符替换圆括号,然后分解数据,然后循环并将圆括号放回。

        3
  •  0
  •   Bill Karwin    15 年前

    一般来说,不能使用正则表达式来解析非正则语言。

    Rockit 为您需要的SQL子集创建一个真正的语法和解析器。