简体   繁体   English

如何在 SQLite 中模拟 REPEAT()

[英]How to emulate REPEAT() in SQLite

Most relational databases have some sort of REPEAT() string function, for instance:大多数关系数据库都有某种REPEAT()字符串函数,例如:

SELECT REPEAT('abc', 3)

Would yield会产生

abcabcabc

SQLite on the other hand has a very limited feature set.另一方面,SQLite 的功能集非常有限。 The functions supported by SQLite are listed here: SQLite 支持的函数在这里列出:

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

Can REPEAT() be emulated with the functions available in SQLite?可以用 SQLite 中可用的函数模拟REPEAT()吗?

A solution was inspired by this answer to a related question, here:一个解决方案的灵感来自这个对相关问题的回答,这里:

How to emulate LPAD/RPAD with SQLite如何使用 SQLite 模拟 LPAD/RPAD

I wanted to share this on Stack Overflow, as this may be useful to other SQLite users.我想在 Stack Overflow 上分享这个,因为这可能对其他 SQLite 用户有用。 The solution goes like this:解决方案是这样的:

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

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

If its a single character you want to repeat, you can use printf function.如果要重复单个字符,可以使用printf函数。

Bellow is an example where x is repeated 10 times. Bellow 是x重复10次的示例。 The key is the * in the format string which specifies that the width of the field will be passed as a parameter:关键是格式字符串中的* ,它指定字段的宽度将作为参数传递:

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

To repeat multiple characters you can then replace() each x by the longer string, much as in Lukas's answer above.要重复多个字符,您可以将每个x replace()为较长的字符串,就像上面 Lukas 的回答一样。

A simplified version of @Lukas Eder's solution using hex() instead of quote: @Lukas Eder 使用 hex() 而不是引号的解决方案的简化版本:

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

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

My answer combines Shiplu Mokaddim's "printf character substitution repetition" with the "replace" of Steve Broberg and Lukas Eder :我的回答结合了Shiplu Mokaddim 的“printf 字符替换重复”Steve BrobergLukas Eder的“替换”:

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

It's also easy to derive the number of repetitions from table data.从表数据中推导出重复次数也很容易。 Here's an example using a common table expression:下面是一个使用公用表表达式的示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM