Datetime Format in Sql server - sql-server-2005

I have field in sql table DateIn, in table date exists like '01/04/2012 00:00:00'. when i run query on query analyzer DateIn comes like '2012-04-01 00:00:00.000' i am passing date from text box like 'dd/mm/yyyy' format but not working. I have function where i am passing date variable Dim StrDate as DateTime from text box to query. Please guide me.

If the column is datetime please stop thinking it is stored in some format like mm/dd/yyyy or dd/mm/yyyy. Date/time values are stored internally without any of this regional formatting applied - this is just the way Management Studio is presenting it to you. You should write queries using yyyymmdd for date literals, like:
SELECT <cols>
FROM dbo.table
WHERE DateIn >= '20120601'
AND DateIn < '20120626';
Anything else is prone to not work if a different user executes, if the regional settings on the machine change, or if you move your code to another server. Please see:
What do BETWEEN and the devil have in common?
Bad habits to kick : mis-handling date / range queries
Also be sure you are using string delimiters. If you say:
WHERE DateIn > 01/06/2012
That is the same as:
WHERE DateIn > (1 divided by 6 divided by 2012)
Which yields, due to integer math:
WHERE DateIn > 0
In SQL Server, 0 as a date/time is '1900-01-01' - therefore this clause will return all non-NULL rows.

Related

SQL, casting a string to date so I can use GETDATE()

I am using SQL Server Management Studio 18 against SQL Server 2016. I have some material that are in batches and those batches have expiration dates that are held as strings, but are basically in the format of 'yearmonthday', e.g. '20210312' for March 3rd, 2021. My goal is to only see material that is expiring after the current date. Whenever I try to CAST the expiration date column AS DATE within the WHERE clause, I get this error:
Conversion failed when converting date and/or time from character string
(or something similar when trying different methods).
So, right now my code looks like this:
SELECT MaterialColumn, BatchColumn, CAST(ExpirationColumn AS DATE)
FROM StockTable
WHERE CAST(ExpirationColumn AS DATE) > CAST(GETDATE() AS DATE)
If I don't do the WHERE clause, I know I can CAST the ExpirationColumn as DATE without issue, but when it's in the WHERE clause, I run into that error. Is there any way I can filter to see only the dates that I want?
You can use try_cast() instead:
SELECT MaterialColumn, BatchColumn, CAST(ExpirationColumn AS DATE)
FROM StockTable
WHERE TRY_CAST(ExpirationColumn AS DATE) > CAST(GETDATE() AS DATE);
You can also find the bad values:
SELECT ExpirationColumn
FROM StockTable
WHERE TRY_CAST(ExpirationColumn AS DATE) IS NULL AND ExpirationColumn IS NOT NULL;
It sounds like you might need to fix some data values.
Honestly, if your dates are all stored in the format yyyyMMdd then there's no need to convert. Instead use a varchar parameter, as (at least) a varchar in the format yyyyMMdd had the same sort order as a date.
As a result you just convert GETDATE to the right format:
WHERE Expiration > CONVERT(varchar(8), GETDATE(), 112)
Of course, this doesn't change my statements in the comment; fix your design, don't stores dates as a string but as a date (and time) data type.

MVC 5 and SQL Server date filter issue

I have datetime values in my database table like 05/05/2015 23:00:00. I am putting date filter in my query and try to fetch all the data of 05/05/2015 like this:
select *
from table
where date <= "05/05/2015".
It's not returning the records which have value 05/05/2015 23:00:00 in database.
Please suggest the way..
Using this where clause here
where date <= "05/05/2015"
means: return every row with a date before 05/05/2015 (including the ones with 05/05/2015 00:00:00 - but nothing more).
If you want to get all records for that day, too, you should use
where date < '20150506'
I'd also recommend to use the ISO-8601 date format yyyyMMdd to prevent any regional settings from interfering with your strings representing dates.
And I would also recommend to use something more expressive than just date for your column name - in SQL Server 2008 and newer, DATE is a reserved T-SQL keyword, too - use something like HireDate, SaleDate or something that tells you want kind of date this is

Convert Data from yyyy-dd-mm to mm/dd/yyyy Issue

