In SQL Server 2000 how do you add 0's to beginning of number to fill nchar(n)

怎甘沉沦 提交于 2020-01-23 17:11:06

问题


I'm trying to add 0's to the beginning of an nchar(n). Is their a format function in SQL Server 2000 to add 0's to an int so that it will always have n number of digits with leading 0's:

example

int         nchar(n)
1           0000..1
2           0000002
3           0000003
...
10          0000010
11          0000011
...
100         0000100
...
1000        0001000

回答1:


e.g. for n=12

DECLARE @foo bigint
DECLARE @bar bigint

SET @foo=12345678901
SET @bar=12

SELECT RIGHT('000000000000' + CAST(@foo AS VARCHAR(12)),12) 
SELECT RIGHT('000000000000' + CAST(@bar AS VARCHAR(12)),12) 

Beware! This won't work for numbers with more than n digits!




回答2:


Sorry for being slightly off-topic, but are you really sure that this is a problem that should be dealt with on a database level rather than in presentation level? I mean, database can and should store those numbers as-is, and only in presentation code do you add all the leading zeroes.



来源:https://stackoverflow.com/questions/5672951/in-sql-server-2000-how-do-you-add-0s-to-beginning-of-number-to-fill-ncharn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!