i've created a view and need to convert a datetime to following format:
2011 06 (year, empty-space, two digit numeric month)
What's the best way to format it?
Here is the datetime(in a subquery in the view, "rounded" to month):
DATEADD(month, DATEDIFF(month, 0,Claim_Submitted_Date), 0) AS Year_Month_Submit
This give开发者_开发知识库s me year,month and day(of course 01
because datetime was rounded to first day of month):
CONVERT(varchar,Year_Month_Submit,112)as Year_Month_Submit
Thank you in advance
select stuff(convert(varchar(6), Claim_Submitted_Date, 112), 5,0,' ')
Answer to Tim Schmelter :
You can compare the methods like this:
declare @i int = 0
declare @dummy varchar(20)
while @i < 1000000
begin
--set @dummy = stuff(convert(varchar(6), getdate() + @i / 1000, 112), 5,0,' ')
set @dummy = REPLACE(CONVERT(VARCHAR(7), getdate() + @i / 1000, 121), '-', ' ')
set @i = @i + 1
end
On my server, my version takes 1 second and the other version takes 3 seconds
Try this:
SELECT LTRIM(STR(YEAR(Claim_Submitted_Date))) + ' ' +
RIGHT('0'+ LTRIM(STR(MONTH(Claim_Submitted_Date))), 2)
FROM MyTable
How about
STUFF(STUFF('YYYY 0M', 1, 4, YEAR(Claim_Submitted_Date)), 8 - LEN(MONTH(Claim_Submitted_Date)), 2, MONTH(Claim_Submitted_Date))
Or
REPLACE(CONVERT(VARCHAR(7), @Claim_Submitted_Date, 121), '-', ' ')
精彩评论