我在 SQL 2008R2 中编写了一个函数,我可以给它一些参数,比如值 varchar、模式 varchar、分隔符和填充符。然后我想用模式'000.000.000.000',分隔符'.'给出值'22687' 并且填充符将为“0”,那么我希望该函数将返回“000.000.022.687”,是否有人已经完成了可以执行此操作的函数?
像这样的东西:
DECLARE @valor VARCHAR(30)
DECLARE @formato VARCHAR(30)
DECLARE @separador CHAR(1)
DECLARE @rellenarcon CHAR(1)
SELECT @valor = '22959'
SELECT @formato = '000.000.000.000'
SELECT @separador = '.'
SELECT @rellenarcon = '0'
DECLARE @n INTEGER
DECLARE @m INTEGER
DECLARE @i INTEGER
DECLARE @j INTEGER
SELECT @n = LEN(@formato)
SELECT @m = LEN(@valor)
SELECT @i = 1
SELECT @j = 1
DECLARE @res2 varchar(30)
SELECT @res2 = ''
SELECT @valor = REVERSE(@valor)
WHILE @i<=@n
BEGIN
if SUBSTRING(@formato,@i,1) <> @separador
begin
IF @j<=@m
BEGIN
SELECT @res2 = @res2 + SUBSTRING(@valor,@j,1)
SELECT @i=@i+1
SELECT @j=@j+1
END
ELSE
BEGIN
SELECT @res2 = @res2 + @rellenarcon
SELECT @i=@i+1
END
end
else
BEGIN
SELECT @res2 = @res2 + @separador
SELECT @i=@i+1
END
END
print reverse(@res2)
是从java到tsql的交叉代码,java中的原代码是:
public static String formatear(String valor, String formato, char separator,
char fillWith, Map<Integer, String> params) {
int n = formato.length() - 1;
int m = valor.length() - 1;
int i = n;
int j = m;
StringBuilder res = new StringBuilder(formato);
for(; i >= 0; i--) {
if(res.charAt(i) != separator) {
if(j >= 0) {
res.deleteCharAt(i);
res.insert(i, valor.charAt(j--));
} else {
res.deleteCharAt(i);
res.insert(i, fillWith);
}
}
}
if(params != null) {
Set<Integer> keys = params.keySet();
for(Integer key : keys) {
i = key;
res.deleteCharAt(i);
res.insert(i, params.get(key));
}
}
return res.toString();
}