I recognize there has been many questions posted about converting strings to datetime
already but I haven't found anything for converting a string like 20120225143620
which includes seconds.
I was trying to perform a clean conversion without substring-ing each segment out and concatenating with /
and :
.
Does anyone have any suggestions?
3条答案
按热度按时间js4nwp541#
You can use the
STUFF()
method to insert characters into your string to format it in to a value SQL Server will be able to understand:Output:
This approach will work if your string is always the same length and format, and it works from the end of the string to the start to produce a value in this format:
YYYYMMDD HH:MM:SS
For this, you don't need to separate the date portion in anyway, as SQL Server will be able to understand it as it's formatted.
Related Reading:
STUFF (Transact-SQL)
The STUFF function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.
STUFF ( character_expression , start , length , replaceWith_expression )
2o7dmzc52#
Output
fzsnzjdm3#
Please run the below sql command for unique key generation with timestamp