SQL null value padding method

A small problem was encountered when making SSRS. The user requested to select the data of the report 24 hours a day. Take 0 ~ 23 from master..spt_values, but 0 ~ 9 is not a normal time point of the system, and needs to be changed after 00 ~ 09, there are several ways to achieve the following.

method one:

 select right (cast('0'+cast( number as nvarchar(2)) as nvarchar(3)),2)
from master..spt_values
where type='p' and number between 1 and 24


方法二:
 select  case when number <10
           then  '0'+ cast(number as varchar(50) )
            else
            cast(number as varchar(20))
             end 
            from master..spt_values
 where type='P'
 and number<24

方法三:
select replicate('0',2-len(number))+convert(varchar(10),number)from master..spt_values where type='P'

replicate: repeat the character expression the specified number of times

After the parameters are defined in this way, you can press 00 ~ 23 to select and view 24 or 24 times a day.

 

 

Published 22 original articles · praised 7 · 100,000+ views

Guess you like

Origin blog.csdn.net/qyx0714/article/details/66972020