Date format on query different from date format in result - sql

I wrote a SQL query to have the results from 2016 Apr 01 to 2016 May 01.
When I wrote:
where a.DateIntervention >= '2016-04-01'
and a.DateIntervention < '2016-05-01'
I obtain the results from 2016 Jan 04 00:00:00.000, so it is reading my dates as ydm, although the results show the date format as ymd (2016-01-04 00:00:00.000)
And when I ask the system about the date format it tells me it is dmy (!)
How to change this setting so that I can write my queries like ymd and continue obtaining the results like ymd?

In SQL Server, you don't need to. If you drop the hyphens then the strings will be interpreted using YYYYMMDD:
where a.DateIntervention >= '20160401' and a.DateIntervention < '20160501'
I prefer the hyphens because they are more readable, accepted in most databases, and generally work in SQL Server. There are particular settings where they don't work, but 'YYYYMMDD' is always interpreted as a date.
I should add, you can throw in a cast()/convert() if you like:
where a.DateIntervention >= cast('20160401' as date) and
a.DateIntervention < cast('20160501' as date)

There's no built-in way for the query to realize "I was supplied a YMD date, I should output dates as YMD too.".
In theory you could call SET DATEFORMAT ymd, but I mislike that because it might affect something farther down the line you don't know about.
If you want an explicit formatting/parsing style during conversion (which is almost always a good idea), you need to explicitly convert it, and supply the style:
-- 126 is hyphenated, but has extra parts if something other than date is used
CONVERT(DATE, '2017-07-28', 126)
Of course, the best option is to supply the parameter as an actual DATE type, and get output the same way, which saves you from converting back and forth to a string type, and avoids the formatting problem. This may not be available in a cases, however (like ad hoc queries).

Related

How to get the week start in this format '07-Feb-22' in SQL server

