Reputation: 31
My table name as tbl_event
Event_ExpiryDate
, Event_Date
fields data type is varchar, I have using the following query for getting data from the table:
select * from tbl_event
WHERE
LEFT (CONVERT(VARCHAR,Event_ExpiryDate,103),12)>= LEFT(CONVERT(varchar,GetDate(),103),12) and
LEFT (CONVERT(VARCHAR,Event_Date,103),12)<= LEFT(CONVERT(varchar,GetDate(),103),12)
but I am getting a result like this
1 data to be missing. Why? this issue only on some month's date only. Months are 2,4,8,12
Upvotes: 0
Views: 55
Reputation: 95949
The real problem here is your data, and that you're using the wrong data type. Fix the data type, fix the problem.
You can fix that by firstly changing your varchar
representation of a date to an unambiguous Date format, yyyyMMdd
(This assumes your dates are in the format dd/MM/yyyy
):
UPDATE dbo.tbl_event
SET Event_Date = CONVERT(varchar(8),CONVERT(date,Event_Date,103),112),
Created_Date = CONVERT(varchar(8),CONVERT(date,Created_Date,103),112),
Event_ExpiryDate = CONVERT(varchar(8),CONVERT(date,Event_ExpiryDate,103),112);
Then you can ALTER
the table to fix your data types:
ALTER TABLE dbo.tbl_event ALTER COLUMN Event_Date date NULL; --Use NOT NULL if not NULLable
ALTER TABLE dbo.tbl_event ALTER COLUMN Created_Date date NULL; --Use NOT NULL if not NULLable
ALTER TABLE dbo.tbl_event ALTER COLUMN Event_ExpiryDate date NULL; --Use NOT NULL if not NULLable
Note: If any of your dates have bad values, for example '31/04/2019'
, the above will fail. You can get around this by changing the CONVERT
functions to TRY_CONVERT
, however any values that fail to convert will have the value NULL
. If your columns have the NOT NULL
property you will need to ensure you handle that too. If you do have bad values in your table, I strongly suggest taking a backup, or copy of the database/table first, so that you have a historical copy. (Of course, does a date like '31/04/2019'
or '12/13/2018'
have any meaning anyway?)
Upvotes: 1
Reputation: 50173
You can use only convert()
:
where convert(date, Event_ExpiryDate, 103) >= convert(date, getdate()) and
convert(date, Event_Date, 103) <= convert(date, getdate());
However, storing varchar
date is really bad idea. It will lead you lots of in trouble.
Upvotes: 0