如何在 SQL Server 中将日期转换为 char(8)。

huangapple go评论56阅读模式
英文:

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

问题

declare @d date = getDate();

其结果是 '2023/11/05'

我想将其转换为 '20231105' 并保存到数据类型为 char(8) 的列中。

英文:

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)

答案1

得分: 2

不要使用 FORMAT,它很慢,只有在没有选择的情况下才应该使用。

只需使用带有 样式 112CONVERT

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

db<>fiddle

尽管如此,我建议您不要将日期保存到列中。日期应该保留在日期格式中,而不是 varchar,直到您实际需要查询它。

最多,您可以使用一个计算列

ALTER TABLE YourTable
  ADD FormattedDate AS ( CONVERT(char(8), YourDateColumn, 112) )
英文:

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) )

答案2

得分: 0

你可以使用这个格式,但我建议使用DimDate(日期表)和带有日期的where子句,并在选择中使用dateint

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

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

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),&#39;yyyyMMdd&#39;) --20230626

Select format(cast(&#39;2023/11/05&#39; as date),&#39;yyyyMMdd&#39;) --20231105

答案3

得分: -1

select FORMAT(getdate(), 'yyyyMMdd')

英文:

I used this code:

select    FORMAT( getdate()  ,&#39;yyyyMMdd&#39;)

huangapple
  • 本文由 发表于 2023年6月26日 13:24:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76553715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定