如何在SQLite中模拟REPEAT()

时间:2012-07-19 20:09:37

标签: sql sqlite function simulation

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

SELECT REPEAT('abc', 3)

会产生

abcabcabc

另一方面,SQLite的功能集非常有限。这里列出了SQLite支持的功能:

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

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

4 个答案:

答案 0 :(得分:6)

解决方案的灵感来自对相关问题的答案,其中:

How to simulate LPAD/RPAD with SQLite

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

-- X = string
-- Y = number of repetitions

replace(substr(quote(zeroblob((Y + 1) / 2)), 3, Y), '0', X)

答案 1 :(得分:2)

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

-- X = string
-- Y = number of repetitions

replace(hex(zeroblob(Y)), '00', X) 

答案 2 :(得分:2)

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

下面是一个例子,其中*被重复10次。

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

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

答案 3 :(得分:2)

我的答案将Shiplu Mokaddim's "printf character substitution repetition"Steve BrobergLukas Eder的“替换”组合在一起:

200
200
200
404
200

从表数据中得出重复次数也很容易。这是使用公用表表达式的示例:

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