【问题标题】:How to emulate REPEAT() in SQLite如何在 SQLite 中模拟 REPEAT()
【发布时间】:2012-07-19 02:08:57
【问题描述】:

大多数关系数据库都有某种REPEAT() 字符串函数,例如:

SELECT REPEAT('abc', 3)

会成功

abcabcabc

另一方面,SQLite 的功能集非常有限。 SQLite 支持的函数列表如下:

http://www.sqlite.org/lang_corefunc.html

REPEAT() 可以用 SQLite 中可用的函数来模拟吗?

【问题讨论】:

    标签: sql sqlite function simulation


    【解决方案1】:

    一个解决方案的灵感来自一个相关问题的答案,在这里:

    How to emulate LPAD/RPAD with SQLite

    我想在 Stack Overflow 上分享这个,因为这可能对其他 SQLite 用户有用。解决办法是这样的:

    -- X = string
    -- Y = number of repetitions
    
    replace(substr(quote(zeroblob((Y + 1) / 2)), 3, Y), '0', X)
    

    【讨论】:

      【解决方案2】:

      如果要重复单个字符,可以使用printf函数。

      下面是* 重复10 次的示例。

      sqlite> select printf('%.' || 10 ||'c', '*');
      **********
      

      要重复多个字符,请参阅上面 Lukas 的回答。

      【讨论】:

        【解决方案3】:

        @Lukas Eder 使用 hex() 代替引号的解决方案的简化版本:

        -- X = string
        -- Y = number of repetitions
        
        replace(hex(zeroblob(Y)), '00', X) 
        

        【讨论】:

          【解决方案4】:

          我的回答结合了Shiplu Mokaddim's"printf character substitution repetition"Steve BrobergLukas Eder 的“替换”:

          sqlite> SELECT replace(printf('%.' || 5 || 'c', '/'),'/','My string ');
          My string My string My string My string My string      
          

          从表格数据中推导出重复次数也很容易。下面是一个使用公用表表达式的示例:

          sqlite> WITH cte(string, reps) AS
              ..>   (SELECT * FROM (values ('alpha ', 1),('bravo ', 5),('charlie ', 3) ) )
              ..> SELECT *, replace(printf('%.' || reps || 'c', '/'), '/', string) FROM cte;
          alpha       1           alpha
          bravo       5           bravo bravo bravo bravo bravo
          charlie     3           charlie charlie charlie
          

          【讨论】:

          猜你喜欢
          • 2011-09-28
          • 1970-01-01
          • 2016-03-02
          • 2013-10-31
          • 1970-01-01
          • 1970-01-01
          • 2010-10-24
          • 2011-09-14
          • 2021-01-20
          相关资源
          最近更新 更多