How to add 1 milliseconds to a datetime string?SQL Server 2008 datetime index performance bugConverting Cursor based filtering logic to CTE basedupdating the entire column with datetime values based on other values in the rowHow to Concatenate DateTime to nvarchar fieldINSERT Statement error message references column I am not including in queryUsing IF clause or while clause in OUTER APPLY
What's an "add" chord?
Clarifications on Poisson Regression
Adding two latex variables in Tikz beamer
"Chess is 90% tactics" - should a player focus more on tactics in order to improve?
Would nuclear bombs be effective against clouds of nanites?
Google just EOLed the original Pixel. How long until it's a brick?
Use field calculator QGIS: if value in one column, then value in new column
What is the lowest level at which a human can beat the 100m world record (or: the presumed human limit) without using magic?
A Simple Battleship Game
Where is a warlock's soul?
Is a Senate trial required after the House impeaches a president?
Ungrouping French Guiana from France in Natural Earth data using QGIS?
Is it safe to delete the default "postgres" role?
"Ich habe Durst" vs "Ich bin durstig": Which is more common?
Grep over multiple files redirecting to a different filename each time
How to talk about things I'm ashamed of, without showing this shame through non-verbal-communication?
CO₂ level is high enough that it reduces cognitive ability. Isn't that a reason to worry?
Prevent sleep if CPU usage is high
What type of beer is best for beer battered fish?
Time machine in Interstellar movie
How to write numbers in the form of using foreach or ...?
Perils of having a moon consisting of valuable material
What is the meaning of Text inside of AMS logo
How do I get a planar traveling party to use survival/spell slots for food/drink instead of an artificer's Replicate Magic Item infusion?
How to add 1 milliseconds to a datetime string?
SQL Server 2008 datetime index performance bugConverting Cursor based filtering logic to CTE basedupdating the entire column with datetime values based on other values in the rowHow to Concatenate DateTime to nvarchar fieldINSERT Statement error message references column I am not including in queryUsing IF clause or while clause in OUTER APPLY
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;
Based on a select, I can return x rows like this:
1 2019-07-23 10:14:04.000
1 2019-07-23 10:14:11.000
2 2019-07-23 10:45:32.000
1 2019-07-23 10:45:33.000
We have all milliseconds with 0.
Is there a way to add 1 by 1 milliseconds, so the select would look like this:
1 2019-07-23 10:14:04.001
1 2019-07-23 10:14:11.002
2 2019-07-23 10:45:32.003
1 2019-07-23 10:45:33.004
I'm trying to create a cursor or even a update with no success.
This is the query to get the results I want:
select top 10 ModifiedOn
from [SCHEMA].[dbo].[TABLE]
where FIELD between '2019-07-23 00:00' and '2019-07-23 23:59'
There are 81k values. The field is DATETIME
.
sql-server sql-server-2008 datetime varchar
add a comment
|
Based on a select, I can return x rows like this:
1 2019-07-23 10:14:04.000
1 2019-07-23 10:14:11.000
2 2019-07-23 10:45:32.000
1 2019-07-23 10:45:33.000
We have all milliseconds with 0.
Is there a way to add 1 by 1 milliseconds, so the select would look like this:
1 2019-07-23 10:14:04.001
1 2019-07-23 10:14:11.002
2 2019-07-23 10:45:32.003
1 2019-07-23 10:45:33.004
I'm trying to create a cursor or even a update with no success.
This is the query to get the results I want:
select top 10 ModifiedOn
from [SCHEMA].[dbo].[TABLE]
where FIELD between '2019-07-23 00:00' and '2019-07-23 23:59'
There are 81k values. The field is DATETIME
.
sql-server sql-server-2008 datetime varchar
2
Are you trying to add 1 millisecond to row 1, 2 milliseconds to row 2, 3 milliseconds to row 3, etc.?
– John Eisbrener
Jul 23 at 13:38
add a comment
|
Based on a select, I can return x rows like this:
1 2019-07-23 10:14:04.000
1 2019-07-23 10:14:11.000
2 2019-07-23 10:45:32.000
1 2019-07-23 10:45:33.000
We have all milliseconds with 0.
Is there a way to add 1 by 1 milliseconds, so the select would look like this:
1 2019-07-23 10:14:04.001
1 2019-07-23 10:14:11.002
2 2019-07-23 10:45:32.003
1 2019-07-23 10:45:33.004
I'm trying to create a cursor or even a update with no success.
This is the query to get the results I want:
select top 10 ModifiedOn
from [SCHEMA].[dbo].[TABLE]
where FIELD between '2019-07-23 00:00' and '2019-07-23 23:59'
There are 81k values. The field is DATETIME
.
sql-server sql-server-2008 datetime varchar
Based on a select, I can return x rows like this:
1 2019-07-23 10:14:04.000
1 2019-07-23 10:14:11.000
2 2019-07-23 10:45:32.000
1 2019-07-23 10:45:33.000
We have all milliseconds with 0.
Is there a way to add 1 by 1 milliseconds, so the select would look like this:
1 2019-07-23 10:14:04.001
1 2019-07-23 10:14:11.002
2 2019-07-23 10:45:32.003
1 2019-07-23 10:45:33.004
I'm trying to create a cursor or even a update with no success.
This is the query to get the results I want:
select top 10 ModifiedOn
from [SCHEMA].[dbo].[TABLE]
where FIELD between '2019-07-23 00:00' and '2019-07-23 23:59'
There are 81k values. The field is DATETIME
.
sql-server sql-server-2008 datetime varchar
sql-server sql-server-2008 datetime varchar
edited Jul 26 at 13:55
Glorfindel
1,2131 gold badge9 silver badges16 bronze badges
1,2131 gold badge9 silver badges16 bronze badges
asked Jul 23 at 13:06
Racer SQLRacer SQL
3,5685 gold badges31 silver badges77 bronze badges
3,5685 gold badges31 silver badges77 bronze badges
2
Are you trying to add 1 millisecond to row 1, 2 milliseconds to row 2, 3 milliseconds to row 3, etc.?
– John Eisbrener
Jul 23 at 13:38
add a comment
|
2
Are you trying to add 1 millisecond to row 1, 2 milliseconds to row 2, 3 milliseconds to row 3, etc.?
– John Eisbrener
Jul 23 at 13:38
2
2
Are you trying to add 1 millisecond to row 1, 2 milliseconds to row 2, 3 milliseconds to row 3, etc.?
– John Eisbrener
Jul 23 at 13:38
Are you trying to add 1 millisecond to row 1, 2 milliseconds to row 2, 3 milliseconds to row 3, etc.?
– John Eisbrener
Jul 23 at 13:38
add a comment
|
5 Answers
5
active
oldest
votes
Datetime
is not precise to the level of 1 millisecond. What you are asking for is not possible unless you change to a different datatype (i.e. datetime2
).
Documentation
Important quote:
Accuracy Rounded to increments of .000, .003, or .007 seconds
add a comment
|
The DateAdd
function is what you are looking for.
Use millisecond
as the first parameter to the function, to tell it that you are adding milliseconds. Then use 1
as the second parameter, for the number of milliseconds to add.
Here is an example, grabbing the current time into a variable, and then adding one millisecond to it and saving the result as a second variable, and then printing each variable
Declare @RightNow as DateTime2
Declare @RightNowPlusAMillisecond as DateTime2
Select @RightNow = Getdate()
Select @RightNowPlusAMillisecond = DateAdd(millisecond,1,@RightNow)
Print @RightNow
Print @RightNowPlusAMillisecond
Results:
2019-07-23 08:25:38.3500000
2019-07-23 08:25:38.3510000
Note:
As Forrest points out in another answer, the datetime
data type does not guarantee millisecond precision. It rounds to increments of .000, .003, or .007 seconds. If you want millisecond precision, use datetime2
.
add a comment
|
@Doug-Deden has the right starting point, but I just wanted to try to answer what I thought was the original intention of the question - how to apply it to a result set with increasing milliseconds per row.
In that case, you can use ROW_NUMBER and a Common Table Expression (edit as needed for you table structure, including joins, etc.).
Select to show values:
;WITH CTE AS (
SELECT t.my_id, t.my_date_column, ROW_NUMBER() OVER (ORDER BY my_date_column, my_id DESC) AS R
FROM Table1 t
)
SELECT TOP 1000 *, DATEADD(MILLISECOND, R, CAST(my_date_column AS datetime2)) [new_date]
FROM CTE
ORDER BY my_date_column
Update joins back to original table:
;WITH CTE AS (
SELECT t.my_id, t.my_date_column, ROW_NUMBER() OVER (ORDER BY my_date_column, my_id DESC) AS R
FROM Table1 t
)
UPDATE t SET
my_date_column = DATEADD(MILLISECOND, R, CAST(my_date_column AS datetime2))
FROM CTE c
JOIN Table1 t ON c.my_id = t.my_id
This CTE is updatable. No need to join back toTable1
. Just doUPDATE CTE SET my_date_column =...
– Steven Hibble
Jul 29 at 15:58
add a comment
|
I have done it using DATETIME2(3)
.
As you can see on the query below, it is more economic
:
declare @dt1 datetime2(3)
declare @dt2 datetime2
SELECT @DT1 = SYSDATETIME()
SELECT @DT2= SYSDATETIME()
SELECT [THE LENGTH OF DATETIME2]=DATALENGTH(@DT2)
,[THE LENGTH OF DATETIME2(3)]=DATALENGTH(@DT1)
The differences between datetime
and datetime2
are well explained here.
For this exercise
I create a temp table for testing purposes, and populate it with 999 different random dates
from 01-jan-2019
and today (23-july-2019
)
and then in order, I set the milliseconds from 1 to 999
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOEXEC OFF
IF OBJECT_ID ('TEMPDB..#T1') IS NOT NULL
DROP TABLE #T1
CREATE TABLE #t1(the_date DATETIME2(3) NOT NULL PRIMARY KEY CLUSTERED )
GO
-- run this 999 times - hopefully there will be no duplicates
-- SELECT 204*24*60*60 - today is 23-july-2019 - the 203rd day of the year
DECLARE @DT DATETIME2(3)
SELECT @DT = CONVERT(DATETIME2(3),
DATEADD(SECOND, ABS(CHECKSUM(NEWID()) % 17625600),
'2019-01-01'),120)
--SELECT @DT
IF NOT EXISTS( SELECT 1 FROM #T1 WHERE THE_DATE = @DT)
INSERT INTO #T1 VALUES (@DT)
GO 999
--check it out what we have
SELECT * FROM #T1
--get the date and the new date
SELECT
THE_DATE
,THE_NEW_DATE= DATEADD(MILLISECOND, ROW_NUMBER() OVER (ORDER BY THE_DATE), THE_DATE )
FROM #T1
and this is what I get: (partial view)
add a comment
|
One of the other posters is correct; DATETIME
(in T-SQL) is not accurate to the millisecond (it is accurate to the centisecond).
For that level of accuracy, you want to use DATETIME2
.
Here is an example of converting a string datetime
to datetime2
,
then adding 1 millisecond, and lastly, converting back to a string.
select convert(
varchar(MAX), --in T-SQL, varchar length is optional
dateadd(
millisecond,
1,
convert(
datetime2,
'2019-07-23 12:01:23.11'
)
)
)
3
Please don't specifyvarchar
without length.
– Aaron Bertrand♦
Jul 23 at 15:01
add a comment
|
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "182"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f243534%2fhow-to-add-1-milliseconds-to-a-datetime-string%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
Datetime
is not precise to the level of 1 millisecond. What you are asking for is not possible unless you change to a different datatype (i.e. datetime2
).
Documentation
Important quote:
Accuracy Rounded to increments of .000, .003, or .007 seconds
add a comment
|
Datetime
is not precise to the level of 1 millisecond. What you are asking for is not possible unless you change to a different datatype (i.e. datetime2
).
Documentation
Important quote:
Accuracy Rounded to increments of .000, .003, or .007 seconds
add a comment
|
Datetime
is not precise to the level of 1 millisecond. What you are asking for is not possible unless you change to a different datatype (i.e. datetime2
).
Documentation
Important quote:
Accuracy Rounded to increments of .000, .003, or .007 seconds
Datetime
is not precise to the level of 1 millisecond. What you are asking for is not possible unless you change to a different datatype (i.e. datetime2
).
Documentation
Important quote:
Accuracy Rounded to increments of .000, .003, or .007 seconds
answered Jul 23 at 14:07
ForrestForrest
3,6351 gold badge10 silver badges28 bronze badges
3,6351 gold badge10 silver badges28 bronze badges
add a comment
|
add a comment
|
The DateAdd
function is what you are looking for.
Use millisecond
as the first parameter to the function, to tell it that you are adding milliseconds. Then use 1
as the second parameter, for the number of milliseconds to add.
Here is an example, grabbing the current time into a variable, and then adding one millisecond to it and saving the result as a second variable, and then printing each variable
Declare @RightNow as DateTime2
Declare @RightNowPlusAMillisecond as DateTime2
Select @RightNow = Getdate()
Select @RightNowPlusAMillisecond = DateAdd(millisecond,1,@RightNow)
Print @RightNow
Print @RightNowPlusAMillisecond
Results:
2019-07-23 08:25:38.3500000
2019-07-23 08:25:38.3510000
Note:
As Forrest points out in another answer, the datetime
data type does not guarantee millisecond precision. It rounds to increments of .000, .003, or .007 seconds. If you want millisecond precision, use datetime2
.
add a comment
|
The DateAdd
function is what you are looking for.
Use millisecond
as the first parameter to the function, to tell it that you are adding milliseconds. Then use 1
as the second parameter, for the number of milliseconds to add.
Here is an example, grabbing the current time into a variable, and then adding one millisecond to it and saving the result as a second variable, and then printing each variable
Declare @RightNow as DateTime2
Declare @RightNowPlusAMillisecond as DateTime2
Select @RightNow = Getdate()
Select @RightNowPlusAMillisecond = DateAdd(millisecond,1,@RightNow)
Print @RightNow
Print @RightNowPlusAMillisecond
Results:
2019-07-23 08:25:38.3500000
2019-07-23 08:25:38.3510000
Note:
As Forrest points out in another answer, the datetime
data type does not guarantee millisecond precision. It rounds to increments of .000, .003, or .007 seconds. If you want millisecond precision, use datetime2
.
add a comment
|
The DateAdd
function is what you are looking for.
Use millisecond
as the first parameter to the function, to tell it that you are adding milliseconds. Then use 1
as the second parameter, for the number of milliseconds to add.
Here is an example, grabbing the current time into a variable, and then adding one millisecond to it and saving the result as a second variable, and then printing each variable
Declare @RightNow as DateTime2
Declare @RightNowPlusAMillisecond as DateTime2
Select @RightNow = Getdate()
Select @RightNowPlusAMillisecond = DateAdd(millisecond,1,@RightNow)
Print @RightNow
Print @RightNowPlusAMillisecond
Results:
2019-07-23 08:25:38.3500000
2019-07-23 08:25:38.3510000
Note:
As Forrest points out in another answer, the datetime
data type does not guarantee millisecond precision. It rounds to increments of .000, .003, or .007 seconds. If you want millisecond precision, use datetime2
.
The DateAdd
function is what you are looking for.
Use millisecond
as the first parameter to the function, to tell it that you are adding milliseconds. Then use 1
as the second parameter, for the number of milliseconds to add.
Here is an example, grabbing the current time into a variable, and then adding one millisecond to it and saving the result as a second variable, and then printing each variable
Declare @RightNow as DateTime2
Declare @RightNowPlusAMillisecond as DateTime2
Select @RightNow = Getdate()
Select @RightNowPlusAMillisecond = DateAdd(millisecond,1,@RightNow)
Print @RightNow
Print @RightNowPlusAMillisecond
Results:
2019-07-23 08:25:38.3500000
2019-07-23 08:25:38.3510000
Note:
As Forrest points out in another answer, the datetime
data type does not guarantee millisecond precision. It rounds to increments of .000, .003, or .007 seconds. If you want millisecond precision, use datetime2
.
edited Jul 23 at 16:23
answered Jul 23 at 13:29
Doug DedenDoug Deden
85310 bronze badges
85310 bronze badges
add a comment
|
add a comment
|
@Doug-Deden has the right starting point, but I just wanted to try to answer what I thought was the original intention of the question - how to apply it to a result set with increasing milliseconds per row.
In that case, you can use ROW_NUMBER and a Common Table Expression (edit as needed for you table structure, including joins, etc.).
Select to show values:
;WITH CTE AS (
SELECT t.my_id, t.my_date_column, ROW_NUMBER() OVER (ORDER BY my_date_column, my_id DESC) AS R
FROM Table1 t
)
SELECT TOP 1000 *, DATEADD(MILLISECOND, R, CAST(my_date_column AS datetime2)) [new_date]
FROM CTE
ORDER BY my_date_column
Update joins back to original table:
;WITH CTE AS (
SELECT t.my_id, t.my_date_column, ROW_NUMBER() OVER (ORDER BY my_date_column, my_id DESC) AS R
FROM Table1 t
)
UPDATE t SET
my_date_column = DATEADD(MILLISECOND, R, CAST(my_date_column AS datetime2))
FROM CTE c
JOIN Table1 t ON c.my_id = t.my_id
This CTE is updatable. No need to join back toTable1
. Just doUPDATE CTE SET my_date_column =...
– Steven Hibble
Jul 29 at 15:58
add a comment
|
@Doug-Deden has the right starting point, but I just wanted to try to answer what I thought was the original intention of the question - how to apply it to a result set with increasing milliseconds per row.
In that case, you can use ROW_NUMBER and a Common Table Expression (edit as needed for you table structure, including joins, etc.).
Select to show values:
;WITH CTE AS (
SELECT t.my_id, t.my_date_column, ROW_NUMBER() OVER (ORDER BY my_date_column, my_id DESC) AS R
FROM Table1 t
)
SELECT TOP 1000 *, DATEADD(MILLISECOND, R, CAST(my_date_column AS datetime2)) [new_date]
FROM CTE
ORDER BY my_date_column
Update joins back to original table:
;WITH CTE AS (
SELECT t.my_id, t.my_date_column, ROW_NUMBER() OVER (ORDER BY my_date_column, my_id DESC) AS R
FROM Table1 t
)
UPDATE t SET
my_date_column = DATEADD(MILLISECOND, R, CAST(my_date_column AS datetime2))
FROM CTE c
JOIN Table1 t ON c.my_id = t.my_id
This CTE is updatable. No need to join back toTable1
. Just doUPDATE CTE SET my_date_column =...
– Steven Hibble
Jul 29 at 15:58
add a comment
|
@Doug-Deden has the right starting point, but I just wanted to try to answer what I thought was the original intention of the question - how to apply it to a result set with increasing milliseconds per row.
In that case, you can use ROW_NUMBER and a Common Table Expression (edit as needed for you table structure, including joins, etc.).
Select to show values:
;WITH CTE AS (
SELECT t.my_id, t.my_date_column, ROW_NUMBER() OVER (ORDER BY my_date_column, my_id DESC) AS R
FROM Table1 t
)
SELECT TOP 1000 *, DATEADD(MILLISECOND, R, CAST(my_date_column AS datetime2)) [new_date]
FROM CTE
ORDER BY my_date_column
Update joins back to original table:
;WITH CTE AS (
SELECT t.my_id, t.my_date_column, ROW_NUMBER() OVER (ORDER BY my_date_column, my_id DESC) AS R
FROM Table1 t
)
UPDATE t SET
my_date_column = DATEADD(MILLISECOND, R, CAST(my_date_column AS datetime2))
FROM CTE c
JOIN Table1 t ON c.my_id = t.my_id
@Doug-Deden has the right starting point, but I just wanted to try to answer what I thought was the original intention of the question - how to apply it to a result set with increasing milliseconds per row.
In that case, you can use ROW_NUMBER and a Common Table Expression (edit as needed for you table structure, including joins, etc.).
Select to show values:
;WITH CTE AS (
SELECT t.my_id, t.my_date_column, ROW_NUMBER() OVER (ORDER BY my_date_column, my_id DESC) AS R
FROM Table1 t
)
SELECT TOP 1000 *, DATEADD(MILLISECOND, R, CAST(my_date_column AS datetime2)) [new_date]
FROM CTE
ORDER BY my_date_column
Update joins back to original table:
;WITH CTE AS (
SELECT t.my_id, t.my_date_column, ROW_NUMBER() OVER (ORDER BY my_date_column, my_id DESC) AS R
FROM Table1 t
)
UPDATE t SET
my_date_column = DATEADD(MILLISECOND, R, CAST(my_date_column AS datetime2))
FROM CTE c
JOIN Table1 t ON c.my_id = t.my_id
edited Jul 24 at 14:17
Marcello Miorelli
7,04329 gold badges83 silver badges182 bronze badges
7,04329 gold badges83 silver badges182 bronze badges
answered Jul 23 at 13:42
BlueGIBlueGI
2761 silver badge5 bronze badges
2761 silver badge5 bronze badges
This CTE is updatable. No need to join back toTable1
. Just doUPDATE CTE SET my_date_column =...
– Steven Hibble
Jul 29 at 15:58
add a comment
|
This CTE is updatable. No need to join back toTable1
. Just doUPDATE CTE SET my_date_column =...
– Steven Hibble
Jul 29 at 15:58
This CTE is updatable. No need to join back to
Table1
. Just do UPDATE CTE SET my_date_column =...
– Steven Hibble
Jul 29 at 15:58
This CTE is updatable. No need to join back to
Table1
. Just do UPDATE CTE SET my_date_column =...
– Steven Hibble
Jul 29 at 15:58
add a comment
|
I have done it using DATETIME2(3)
.
As you can see on the query below, it is more economic
:
declare @dt1 datetime2(3)
declare @dt2 datetime2
SELECT @DT1 = SYSDATETIME()
SELECT @DT2= SYSDATETIME()
SELECT [THE LENGTH OF DATETIME2]=DATALENGTH(@DT2)
,[THE LENGTH OF DATETIME2(3)]=DATALENGTH(@DT1)
The differences between datetime
and datetime2
are well explained here.
For this exercise
I create a temp table for testing purposes, and populate it with 999 different random dates
from 01-jan-2019
and today (23-july-2019
)
and then in order, I set the milliseconds from 1 to 999
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOEXEC OFF
IF OBJECT_ID ('TEMPDB..#T1') IS NOT NULL
DROP TABLE #T1
CREATE TABLE #t1(the_date DATETIME2(3) NOT NULL PRIMARY KEY CLUSTERED )
GO
-- run this 999 times - hopefully there will be no duplicates
-- SELECT 204*24*60*60 - today is 23-july-2019 - the 203rd day of the year
DECLARE @DT DATETIME2(3)
SELECT @DT = CONVERT(DATETIME2(3),
DATEADD(SECOND, ABS(CHECKSUM(NEWID()) % 17625600),
'2019-01-01'),120)
--SELECT @DT
IF NOT EXISTS( SELECT 1 FROM #T1 WHERE THE_DATE = @DT)
INSERT INTO #T1 VALUES (@DT)
GO 999
--check it out what we have
SELECT * FROM #T1
--get the date and the new date
SELECT
THE_DATE
,THE_NEW_DATE= DATEADD(MILLISECOND, ROW_NUMBER() OVER (ORDER BY THE_DATE), THE_DATE )
FROM #T1
and this is what I get: (partial view)
add a comment
|
I have done it using DATETIME2(3)
.
As you can see on the query below, it is more economic
:
declare @dt1 datetime2(3)
declare @dt2 datetime2
SELECT @DT1 = SYSDATETIME()
SELECT @DT2= SYSDATETIME()
SELECT [THE LENGTH OF DATETIME2]=DATALENGTH(@DT2)
,[THE LENGTH OF DATETIME2(3)]=DATALENGTH(@DT1)
The differences between datetime
and datetime2
are well explained here.
For this exercise
I create a temp table for testing purposes, and populate it with 999 different random dates
from 01-jan-2019
and today (23-july-2019
)
and then in order, I set the milliseconds from 1 to 999
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOEXEC OFF
IF OBJECT_ID ('TEMPDB..#T1') IS NOT NULL
DROP TABLE #T1
CREATE TABLE #t1(the_date DATETIME2(3) NOT NULL PRIMARY KEY CLUSTERED )
GO
-- run this 999 times - hopefully there will be no duplicates
-- SELECT 204*24*60*60 - today is 23-july-2019 - the 203rd day of the year
DECLARE @DT DATETIME2(3)
SELECT @DT = CONVERT(DATETIME2(3),
DATEADD(SECOND, ABS(CHECKSUM(NEWID()) % 17625600),
'2019-01-01'),120)
--SELECT @DT
IF NOT EXISTS( SELECT 1 FROM #T1 WHERE THE_DATE = @DT)
INSERT INTO #T1 VALUES (@DT)
GO 999
--check it out what we have
SELECT * FROM #T1
--get the date and the new date
SELECT
THE_DATE
,THE_NEW_DATE= DATEADD(MILLISECOND, ROW_NUMBER() OVER (ORDER BY THE_DATE), THE_DATE )
FROM #T1
and this is what I get: (partial view)
add a comment
|
I have done it using DATETIME2(3)
.
As you can see on the query below, it is more economic
:
declare @dt1 datetime2(3)
declare @dt2 datetime2
SELECT @DT1 = SYSDATETIME()
SELECT @DT2= SYSDATETIME()
SELECT [THE LENGTH OF DATETIME2]=DATALENGTH(@DT2)
,[THE LENGTH OF DATETIME2(3)]=DATALENGTH(@DT1)
The differences between datetime
and datetime2
are well explained here.
For this exercise
I create a temp table for testing purposes, and populate it with 999 different random dates
from 01-jan-2019
and today (23-july-2019
)
and then in order, I set the milliseconds from 1 to 999
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOEXEC OFF
IF OBJECT_ID ('TEMPDB..#T1') IS NOT NULL
DROP TABLE #T1
CREATE TABLE #t1(the_date DATETIME2(3) NOT NULL PRIMARY KEY CLUSTERED )
GO
-- run this 999 times - hopefully there will be no duplicates
-- SELECT 204*24*60*60 - today is 23-july-2019 - the 203rd day of the year
DECLARE @DT DATETIME2(3)
SELECT @DT = CONVERT(DATETIME2(3),
DATEADD(SECOND, ABS(CHECKSUM(NEWID()) % 17625600),
'2019-01-01'),120)
--SELECT @DT
IF NOT EXISTS( SELECT 1 FROM #T1 WHERE THE_DATE = @DT)
INSERT INTO #T1 VALUES (@DT)
GO 999
--check it out what we have
SELECT * FROM #T1
--get the date and the new date
SELECT
THE_DATE
,THE_NEW_DATE= DATEADD(MILLISECOND, ROW_NUMBER() OVER (ORDER BY THE_DATE), THE_DATE )
FROM #T1
and this is what I get: (partial view)
I have done it using DATETIME2(3)
.
As you can see on the query below, it is more economic
:
declare @dt1 datetime2(3)
declare @dt2 datetime2
SELECT @DT1 = SYSDATETIME()
SELECT @DT2= SYSDATETIME()
SELECT [THE LENGTH OF DATETIME2]=DATALENGTH(@DT2)
,[THE LENGTH OF DATETIME2(3)]=DATALENGTH(@DT1)
The differences between datetime
and datetime2
are well explained here.
For this exercise
I create a temp table for testing purposes, and populate it with 999 different random dates
from 01-jan-2019
and today (23-july-2019
)
and then in order, I set the milliseconds from 1 to 999
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOEXEC OFF
IF OBJECT_ID ('TEMPDB..#T1') IS NOT NULL
DROP TABLE #T1
CREATE TABLE #t1(the_date DATETIME2(3) NOT NULL PRIMARY KEY CLUSTERED )
GO
-- run this 999 times - hopefully there will be no duplicates
-- SELECT 204*24*60*60 - today is 23-july-2019 - the 203rd day of the year
DECLARE @DT DATETIME2(3)
SELECT @DT = CONVERT(DATETIME2(3),
DATEADD(SECOND, ABS(CHECKSUM(NEWID()) % 17625600),
'2019-01-01'),120)
--SELECT @DT
IF NOT EXISTS( SELECT 1 FROM #T1 WHERE THE_DATE = @DT)
INSERT INTO #T1 VALUES (@DT)
GO 999
--check it out what we have
SELECT * FROM #T1
--get the date and the new date
SELECT
THE_DATE
,THE_NEW_DATE= DATEADD(MILLISECOND, ROW_NUMBER() OVER (ORDER BY THE_DATE), THE_DATE )
FROM #T1
and this is what I get: (partial view)
edited Jul 24 at 11:56
answered Jul 23 at 18:06
Marcello MiorelliMarcello Miorelli
7,04329 gold badges83 silver badges182 bronze badges
7,04329 gold badges83 silver badges182 bronze badges
add a comment
|
add a comment
|
One of the other posters is correct; DATETIME
(in T-SQL) is not accurate to the millisecond (it is accurate to the centisecond).
For that level of accuracy, you want to use DATETIME2
.
Here is an example of converting a string datetime
to datetime2
,
then adding 1 millisecond, and lastly, converting back to a string.
select convert(
varchar(MAX), --in T-SQL, varchar length is optional
dateadd(
millisecond,
1,
convert(
datetime2,
'2019-07-23 12:01:23.11'
)
)
)
3
Please don't specifyvarchar
without length.
– Aaron Bertrand♦
Jul 23 at 15:01
add a comment
|
One of the other posters is correct; DATETIME
(in T-SQL) is not accurate to the millisecond (it is accurate to the centisecond).
For that level of accuracy, you want to use DATETIME2
.
Here is an example of converting a string datetime
to datetime2
,
then adding 1 millisecond, and lastly, converting back to a string.
select convert(
varchar(MAX), --in T-SQL, varchar length is optional
dateadd(
millisecond,
1,
convert(
datetime2,
'2019-07-23 12:01:23.11'
)
)
)
3
Please don't specifyvarchar
without length.
– Aaron Bertrand♦
Jul 23 at 15:01
add a comment
|
One of the other posters is correct; DATETIME
(in T-SQL) is not accurate to the millisecond (it is accurate to the centisecond).
For that level of accuracy, you want to use DATETIME2
.
Here is an example of converting a string datetime
to datetime2
,
then adding 1 millisecond, and lastly, converting back to a string.
select convert(
varchar(MAX), --in T-SQL, varchar length is optional
dateadd(
millisecond,
1,
convert(
datetime2,
'2019-07-23 12:01:23.11'
)
)
)
One of the other posters is correct; DATETIME
(in T-SQL) is not accurate to the millisecond (it is accurate to the centisecond).
For that level of accuracy, you want to use DATETIME2
.
Here is an example of converting a string datetime
to datetime2
,
then adding 1 millisecond, and lastly, converting back to a string.
select convert(
varchar(MAX), --in T-SQL, varchar length is optional
dateadd(
millisecond,
1,
convert(
datetime2,
'2019-07-23 12:01:23.11'
)
)
)
edited Jul 23 at 17:00
Marcello Miorelli
7,04329 gold badges83 silver badges182 bronze badges
7,04329 gold badges83 silver badges182 bronze badges
answered Jul 23 at 14:55
McDonalds Happy MealMcDonalds Happy Meal
716 bronze badges
716 bronze badges
3
Please don't specifyvarchar
without length.
– Aaron Bertrand♦
Jul 23 at 15:01
add a comment
|
3
Please don't specifyvarchar
without length.
– Aaron Bertrand♦
Jul 23 at 15:01
3
3
Please don't specify
varchar
without length.– Aaron Bertrand♦
Jul 23 at 15:01
Please don't specify
varchar
without length.– Aaron Bertrand♦
Jul 23 at 15:01
add a comment
|
Thanks for contributing an answer to Database Administrators Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f243534%2fhow-to-add-1-milliseconds-to-a-datetime-string%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
Are you trying to add 1 millisecond to row 1, 2 milliseconds to row 2, 3 milliseconds to row 3, etc.?
– John Eisbrener
Jul 23 at 13:38