How to convert a date to char(8) in sql server

tv6aics1  于 2023-06-28  发布在  SQL Server
关注(0)|答案(3)|浏览(110)

I have a date value like:

declare @d date = getDate();

Its result is '2023/11/05'

I want to convert it to '20231105' and save it into column of datatype char(8)

dhxwm5r4

dhxwm5r41#

Don't use FORMAT it's slow, and should only be used if you have no choice.

Just use CONVERT with style 112 .

select convert(char(8), @d, 112);

db<>fiddle

Having said that, I'd advise you not to save that into a column. Dates should be kept in date formats, not varchar , until you actually need to query it.

At the most, you could use a computed column

ALTER TABLE YourTable
  ADD FormattedDate AS ( CONVERT(char(8), YourDateColumn, 112) )
7uzetpgm

7uzetpgm2#

You can use the format, but my recommend is to use the DimDate(Table Date) and where clause with date and use dateint in select

Select format(cast(GETDATE() as date),'yyyyMMdd') --20230626

Select format(cast('2023/11/05' as date),'yyyyMMdd') --20231105
a9wyjsp7

a9wyjsp73#

I used this code:

select    FORMAT( getdate()  ,'yyyyMMdd')

相关问题