Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

formatting

Status
Not open for further replies.

csupriest

Programmer
Jan 25, 2006
5
0
0
US
I want to format results in my query.
I want the length to be 6.
If its 5 in length I want to add a zero at the end
If the value is 4 in length I want to add a leading zero and a zero at the end.

Does some have an example of this.
Thanks

Select number from table

results "number":
2534
2521
15556
25111

I want the result to be:
025340
025210
155560
251110

 
Isn't it a job for your front end?
Code:
DECLARE @test TABLE (results int)
INSERT INTO @Test VALUES (2534)
INSERT INTO @Test VALUES (2521)
INSERT INTO @Test VALUES (15556)
INSERT INTO @Test VALUES (25111)

SELECT RIGHT('000000'+LEFT(CAST(Results*10000 as varchar(10)),5),6) FROM @Test
But this code is valid if you don't have 6 or more digits value.

Borislav Borissov
VFP9 SP2, SQL Server
 
This is for a backend process. This seems to work but not for values that are 5 in length

example 25111

need it to be: 251110
 
How about?

Code:
;WITH t AS (
SELECT Number, CAST(Number AS VARCHAR) String
  FROM (VALUES (2534), (2521), (15556), (25111), (123456)) v(Number)
)

SELECT *,
       CASE LEN(String)
	  WHEN 4 THEN '0' + String + '0'
	  WHEN 5 THEN String + '0'
	  ELSE String
       END FormattedString
  FROM t
 
>This is for a backend process
Where does this end in? In a report? In generated data?
A report IS a frontend thing, even when reporting services are used. Output formatting is a feature there, which doesn't need the crappy string functionalities T-SQL only offers.
And if this data ends in more generated data in a backend, the need to format it that way would just delay to anywhere it will be shown or printed.

Besides left AND right padding is very unusual.

Bye, Olaf.



 
Numbers, in relational databases, do not have leading zeros. When you add leading zeros, you are creating a string or character or varchar variable. what's wrong with DaveInIowa's solution? Seems straightforward and accurate.

==================================
advanced cognitive capabilities and other marketing buzzwords explained with sarcastic simplicity


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top