0

I have a data & time format column which I would like to convert to the following format in Microsoft SQL Server: yyyymmddhhmmss00000

So for example if I have 2021-02-04 11:49:50 this will be converted to 2021020411495000000.

Any one knows how to do it please?

1
  • 1
    Have a look at CONVERT, REPLACE and the concatenation operator (+). Commented Feb 4, 2021 at 10:54

2 Answers 2

2

You can use the FORMAT function:

SELECT FORMAT(myDate, 'yyyyMMddHHmmss00000')
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for this but you have to be careful when using this because it doesn't distinguish between AM and PM
Sorry needs to be uppercase HH have corrected
1

By converting the date to NVARCHAR once with format 112 and once with format 8 you can extract the numeric date and the time without milliseconds. After removing : from the time you can concat these two strings and convert them to bigint. Following an example:

DECLARE @d DATETIME = GETDATE()
SELECT CAST(CONVERT(NVARCHAR(8), @d, 112) + REPLACE(CONVERT(NVARCHAR(8), @d, 8), ':', '') + '00000' AS BIGINT)

2 Comments

Does it "need" to be an nvarchar? As the value only consists of numerical characters, why not use a varchar (which is half the size), or even better (as it's fixed width) a char?
@Larnu thanks for the hint. Yes, you are right - char and varchar work as well. Sorry I didn't think of this - we just used the nvarchar way in several of our queries and I just rememberd it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.