Link to home
Start Free TrialLog in
Avatar of Mike Broderick
Mike BroderickFlag for United States of America

asked on

SQL decimal field containing date YYMMDD, add century for select's where() and order by

I have a C# program accessing an SQL table with a decimal field that contains dates in YYMMDD format. I want to select rows based on a date range (year 85 or later for example).  How can I add a century to the field or create another field so that, for example, I can select only certain years (85 - 12) and 990101 precedes 010101 in the results?
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

>SQL table with a decimal field that contains dates in YYMMDD format.
Give us a 'for example' of a decimal field value that contains a date in YYMMDD format.

In general T-SQL has the CONVERT function where if you scroll down it shows dates, note the 'with century' column.   Also check out PaulMaxwell's EE article SQL Server Date Styles (formats) using CONVERT() for a wompload of T-SQL date conversion functions.

Also adding C# zone to this question.
Avatar of Brian Custer
Brian Custer

First, I wouldn't use a decimal data type to store dates.  If you need them in a numeric format I would use an integer data type because it is smaller (only 4 bytes) and in some cases easier to work with than a decimal since a decimal isn't a discrete number.  Second, if you want specific ages then I would create a column that has an age field that calculates the age of a person if they were born on that specific date.
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sounds like BAD design of the database.  Store dates in date fields not as integer values in tables - then it would be much easier to manipulate them later.
Avatar of Mike Broderick

ASKER

Excellent. I think you meant to say ...ELSE 19000000 ... It works perfectly.  Below is the code I tested in SQL Server Mgt Studio.

Thanks.

WITH TEMP_W_COMACT as (Select *, CASE WHEN MDATE / 10000 < 50 THEN 20000000 ELSE 19000000 END + MDATE AS MDATEYMD FROM [AS400].[dbo].[W_COMACT])
SELECT *
  FROM TEMP_W_COMACT
  where (MMTRNO =15 and mflag = ' ')
  order by MMTRNO, mflag, mdate
Yeah, sorry, I really thought I did post 19000000 but you got it anyway, nice!