如何在SELECT查询中将timestamp字段格式化为mm/dd/yyyy HH:MM:SS格式?
Alright, let's break down what's going on here. First off, a critical clarification: in SQL Server, the timestamp type (now officially called rowversion) is a binary row version identifier—it doesn't store actual date or time data at all. That's exactly why your CAST(ssma_timestamp AS datetime) is returning wonky, unreadable results.
Since you mentioned this is an ssma_timestamp field, it's almost certainly a migration artifact from using the SQL Server Migration Assistant (SSMA) to bring data over from another database (like Sybase, MySQL, or Access). In those systems, timestamp often does represent a date/time value, which gets stored as binary data when migrated to SQL Server. Here's how to fix this:
Step 1: Convert Binary Timestamp to Datetime
Assuming your source database's timestamp stored milliseconds since the Unix epoch (1970-01-01 00:00:00), use DATEADD and CONVERT to turn the binary value into a proper datetime:
SELECT DATEADD(ms, CONVERT(BIGINT, ssma_timestamp), '1970-01-01 00:00:00') AS converted_datetime FROM sa_project
Step 2: Format to mm/dd/yyyy HH:MM:SS
Once you have a valid datetime value, you can format it to your desired string format.
For SQL Server 2012 and later:
Use the FORMAT function for clean, readable formatting:
SELECT FORMAT( DATEADD(ms, CONVERT(BIGINT, ssma_timestamp), '1970-01-01 00:00:00'), 'MM/dd/yyyy HH:mm:ss' ) AS formatted_datetime FROM sa_project
For older SQL Server versions (pre-2012):
The FORMAT function isn't available, so use CONVERT with style codes instead:
SELECT CONVERT(VARCHAR, DATEADD(ms, CONVERT(BIGINT, ssma_timestamp), '1970-01-01 00:00:00'), 101) + ' ' + CONVERT(VARCHAR, DATEADD(ms, CONVERT(BIGINT, ssma_timestamp), '1970-01-01 00:00:00'), 108) AS formatted_datetime FROM sa_project
Here, style 101 gives you mm/dd/yyyy and style 108 gives HH:MM:SS—we just concatenate them to get your full desired format.
Important Notes:
- If your source database used a different epoch (like
1900-01-01) or time unit (seconds instead of milliseconds), adjust theDATEADDparameter and base date accordingly. - If this really is a native SQL Server
rowversion(timestamp) field, it can't be converted to a meaningful date/time—its only purpose is tracking row modifications. In that case, double-check your migration setup or look for another field that stores the actual timestamp of record changes.
内容的提问来源于stack exchange,提问作者goodk

