Luk*_*der 12 sql sqlite emulation padding
我很好奇如何以最一般的方式正式模拟SQLite的RPAD和LPAD函数.目标是能够做到
LPAD(column, character, repeat)
RPAD(column, character, repeat)
Run Code Online (Sandbox Code Playgroud)
对于非固定表列column
,character
,repeat
.如果character
并且repeat
是已知的常数,那么这将是一个好的,可行的解决方案:
但是如果上面的内容应该像这样执行呢:
SELECT LPAD(t.column, t.character, t.repeat) FROM t
SELECT LPAD(t.column, some_function(), some_other_function()) FROM t
SELECT LPAD(t.column, :some_bind_variable, :some_other_bind_variable) FROM t
Run Code Online (Sandbox Code Playgroud)
如何LPAD
通常模拟此功能?我迷失了各种可能性:
一个相关的问题:
Son*_*oor 20
复制自http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/
-- the statement below is almost the same as
-- select lpad(mycolumn,'0',10) from mytable
select substr('0000000000' || mycolumn, -10, 10) from mytable
-- the statement below is almost the same as
-- select rpad(mycolumn,'0',10) from mytable
select substr(mycolumn || '0000000000', 1, 10) from mytable
Run Code Online (Sandbox Code Playgroud)
小智 8
你也可以打印。
sqlite> SELECT PRINTF('%02d',5);
05
sqlite> SELECT PRINTF('%04d%02d',25,5);
002505
sqlite>
Run Code Online (Sandbox Code Playgroud)
@user610650 解决方案的更简单版本,使用 hex() 而不是 quote(),除了字符填充之外还使用字符串填充:
X = padToLength
Y = padString
Z = expression
select
Z ||
substr(
replace(
hex(zeroblob(X)),
'00',
Y
),
1,
X - length(Z)
);
Run Code Online (Sandbox Code Playgroud)