Teradata sql 中的零填充
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23644046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
zero padding in teradata sql
提问by user3634687
Table A
Id varchar(30)
表 A
Id varchar(30)
I'm trying to re-create a logic where I have to use 9 digit Ids irrespective of the actual length of the Value of the Id field.
So for instance, if the Id is of length 6, I'll need to left pad with 3 leading zeros. The actual length can be anything ranging from 1 to 9.
我正在尝试重新创建一个逻辑,无论 Id 字段的值的实际长度如何,我都必须使用 9 位 Id。
因此,例如,如果 Id 的长度为 6,我将需要在左侧填充 3 个前导零。实际长度可以是 1 到 9 之间的任何值。
Any ideas how to implement this in Teradata SQL?
任何想法如何在 Teradata SQL 中实现它?
回答by dnoeth
If the actual length is 1 to 9 characters why is the column defined as VarCar(30)?
如果实际长度为 1 到 9 个字符,为什么将列定义为 VarCar(30)?
If it was a numeric column it would be easy:
如果它是一个数字列,那就很容易了:
CAST(CAST(numeric_col AS FORMAT '9(9)') AS CHAR(9))
For strings there's no FORMAT like that, but depending on your release you might have an LPAD function:
对于字符串,没有类似的 FORMAT,但根据您的版本,您可能有一个 LPAD 函数:
LPAD(string_col, 9, '0')
Otherwise it's:
否则就是:
SUBSTRING('000000000' FROM CHAR_LENGTH(string_col)+1) || string_col,
If there are more than nine characters all previous calculations will return them.
如果超过九个字符,所有先前的计算都会返回它们。
If you want to truncate (or a CHAR instead of a VARCHAR result) you have to add a final CAST AS CHAR(9)
如果要截断(或 CHAR 而不是 VARCHAR 结果),则必须添加最终 CAST AS CHAR(9)
And finally, if there are leading or trailing blanks you might want to use TRIM(string_col)
最后,如果您可能想要使用前导或尾随空格TRIM(string_col)