E
E
Eugene2015-12-25 15:46:10
SQL
Eugene, 2015-12-25 15:46:10

How to insert datetime in MSSQL?

There is a table with a DateTime field.
View request:

INSERT INTO test (created_at) VALUES ('2015-12-25T15:32:06.427');

works.
And if I specify the value without T, then I get an error:
INSERT INTO test (created_at) VALUES ('2015-12-25 15:32:06.427');

[S0003][242] Converting a varchar data type to a datetime data type resulted in an out of range value.

Why is that? And how to make the table accept values ​​in the format '2015-12-25 15:32:06.427'

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dmitry Kovalsky, 2015-12-25
@djtahoma

No need to force the base. Either correct the input data or conjure with string type casts. I recommend to deal with the input data of the request.

R
res2001, 2015-12-25
@res2001

Convert the date/time to the standard format: 'yyyymmddhhmmss'
For the case of a single date, you can set: 'yyyymmdd'
In this format, there will never be a problem with writing the date/time.

N
nozzy, 2015-12-25
@nozzy

INSERT INTO test (created_at) VALUES (CAST('2015-12-25 15:32:06.427' AS DateTime));

R
Rustam Kalimullin, 2015-12-25
@SusaninIT

And we only store the timestamp in the database.
For comparisons and selections, it is enough (an integer in fact), and for output, we will convert it to the desired format.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question