سؤال

I need to generate unique key to store in sql . suppose we have date "2013/07/25" for today how we can generate unique 4 digit key based on everyday date ?

هل كانت مفيدة؟

المحلول

Using a 4 digit key you could represent every day from a predefined base and start counting from that base.

For example (using 1/1/2000 as base) :

DateTime dt = new DateTime(2000,1,1);
DateTime dtEnd = dt.AddDays(9999);
Console.WriteLine("Maximum date available:" + dtEnd.ToShortDateString());

dtEnd = new DateTime(2013,7,25);
TimeSpan ts = dtEnd - dt;
Console.WriteLine("Today Day number from base: " + ts.TotalDays);

Of course you could easily fine-tune your range changing the base date and setting it to a different value. However, once set and starting to save data in db it will be not easy to change the base value. I would recommend to avoid this pattern and choose a more flexible way to store unique keys in a table, but, of course, I don't know your requirements.

نصائح أخرى

I would take the days since some date, such as '2010-01-01'. This will give you up to 10,000 days, which is a bit under 30 years.

Here is a method for doing so:

select right('0000'+cast(datediff(day, '2010-01-01', @YOURDATE) as varchar(4)), 4)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top