We are using the below SQL fragment in the where condition of a SQL Server stored procedure:
convert(varchar, CreateDate, 101) <= convert(varchar, GETDATE() - #numberofdays, 101)
Datatype of CreateDate is datetime
Datatype of #numberofdays is int
Can you please confirm if this condition will work fine or it can fail in any scenario as the datatypes are converted to varchar before comparing dates?
CreateDate <= DATEADD(day,-1*#numberofdays,GETDATE())
Yes it will work.
See below queries
declare #numberofdays int
set #numberofdays=3
declare #CreateDate datetime
set #CreateDate= '2017-03-20'
select
convert(varchar,#CreateDate, 101) as date1,
convert(varchar,GETDATE()- #numberofdays,101) as date2
output from them is
date1 date2
03/20/2017 10/08/2017
Which is in same format and will work
working demo
Related
Here is my stored procedure which accepts two date parameters, one for start date and second for end date. It gets a bunch of different data from joined tables:
#FromDate varchar(50),
#ToDate varchar (50)
SELECT DISTINCT
dbo.DefectInspection.DefectInspection_Id,
CONVERT(varchar(50), CAST(dbo.DefectInspection.DefectInspection_CreatedDate AS date), 34) AS CreatedDate
FROM
(bunch of tables)
WHERE
CAST(DefectInspection.DefectInspection_CreatedDate AS date)
BETWEEN CAST( #FromDate AS Date) AND CAST(#ToDate AS Date)
The issue is it will only return date if I input my dates as MM-DD-YYYY instead of the days firsts. This is an issue because the date style sent from client side is always DD-MM-YYYY
Using desired input: no data returedn
Using month format - data returned
When using SQL (and other languages) its best to use an unambiguous format such as yyyy-mm-dd
Also consider using the DATE type instead of VARCHAR
#FromDate DATE(50),
#ToDate DATE(50)
Though using the wrong datatypes is terrible, sometimes we all have to deal with issues which cannot be changed easily.
You can use:
DECLARE #fromDate AS varchar(50);
DECLARE #toDate AS varchar(50);
DECLARE #from AS date;
DECLARE #until AS date;
SET #fromDate = '09-01-2023';
SET #toDate = '10-01-2023';
SET #from = TRY_CONVERT(date, #fromDate, 105);
SET #until = TRY_CONVERT(date, #toDate, 105);
IF #from IS NULL OR #until IS NULL
THROW 51000, 'Parameter is not a valid date ..', 0;
ELSE BEGIN
SELECT DISTINCT
...
FROM
(bunch of tables)
WHERE TRY_CONVERT(date, DefectInspection.DefectInspection_CreatedDate, 110) BETWEEN #from AND #until;
END;
TRY_CONVERT returns NULL if the parsing fails.
The 3rd parameter (style) 105 means format "dd-mm-yyyy" like you use it, 110 means "mm-dd-yyyy".
I have a varchar column where some values are in mm/dd/yyyy format and some are in yyyymmdd.
I want to convert all mm/dd/yyyy dates into the yyyymmdd format. What is the best way to do this? Thanks
Table is Employees and column is DOB
Assuming your "date" column is not actually a date.
Select convert(varchar(8),cast('12/24/2016' as date),112)
or
Select format(cast('12/24/2016' as date),'yyyyMMdd')
Returns
20161224
DECLARE #v DATE= '3/15/2013'
SELECT CONVERT(VARCHAR(10), #v, 112)
you can convert any date format or date time format to YYYYMMDD with no delimiters
You can do as follows:
Select Format(test.Time, 'yyyyMMdd')
From TableTest test
try this....
SELECT FORMAT(CAST(DOB AS DATE),'yyyyMMdd') FROM Employees;
Select CONVERT(VARCHAR(8), GETDATE(), 112)
Tested in SQL Server 2012
https://www.w3schools.com/sql/func_sqlserver_convert.asp
In SQL Server, you can do:
select coalesce(format(try_convert(date, col, 112), 'yyyyMMdd'), col)
This attempts the conversion, keeping the previous value if available.
Note: I hope you learned a lesson about storing dates as dates and not strings.
SELECT YEAR(getdate()) * 10000 + MONTH(getdate()) * 100 + DAY(getdate())
mm/dd/yyyy corresponds to U.S. standard so if you convert to date using 101 value and then to varchar using 112 for ISO date get the expected result.
declare #table table (date_value varchar(10))
insert into #table values ('03/30/2022'),('20220330')
select date_value
--converted to varchar
,case
--mm/dd/yyyy pattern
when patindex('[0,1][0-9]/[0-3][0-9]/[0-9][0-9][0-9][0-9]',date_value)>0 then convert(varchar(10),convert(date,date_value,101),112)
else date_value end date_value_new
--converted to date
,case
when patindex('[0,1][0-9]/[0-3][0-9]/[0-9][0-9][0-9][0-9]',date_value)>0 then convert(date,date_value,101)
else convert(date,date_value,112) end date_value_date
from #table
SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM table;
//converts any date format to YYYY-MM-DD
I have a table with two datetime columns and I'm trying to convert them to an iso string format using the following query:
select
CONVERT(VARCHAR(23), date1, 126) as date1,
CONVERT(VARCHAR(23), date2, 126) as date2
from
some_table
But I'm getting two different results, one with milliseconds and one without
date1 date2
2015-03-11T05:16:04.663 2015-03-11T05:15:43
I've looked at the create table script and they are both defined as datetime. I have no clue how the data is being inserted.
How can I get both columns to return with milliseconds ?
SQL Server "helpfully" will trim the milliseconds portion if it's entirely 0. If you need the 0 milliseconds included (I can't imagine what you're doing where you need .000 to be included) then you'll have to detect the trimming and re-add them:
;With Converted as (
--Your existing query. For this example, I'm just using one date:
select CONVERT(varchar(23),CONVERT(datetime,'2015-03-01T05:15:43.000'),126) as date2
)
select
CASE
WHEN LEN(date2) = 19 THEN date2 + '.000'
ELSE date2
END as date2
from Converted
(And, again if for some bizarre reason you really need the end result to be a varchar(23) rather than a varchar(27) you'll have to add another CONVERT that wraps the CASE expression because the system's not smart enough to realise that any value that the CASE returns could always fit in a varchar(23))
It is becouse the second date has 0 ms.
CREATE TABLE #Test ( date1 datetime, date2 datetime)
INSERT INTO #Test VALUES ('2015-03-11 05:16:04.663','2015-03-11 05:15:43' )
INSERT INTO #Test VALUES ('2015-03-11 05:16:04','2015-03-11 05:15:43.55' )
select
CONVERT(VARCHAR(23), date1, 126) as date1,
CONVERT(VARCHAR(23), date2, 126) as date2
from
#Test
Check this example.
How can I create a method to subtract two dates and this is equal to in real date as format datetime2(7) in sql server 2008.
For example ,I create this method:
Delete from TblMessage
Where MDateTime<((SELECT TOP (1)MDateTime FROM TblMessage ORDER BY MDateTime DESC)- ('2013-10-04 16:47:56.0000000'))
but it is not working .I want to result of subtract two date like this:
MDateTime1:2013-10-05 16:47:56.0000000
MDateTime2:2013-09-04 16:47:56.0000000
Result:2013-01-01 00:00:00.0000000
Result=MDateTime1-MDateTime2
How can I do this. Thanks...
Perhaps you are looking for this?
select DATEADD( day, datediff(day,GETDATE(), getdate() - 10), GETDATE() ) ;
DATEDIFF(dayofyear,MDateTime1,MDateTime2) AS Result
http://msdn.microsoft.com/en-us/library/ms189794.aspx
DECLARE
#DATE1 DATETIME = '2013-10-05 16:47:56.000',
#DATE2 DATETIME = '2013-09-04 17:37:42.000',
#DATEDIFF AS INT,
#BASEDATE DATETIME;
-- USE WHAT EVER DATE YOU WISH TO BE YOUR BASE DATE
SET #BASEDATE = '1/1/1900';
SET #DATEDIFF = DATEDIFF(SECOND, #DATE2, #DATE1);
SELECT #DATE1,#DATE2,#DATEDIFF, DATEADD(SECOND,#DATEDIFF,#BASEDATE)
Thus a scalar function could be created like this...
CREATE FUNCTION dbo.sf_GetMeasureDate
(
#EndDate DATETIME,
#StartDate DATETIME,
#BaseDate DATETIME
)
RETURNS DATETIME
AS
BEGIN
DECLARE #DATEDIFF AS INT
SET #DATEDIFF = DATEDIFF(SECOND, #StartDate, #EndDate);
Return DATEADD(SECOND,#DATEDIFF,#BASEDATE)
END
GO
Then within you regular SELECT statement you can call the function as such.
SELECT dbo.sf_GetMeasureDate('2013-10-05 16:47:56.000','2013-09-04 17:37:42.000','1/1/1900')
or within an existing query:
SELECT dbo.sf_GetMeasureDate([fld1],[fld2],'1/1/1900')
I would like to compare datetime datatype, like "20/12/2011 00:00:00", with compound string date format (I mean that it is composed of string of date, string of month and string of year).
For example, coloumn entime is datatime datatype which is stored "20/12/2011 00:00:00" data and other three column(date,month,year respectively) are string. so I want to compare between entime column with the date,month and year composed together, How I can write SQL Command to suppurt the above requirement ?
Hope you can help me ?
The best option is to convert the datetime to string and then make the needed comparisons.
You can see here how to make the conversion.
There is also the DATEPART function as an alternative.
SELECT *
FROM DateTable
WHERE
DATEPART(YEAR, [DATECOLUMN]) = #YearString
AND DATEPART(MONTH, [DATECOLUMN]) = #MonthString
AND DATEPART(DAY, [DATECOLUMN]) = #DayString
You can go below way, would you please try it out, thanks
SET DATEFORMAT DMY
SELECT CAST(CONVERT(VARCHAR(15), GETDATE(), 105) AS DATETIME)
SELECT CAST(('20'+'-'+'12'+'-'+'2011') AS DATETIME)
As an example:
SET DATEFORMAT DMY
SELECT CAST(CONVERT(VARCHAR(15), yourDateColumn, 105) AS DATETIME) FROM TableName
SELECT CAST((dayColumn+'-'+monthColumn+'-'+yearColumn) AS DATETIME)
FROM anotherTable
Finally the comparison:
SELECT t1.* FROM tableName t1, anotherTable t2
WHERE CAST(CONVERT(VARCHAR(15), t1.DateColumnName, 105) AS DATETIME)
= CAST((t2.dayColumn+'-'+t2.monthColumn+'-'+t2.yearColumn) AS DATETIME)
Is this your requirement ?
DECLARE #tblTemp TABLE
(
DAY VARCHAR(10)
,Month VARCHAR(10)
,Year VARCHAR(10)
)
DECLARE #dtDateTime VARCHAR(10) = '20/12/2011 00:00:00'
INSERT INTO #tblTemp VALUES
('01','01','2011'),
('01','02','2011'),
('01','03','2011'),
('01','04','2012');
select * from #tblTemp where CONVERT(DATE,Year +Month+DAY ,103) < CONVERT(DATE,#dtDateTime,103)