I have a column in my table with Dates in the format yyyy-mm-dd I want to convert all the dates in that column to the format mm/dd/yyyy
I am using the below query
UPDATE Test.dbo.Status
SET DateIn = CONVERT(DATE,DateIn ,101)
The DateIn column is defined as Date in my table (DateIn DATE NULL)
The query does no change to the data. am I doing some thing wrong here?
You can change the default format in which SQL Server displays a date, but you can't alter the way a DATE value is stored via CONVERT(). You can format a date however you want if you store it as a string, but you lose functionality when you do that and it's not advisable. If you are hell-bent on storing a formatted version, you might want to create a new VARCHAR() field so you can preserve your DATE version.
You're better off formatting the date at the application level.
The reason your query does nothing is that the actual DATE values are equivalent. Notice when you take any valid date format and CAST() it as DATE the resulting format is the same regardless of the input:
SELECT CAST('20040510' AS DATE)
SELECT CAST('2004-05-10' AS DATE)
SELECT CAST('May 10, 2004' AS DATE)
All return: 2004-05-10 on my instance of SQL Server.

Datetime interpretation issue

I have the following data:
StartDate FinishDate Details
09/10/2013 11/10/2013 xxx
14/10/2013 13/10/2014 Taking a year off
Whilst editing this data I which to check the date ranges do not overlap.
I am running an SQL query from access via ado to do this; I am putting the dates entered into database format (ie 'mm/dd/yyyy'); This is the query I've got:
SELECT Count(*)
FROM MarkerAbsence
WHERE PerID = 718 AND
('10/09/2013' BETWEEN StartDate AND FinishDate OR
'10/11/2013' BETWEEN StartDate AND FinishDate)
If the data is valid, it should return zero records; however it doesnt it returns 1 (being the second listed record above) and therefore seems to be interpreting '10/11/2013' as dd/mm/yyyy instead of mm/dd/yyyy.
Yet if I do this in SMO:
DECLARE #datevar datetime2 = '31/12/2008';
SELECT #datevar;
I get:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
While
DECLARE #datevar datetime2 = '12/31/2008';
SELECT #datevar;
returns
2008-12-31 00:00:00.0000000
So why am I having this problem and how do I fix it?
If you're running a query using MS Access, you need to delimit dates with # symbols, i.e.: #12/31/2008#. If this won't work for whatever reason, it is best to use string dates in the 'yyyy-mm-dd' format, as it will be recognized and is unambiguous.
You're probably getting this problem as MS is a US company, and the US uses mm/dd/yyyy format, so MS has defaulted much of their older software to treat dates as being in this format if at all possible, whereas you're probably in a country that uses - and have your PC's locality set to use - dd/mm/yyy format. Since not all of MS' software follows this rule, you have this problem.
The solution is to use a string date format that is unambiguous, such as: yyyy-mm-dd, mmm/dd/yyyy, or dd/mmm/yyyy (where mmm returns a three-letter month such as Dec).
You are using dd/mm/yyyy formats for your date strings. By default, without an explicit conversion, SQL is expecting date strings in the mm/dd/yyyy or yyyy-mm-dd format. So either change your strings to match one of these formats or do this:
SELECT Count(*)
FROM MarkerAbsence
WHERE PerID = 718 AND
(CONVERT(DATETIME, '10/09/2013', 103) BETWEEN StartDate AND FinishDate OR
CONVERT(DATETIME, '10/11/2013', 103) BETWEEN StartDate AND FinishDate)

Change date format in SQL for ASP

I have the following code:
"SELECT top 1 * FROM CensusFacility_Records WHERE Division_Program = 'Division 1' AND JMS_UpdateDateTime = '" & date & "'"
The date format in column JMS_UpdateDateTime is:
8/22/2013 12:00:07 AM
How can I make sure that my "date" in the query is converted to the correct time format?
My date variable in my SQL query is a real/date time. I would like for it to match the format within the JMS_UpdateDateTime field.
If your database table is small enough, you can cast the value to an actual datetime inside your query, and pass the value in as a datetime parameter, so you're comparing dates instead of comparing strings.
If your table has a decent amount of records, don't do this, because it will be a performance hog.
SELECT top 1 *
FROM CensusFacility_Records
WHERE Division_Program = 'Division 1'
AND cast(JMS_UpdateDateTime as datetime) = #dateParam
I believe SQL Server will be able to read the string that's in your database and automatically cast it properly, assuming your server settings are standard.
But in any case, use parameterized SQL instead of passing in a string like you've got.
The format of your SQL DateTime is actually a bit of a red herring here - it can be displayed in any way the front end (e.g. Management Studio) chooses. The important thing here is that your date variable is in an unambiguous format. With this in mind I'd recommend using the ISO 8601 date/time format, e.g. date.ToString("o") (assuming date is a DateTime).