1

I have an issue where I am trying to add a leading 0 to run an output.

SELECT 
    CASE 
        WHEN LEN(t.trans_time) = 5 
            THEN CONCAT(0, [trans_time])
            ELSE T.[trans_time] 
     END AS [TransactionTime]

     ,RIGHT(CONCAT(0,trans_time),6) AS trans_time

    ,LEN(T.trans_Time)

    ,t.trans_time

enter image description here

Why does the case statement not return the leading 0 whereas using:

,RIGHT(CONCAT(0,trans_time),6) AS trans_time

Works no problem.

Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
  • 2
    Format output in the code which run sql query. Programming languages are much better tool for this then SQL. Sql wasn't designed for pretty output. – Fabio Oct 05 '18 at 09:14
  • 1
    The case can only return one datatype, so make sure that all cases return varchar. Just convert the ELSE to varchar and it should work – GuidoG Oct 05 '18 at 09:32
  • Maybe this can help you also https://stackoverflow.com/questions/5540064/padleft-function-in-t-sql – GuidoG Oct 05 '18 at 09:34

2 Answers2

4

Case expression return only one type, whereas concat() would return different type & i am assuming trans_time has INT type.

So, you would need to do type conversations :

SELECT (CASE WHEN LEN(t.trans_time) = 5 
             THEN CONCAT(0, [trans_time])
             ELSE CAST(T.[trans_time]  AS VARCHAR(255))
         END) AS [TransactionTime],
. . .
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
3

Another way to do this is to use the format function, wich is available from sql server 2012.
It not only makes the code more readable but will also perform better.

declare @t table (id int)
insert into @t values (90113), (90204), (90207), (90235), (90302), (90318), (90324)

select format(id, '000000') as TransactionTime from @t

this will return

TransactionTime 
---------------
090113  
090204  
090207  
090235  
090302  
090318  
090324  
GuidoG
  • 11,359
  • 6
  • 44
  • 79