Hi there please help me .
I'm using this code
Weekstart = DATEDD(Wk, DATEDIFF(d,0,CONVERT(DATE, GETDATE(),103)) / 7,0)
This above query is given me the output in this format '2022-02-07 00:00:00.000' however I want the date in this format '07-Feb-22'
Some things to avoid:
Shorthand like Wk and d - this isn't code golf
Magic dates like 0 - again, not code golf
Style 103 doesn't belong here at all, that is when you are taking a string in a regional format (which you also should avoid), not when converting a datetime to a date
Lots more things to avoid here: Dating Responsibly
I would do it this way. Use a base date that you know falls on the same weekday that you consider the start of the week:
DECLARE #base date = '20180101';
SELECT Weekstart = REPLACE(CONVERT(char(9),
DATEADD(WEEK, DATEDIFF(DAY, #base, GETDATE())/7, #base), 6),' ','-');
The only magic / shorthand in here is the style number, 6, which is a very specific way to coerce a date/time into a specific format (discover them all here). Some will suggest the built-in FORMAT() function, which matches capability in other languages like C#, but I suggest avoiding it. Not only is it not available in flavors of SQL Server that don't support CLR or x64 (like Azure SQL Edge), the overhead is substantial.

How to correct this delete query

I need to do a select query like this:
select *
from faults
where insertdate < DATEADD(DAY, -30, sessiondate)
The query should be correct but I get this error:
Conversion failed when converting date and/or time from character string.
Since, sessiondate contains a date but as string and not in date format.
Is there a way to do this query with a string instead of a date type?
The error seems pretty clear. insertdate and/or sessiondate are stored as strings. You should fix the data.
SQL Server has three ways to convert such values:
Implicitly by putting the strings in a place where date/times are expected.
Explicitly using CAST()/CONVERT().
Explicitly and flexibly using PARSE().
You need to figure out what your format is. They you can convert it. You've provided no information, but a typical method would be:
where insertdate < DATEADD(DAY, -30, TRY_CONVERT(date, sessiondate, <date style here>))
Usually the formats available with CONVERT() are sufficient (see here). Sometimes, you may need to use TRY_PARSE().
EDIT:
To support timestamps, then you need to convert to datetime2:
try_convert(datetime2, '2019-07-08T09:17:19+02:00')
You should be comparison to a value with a timestamp.

Conversion of Date for direct sql query in OBIEE using presentation variable

I am trying to achieve this use case: when there is no date picked I want to show all the results but when I have date picked I want it to filter.
fyi:
the date getting picked are YYYY-MM-DD HH24:MI:SS in the presentation variable, but the date format in my query is dd-mon-yy. So when I need to convert the value of the presntation varible to dd-mon-yy.
OBIEE doesnt like when I play around with the values, and the BI server does not let me look at the error message.
I dont have access to change the format on the server level so my only option is to use formulas
I'm new to presentation variable.
ALso I need you'll to remember if there is no date selected in the prompt I would want all values returned
code:
and
( ( main_query.schd_compare >= (#{pv_task_sch_st_date}['#']{NVL(main_query.schd_compare,'None')})
)
AND (
main_query.schd_compare <= (#{pv_task_sch_end_date}['#']{NVL(main_query.schd_compare,'None')})
) )
I need help with syntax for obiee
Inside the database, it doesn't care if a date is "DD Mon YY" or "YYYY-MM-DD HH24:MI:SS". Those are just formatting, and the actual bit value of that date will be the same. So if both "dates" are actually a date datatype, then you can just use something like:
....
AND (
(
main_query.schd_compare >= NVL(pv_task_sch_st_date,main_query.schd_compare)
)
AND
(
main_query.schd_compare <= NVL(pv_task_sch_end_date,main_query.schd_compare)
)
)
That's if your pv_task_sch_???_date are passed as NULL values when not selected. Oracle does seem to treat empty strings and NULL the same in comparisons like this, but you it can be hard to debug if you get in the habit of relying on NULL and '' being the same.
As for your query, my guess is that your pv_task... values are actually being passed to your query as a some sort of string. If that's the case, then you'll need to put a TO_DATE() around your pv_task... variables.
Take a look at https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=2066b2005a22769e785815f6b03750a1. I stepped through a few examples of how your dates can be treated.
I did say earlier that the database doesn't care when format your date is in. And it is stored the same, no matter the format. But when you're using TO_DATE() or other similar functions, Oracle wants you to specify the proper mask of your data. If you send "01 Jan 99" to TO_DATE(), Oracle needs to know how to interpret that value. So you tell it that the string is "DD Mon YY". You can't do TO_DATE('2018-09-10','YYYY-MM-DD HH24:MI:SS') because my input doesn't have a time component. ( I would also caution about using 2-digit years. )
By the way, I hate dates. And dealing with dates in Oracle reinforces that hatred.

Format date as yyyy-mm-dd hh:mm:ss.000

I have this date: 7/19/2013
I want to format it as the following:
2013-07-19 00:00:00.000
I tried this:
select convert(varchar(10),'7/19/2013',120)
But it is giving me the same result!
You need to tell SQL Server it's a date; otherwise, it just sees a string, and ignores the style number since it's not relevant for a string. As Steve Kass pointed out, the code is only truly portable if you protect the incoming string from incorrect regional- or language-based translations (such as d/m/y - which could lead to an error or, even worse, the wrong data). I've updated the code to interpret the string as m/d/y regardless of locale, but if you're on SQL Server 2012 you could also use PARSE() as in his example (or TRY_PARSE() if you want to essentially ignore invalid dates).
And if you want the time attached including milliseconds, you need to allow more than 10 characters, and a style that supports milliseconds.
SELECT CONVERT(CHAR(23),CONVERT(DATETIME,'7/19/2013',101),121);
Result:
2013-07-19 00:00:00.000
If you don't care about milliseconds, you can use style 120 instead:
SELECT CONVERT(CHAR(19),CONVERT(DATETIME,'7/19/2013',101),120);
And if you don't care about seconds, you can truncate earlier:
SELECT CONVERT(CHAR(16),CONVERT(DATETIME,'7/19/2013',101),120);
Note that Aaron's solution will fail if the server is localized to a language with DMY as the date format. This is because the inner CONVERT in Aaron's example will incorporate the server locale, which may not be what you expect.
To make this bulletproof (assuming the source of the string doesn't automatically re-localize the format), convert the string with PARSE (requires SQL Server 2012 or later).
SET LANGUAGE English
SELECT CONVERT(CHAR(23),TRY_CONVERT(DATETIME,'7/19/2013'),121);
SELECT CONVERT(CHAR(23),PARSE('7/19/2013' AS DATETIME USING 'en-US'),121);
SET LANGUAGE Français
SELECT CONVERT(CHAR(23),TRY_CONVERT(DATETIME,'7/19/2013'),121);
SELECT CONVERT(CHAR(23),PARSE('7/19/2013' AS DATETIME USING 'en-US'),121);
Adding to your query, you can just add the Zeros/the characters as you want :)...
SELECT CONVERT(VARCHAR (10),'7/19/2013',120) + ' 00:00:00.000'
Result:
7/19/2013 00:00:00.000

SQL Server date format MM/DD/YYYY

How do I check if a date string is in the MM/DD/YYYY format in SQL Server?
SET DATEFORMAT MDY;
SELECT CASE WHEN ISDATE(#string) = 1
AND #string LIKE '[0-1][0-9]/[0-3][0-9]/[1-2][0-9][0-9][0-9]'
THEN 1 ELSE 0 END;
If the result is 1, it's a valid date, but there's no guarantee that it's the date the user meant. If they enter:
06/07/2012
There is no way to know if they meant June 7 or July 6. Your best bet is to make users pick dates from drop-downs or calendar controls, which allows you to control the format and avoid any needless interpretation. Your application layer can use strongly typed variables / parameters and insert into properly typed columns.
If you're after the SQL Server dateformat to see whether it's MDY then use:
dbcc useroptions
And have a look at the dateformat Set Option
you convert date to datestring in this format MM/DD/YYYY using CONVERT function
select convert(varchar(10),getdate(),101)
The output will be as of Sept 8th 2012
09/08/2012
There is no need to validate, other then checking the date field is null or not
You have to do it outside the database. A database stores datetime internally in its own format. I dont think you can read what format the date is stored in. You can read it which ever way you like, for example dd/mm/yyyy or yyyy/mm/dd etc.
What you can do is check this value outside the database for any date field. You can use regular expression for that. But that will be outside the database.