When using this statement
create table demo (
ts timestamp
)
insert into demo select current_timestamp
I get the following error:
Cannot insert an explicit value into a timestamp column. Use INSERT with a column list to exclude the timestamp column, or insert a DEFAULT into the timestamp column
How do I insert the current time to a timestamp
column?
How to insert current time into a timestamp with SQL Server:
Answer: You can't, and here's why.
In newer versions of SQL Server,
timestamp
is renamed toRowVersion
. Rightly so, because timestamp is very misleading.SQL Server timestamp IS NOT set by the user and does not represent a date or time. timestamp is just a binary representation of a consecutive number, it's only good for making sure a row hasn't changed since it's been read.
If you want to store a date or a time, do not use timestamp, you must use one of the other datatypes, like for example
datetime
,smalldatetime
,date
,time
orDATETIME2
For example:
So timestamp is some kind of binary number. What if we try casting it to datetime?
The current year for me is not 1900. So I'm not sure what SQL Server is thinking.
There is some good information in these answers. Suppose you are dealing with databases which you can't alter, and that you are copying data from one version of the table to another, or from the same table in one database to another. Suppose also that there are lots of columns, and you either need data from all the columns, or the columns which you don't need don't have default values. You need to write a query with all the column names.
Here is a query which returns all the non-timestamp column names for a table, which you can cut and paste into your insert query. FYI: 189 is the type ID for timestamp.
Just change the name of the table at the top from 'Product' to your table name. The query will return a list of column names:
If you are copying data from one database (DB1) to another database(DB2) you could use this query.
According to MSDN,
timestamp
You're probably looking for the
datetime
data type instead.Assume Table1 and Table2 have three columns A, B and TimeStamp. I want to insert from Table1 into Table2.
This fails with the timestamp error:
This works:
create table demo ( id int, ts timestamp )
insert into demo(id,ts) values (1, DEFAULT)
If you have a need to copy the exact same timestamp data, change the data type in the destination table from timestamp to binary(8) -- i used varbinary(8) and it worked fine.
This obviously breaks any timestamp functionality in the destination table, so make sure you're ok with that first.