Tuesday, October 8, 2019

Absolutely unique timed file names

       That is pretty common task to generate new files with a timestamp in their names.
It gives you ability to easily identify them, sort them and make them pretty unique.
However, if you have a very busy process it is possible that duplicate name will be produced and you might loose some data.

To avoid that situation I've came up with following solution.

Script #1. Generating timestamp.

The shortest query to generate only-numeric timestamp I've came up is that:
SELECT REPLACE(REPLACE(REPLACE(REPLACE(SYSDATETIME(),'-',''),' ',''),':',''),'.','');

It produces pretty unique output like this: "201910080935132176384"
But if you are not satisfied by that uniqueness you can add some more complexity by randomizing.

Script #2. Generating random number.

SELECT CAST(ABS(CAST(CAST(NewID() as BINARY(16)) as BIGINT)) as VARCHAR);

That generates a very unique numeric sequence up to 19 characters long like this: "4978829248728009422". If you'd like to combine it with time stamp it will be up to 40 characters long.

Script #3. Generating absolutely unique timed file name.

SELECT 'MyFile_'
+ REPLACE(REPLACE(REPLACE(REPLACE(SYSDATETIME(),'-',''),' ',''),':',''),'.','')
       + CAST(ABS(CAST(CAST(NewID() as BINARY(16)) as BIGINT)) as VARCHAR(40)) + '.txt';

That script will produce an absolutely unique, but precisely timed file name for you like this:
"MyFile_2019100809405568226626782079553600129740.txt"

If you wish, you have an ability to play around and insert underscores as dividers between date and time, seconds and milliseconds, time stamp and a random number. For instance you can do something like this: "MyFile_20191008_094601_4511373_6188309678908101054.txt".

SELECT 'MyFile_'
       + REPLACE(REPLACE(REPLACE(REPLACE(SYSDATETIME(),'-',''),' ','_'),':',''),'.','_')
       + '_' + CAST(ABS(CAST(CAST(NewID() as BINARY(16)) as BIGINT)) as VARCHAR(40))
       + '.txt';


No comments:

Post a Comment