Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a datetime value with GetDate() function to a SQL server (2005) table?

I am working (or fixing bugs) on an application which was developed in VS 2005 C#. The application saves data to a SQL server 2005. One of insert SQL statement tries to insert a time-stamp value to a field with GetDate() TSQL function as date time value.

Insert into table1 (field1, ... fieldDt) values ('value1', ... GetDate());

The reason to use GetDate() function is that the SQL server may be at a remove site, and the date time may be in a difference time zone. Therefore, GetDate() will always get a date from the server. As the function can be verified in SQL Management Studio, this is what I get:

SELECT GetDate(), LEN(GetDate());
-- 2010-06-10 14:04:48.293   19

One thing I realize is that the length is not up to the milliseconds, i.e., 19 is actually for '2010-06-10 14:04:48'. Anyway, the issue I have right now is that after the insert, the fieldDt actually has a date time value up to minutes, for example, '2010-06-10 14:04:00'. I am not sure why. I don't have permission to update or change the table with a trigger to update the field.

My question is that how I can use a INSERT T-SQL to add a new row with a date time value ( SQL server's local date time) with a precision up to milliseconds?

like image 919
David.Chu.ca Avatar asked Oct 19 '25 14:10

David.Chu.ca


2 Answers

Check your table. My guess is that the FieldDT column has a data type of SmallDateTime which stores date and time, but with a precision to the nearest minute. If my guess is correct, you will not be able to store seconds or milliseconds unless you change the data type of the column.

like image 153
George Mastros Avatar answered Oct 22 '25 05:10

George Mastros


I would guess that you are not storing the GetDate() value in a DateTime field. If you store the value in a datetime field you will get the maximum precision allowed by the DateTime type. Additionally, DateTime is a binary type (a double actually) so 19 means 19 bytes, not 19 characters.

Try to create a simple table with a Datetime field like this

CREATE TABLE [dbo].[DateTable](
[DateField] [datetime] NOT NULL
)

And add a date with

insert into datetable (datefield) values(getdate())

When you execute a select you will get back a value including milliseconds. The following query

select *  from datetable

returns

2010-06-11 00:38:46.660

like image 37
Panagiotis Kanavos Avatar answered Oct 22 '25 04:10

Panagiotis Kanavos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!