Convert between SQL server timestamp (timestamp) and time format (datetime)

In SQL Server, "time stamp" (timestamp) and "time format" (datetime) are different data types, they have different meanings and purposes.

1. Timestamp (timestamp):
Timestamp is a binary data type in SQL Server, used to record the version number of each row in the table. It is automatically updated every time a row changes and is used for concurrency control and data consistency.
It's important to note that SQL Server's timestamp has nothing to do with calendar time or datetime, it's just an identifier used for internal data management.
2. Time format (datetime):
The time format is a data type used to store date and time values. It can represent dates and times from January 1, 1753 to December 31, 9999.
Columns of the datetime data type can be inserted or updated using standard date and time functions such as GETDATE() or strings providing date and time values.

Since timestamp (timestamp) and time format (datetime) have different meanings and purposes, they are not directly convertible to each other. If you need to convert a value of one of these types to the other, you can use the following method:

3. Convert timestamp (timestamp) to time format (datetime):
If you want to display the value of the timestamp as a date and time format, you can use the conversion function (CONVERT) to convert the timestamp value to the datetime data type. For example:

   SELECT CONVERT(datetime, timestamp_column) AS datetime_column
   FROM 表名;

This will take the value from the timestamp column named timestamp_column and convert it to a value of datetime data type.

4. Conversion of time format (datetime) to timestamp (timestamp):
Converting a value in time format to timestamp is not directly supported. Because timestamps are maintained automatically, you don't need to manually assign or change their values.
If you want to create a new timestamp column in the table to record the changed version of each row, you can use the ROWVERSION data type (equivalent to the timestamp type). For example:

   ALTER TABLE 表名
   ADD new_timestamp_column ROWVERSION;

This will add a new timestamp column newtimestampcolumn to the table, which will be automatically updated whenever a row changes.
Note that it is recommended to use the rowversion datatype to represent timestamps in SQL Server rather than timestamp because the behavior and usage of timestamp can be confusing. Therefore, the timestamp data type is deprecated and may be removed in a future release of SQL Server.

Guess you like

Origin blog.csdn.net/qq1507171150/article/details/131789349