• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2056
  • Last Modified:

Convert time to number in T-SQL

I'm sure this is easy - how do you convert the current date and time into a number in Transact SQL, taking into account split seconds? Quite a few digits if possible as i want to use it as an  ID on an Audit table (not a unique ID though for obvious reasons!)- thanks for looking
0
fuerteventura
Asked:
fuerteventura
4 Solutions
 
TimCotteeCommented:
You can cast it:

select cast(getdate() as decimal(18,13))

For example. The larger the precision/scale, the finer the resolution of the result.
0
 
Aneesh RetnakaranDatabase AdministratorCommented:
SELECT REPLACE(REPLACE(REPLACE(CONVERT (VARCHAR,GETDATE(),120),':',''),'-',''),' ','')
0
 
Ashish PatelCommented:
just an addition in above query

SELECT Cast(REPLACE(REPLACE(REPLACE(CONVERT (VARCHAR,GETDATE(),120),':',''),'-',''),' ','') as Numeric(18,0))
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
fuerteventuraAuthor Commented:
Many thanks for all your help, I know have further clarification on what is required - what i need is the following:

on 4th February 2008 at 11:30 and 20 seconds and 30 milliseconds I need an id such as the following:
0402200811302030

Can anyone help me get that/ I presume a datepart function may be usefull? I will be awarding points to all of the above as all answer the original question, many thanks again
0
 
Aneesh RetnakaranDatabase AdministratorCommented:
SELECT REPLACE(CONVERT(VARCHAR, GETDATE() , 103),'/','')+
       REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')


0
 
Scott PletcherSenior DBACommented:
Instead of:

mmddyyyyhhmmssss

you should use:

yyyymmddhhmmssss

So:

SELECT REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(16), GETDATE(), 121), '-', ''), ' ', ''), ':', ''), '.', '')

This allows direct sorting and means that new numbers will always be larger than earlier ones.

You can always re-format for display.  Don't allow the desired display format to make you use the wrong internal storage format :-) .
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now