SQL Query datetime issue - sql-server

I have a query on SQL Server that's finding wrong results based on a datetime condition.
SET LANGUAGE Português
select distinct
CONVERT(varchar(10), DATENAME(MONTH, i9_parcelaBase.i9_data_vencimento)) + '/' + CONVERT(varchar(10),
DATENAME(YEAR,i9_parcelaBase.i9_data_vencimento)) AS Periodo,
i9_parcelaBase.i9_data_vencimento,
i9_parcelaBase.i9_data_limite_envio_nf,
i9_parcelaBase.i9_status_atual,
i9_processo_statusBase.i9_status,
i9_processo_statusBase.i9_name
--i9_nota_fiscalBase.i9_nota_fiscalid as ID
from i9_parcelaBase
left join i9_processo_statusBase
on i9_parcelaBase.i9_status_atual = i9_processo_statusBase.i9_processo_statusId
where i9_processo_statusBase.i9_entidade = 100000002
and i9_parcelaBase.i9_data_vencimento between CONVERT(varchar(10), year(getdate())-1) + '-' + CONVERT(varchar(10), month(getdate())+1) + '-1'
and CONVERT(varchar(10), year(getdate())) + '-' + CONVERT(varchar(10), month(getdate())) + '-1'
order by i9_data_vencimento asc
Basically, Month that's receiving data without '0' before (when necessary).
Sample:
Actual return: '2017-6-1'
Expected return '2017-06-01'
Can anyone help me to solve this problem?

By the look of your query, i9_data_vencimento is expected to end with just -1, not -01. You can cast the string into a date, then recast it back as a string as a way to format it:
select distinct
CONVERT(varchar(10), DATENAME(MONTH, i9_parcelaBase.i9_data_vencimento)) + '/' + CONVERT(varchar(10),
DATENAME(YEAR,i9_parcelaBase.i9_data_vencimento)) AS Periodo,
CONVERT( VARCHAR(10), CONVERT( DATETIME, i9_parcelaBase.i9_data_vencimento ), 120 ) AS i9_data_vencimento,
:
:
Also, considering that i9_data_vencimento is just a string, and assuming it always ends with '1' in the format 'yyyy-mm-1', you could use a LEFT function to strip off the last character and replace it with '01':
SELECT DISTINCT
:
LEFT(i9_parcelaBase.i9_data_vencimento, 8) + '01' AS i9_data_vencimento,
:

Related

I have a start_date and end_date. I want to get the list of dates in between GETDATE(). Can anyone help me pointing the mistake in my query

I am getting error in below query.
Query
;with CTE as
(select Dm.Category_id as Category_Label_id,Ca.Category_Name as Category_label_Name,
convert(datetime, convert(varchar,year(getdate())) + '/' + convert(varchar,MONTH(GETDATE())) + '/' + convert(varchar, day(d.Expiry_Date))) as Exp_date1
,DATEDIFF(day,getdate(), convert(varchar(10), convert(varchar,year(getdate())) + '/' + convert(varchar,MONTH(GETDATE())) + '/' + convert(varchar, day(d.Expiry_Date)))) as Days_remain
,convert(datetime, DATEADD(day,-Reminder_Days, convert(varchar(10), convert(varchar,year(getdate())) + '/' + convert(varchar,MONTH(GETDATE())) + '/' + convert(varchar, day(d.Expiry_Date))))) as Exp_date2
from documentalert d
inner join document dm on dm.doc_id=d.doc_id
inner join Category ca on ca.Category_id = dm.Category_id
inner join category_value c on c.doc_id= dm.doc_id
inner join dbo.Category_Key k on k.Category_Key_id= c.category_label_id
and c.Category_Label_id=4 -- expiry date
where d.alerttype='M'
and dm.user_id=427 and dm.is_active=1 )
select * from cte where getdate() between Exp_date2 and Exp_date1
Error
Msg 242, Level 16, State 3, Line 1 The conversion of a varchar data
type to a datetime data type resulted in an out-of-range value.
I suspect that you are getting that error as you are building dates by taking the year and month from GETDATE() and then appending the day from Expiry_Date.
If any of your Expiry_Date values have the day as 31, then that will not work in the month of September, which GETDATE() will return:
Run the below:
SELECT CONVERT(DATETIME,
CONVERT(VARCHAR, YEAR(GETDATE())) + '/' +
CONVERT(VARCHAR, MONTH(GETDATE())) + '/' +
CONVERT(VARCHAR, 31) -- Fails with 31
) AS Exp_date1;
Errors with:
Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Where as this one works:
SELECT CONVERT(DATETIME,
CONVERT(VARCHAR, YEAR(GETDATE())) + '/' +
CONVERT(VARCHAR, MONTH(GETDATE())) + '/' +
CONVERT(VARCHAR, 30) -- Works with 30
) AS Exp_date1;
You need to either consider days and month values in your logic or use the Expiry_Date in a better way. I'm not sure why you want to append any day value to the current year and month. If you want to filter values to the current month, use a where clause to check the value first.

Formatting the SQL query result based on a pattern

I have got a table that contains deferent type of date formats:
########
DateTime
########
10/05/2015
11/05/2015
1/5/2015
01/5/2014
Now my question is that How can I select all the rows based on this pattern \d{2}/\d{2}/\d{4} the format the result with this pattern \d{4}/\d{2}/\{2}?
The first one is dd/mm/yyyy and I would like the result be yyyy/mm/dd
Test Data
DECLARE #TABLE TABLE (Dates VARCHAR(20))
INSERT INTO #TABLE VALUES
('10/05/2015'),
('11/05/2015'),
('1/5/2015'),
('01/5/2014')
Query
The following query will convert all the values to proper sql server date data type.
SELECT CONVERT(DATE,
RIGHT('0000' + PARSENAME(REPLACE(Dates , '/','.'),1),4)
+ RIGHT('00' + PARSENAME(REPLACE(Dates , '/','.'),2),2)
+ RIGHT('00' + PARSENAME(REPLACE(Dates , '/','.'),3),2)
)
FROM #TABLE
Result
2015-05-10
2015-05-11
2015-05-01
2014-05-01
Once you have got the values in well-formatted sql server date type, you can extend the query to get the required output yyyy/mm/dd by doing the following:
SELECT CONVERT(VARCHAR(10),
CONVERT(DATE,
RIGHT('0000' + PARSENAME(REPLACE(Dates , '/','.'),1),4)
+ RIGHT('00' + PARSENAME(REPLACE(Dates , '/','.'),2),2)
+ RIGHT('00' + PARSENAME(REPLACE(Dates , '/','.'),3),2)
), 111)
FROM #TABLE
Result
2015/05/10
2015/05/11
2015/05/01
2014/05/01
In your case I you don't need to use regular expressions. A simple LIKE should suffice.
... WHERE DateTime LIKE "__/__/____" ...

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value exception

I was trying to concatenate the date and month with the Year and I need to check with the each record to find the financial year. When I execute the query it shows (The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.) error. Please help me to find the issue.
Code
set #SiteFileVal1='04-01'
set #SiteFileVal2='03-31'
set #SiteFileYear='2013'
SELECT bb.Amount
FROM Budget bb
JOIN Invoice i ON i.AccountId=bb.AccountId
WHERE bb.AccountId=i.AccountId
AND bb.Year=
(SELECT CASE WHEN (i.Date >= convert(datetime,#SiteFileVal1+'-'+convert(varchar(200),DATEPART(yyyy,i.Date)))
AND i.Date < convert(datetime,#SiteFileVal2+'-'+convert(varchar(200), DATEADD(yyyy,1,DATEPART(yyyy,i.Date))))) THEN year(#SiteFileYear) ELSE DATEADD(yyyy,-1,DATEPART(yyyy,i.Date)) END)
This part is incorrect:
DATEADD(yyyy,-1,DATEPART(yyyy,i.Date))
DATEADD expects a date passed in, and you are only passing in the year of a date -- DATEPART(yyyy, i.Date)
Using your code, I did:
select DATEADD(yyyy,-1,DATEPART(yyyy,'1/8/2007'));
The result? 1904-07-01 00:00:00.000
When I add a month/day back in, this is what I get:
select DATEADD(yyyy,-1, CAST(DATEPART(mm, '1/8/2007') as varchar) + '/' +
CAST(DATEPART(DD, '1/8/2007') as varchar) + '/' +
cast(DATEPART(yyyy,'1/8/2007') as varchar))
result: 2006-01-08 00:00:00.000
This is a lot of parsing for a query, but here's what you need, formatted to your column.
set #SiteFileVal1='04-01'
set #SiteFileVal2='03-31'
set #SiteFileYear='2013'
SELECT bb.Amount
FROM Budget bb
JOIN Invoice i ON i.AccountId=bb.AccountId
WHERE bb.AccountId=i.AccountId
AND bb.Year=
DatePart(yyyy,
(CASE WHEN (i.Date >= convert(datetime,#SiteFileVal1+'-'+convert(varchar(200),DATEPART(yyyy,i.Date)))
AND i.Date < convert(datetime,#SiteFileVal2+'-'+convert(varchar(200), DATEADD(yyyy,1,CAST(DATEPART(mm, i.Date) as varchar) + '/' +
CAST(DATEPART(DD, i.Date) as varchar) + '/' +
cast(DATEPART(yyyy,i.Date) as varchar)))))
THEN year(#SiteFileYear) ELSE
DATEADD(yyyy,-1, CAST(DATEPART(mm, i.Date) as varchar) + '/' +
CAST(DATEPART(DD, i.Date) as varchar) + '/' +
cast(DATEPART(yyyy,i.Date) as varchar)) END) )

Date format in dd/MM/yyyy hh:mm:ss

I need to convert datetime from 2012-07-29 10:53:33.010 to
29/07/2012 10:53:33.
I tried using
select CONVERT(varchar(20), GETDATE(), 131)
but its showing date according to Hijri calendar
11/09/1433 10:53:33:
Please help?
SELECT FORMAT(your_column_name,'dd/MM/yyyy hh:mm:ss') FROM your_table_name
Example-
SELECT FORMAT(GETDATE(),'dd/MM/yyyy hh:mm:ss')
This can be done as follows :
select CONVERT(VARCHAR(10), GETDATE(), 103) + ' ' + convert(VARCHAR(8), GETDATE(), 14)
Hope it helps
You could combine 2 formats:
3 dd/mm/yy (British/French)
8 hh:mm:ss
according to CONVERT() function, and using + operator:
SELECT CONVERT(varchar(10),GETDATE(),3) + ' ' + CONVERT(varchar(10),GETDATE(),8)
SELECT CONVERT(CHAR(10),GETDATE(),103) + ' ' + RIGHT(CONVERT(CHAR(26),GETDATE(),109),14)
The chapter on CAST and CONVERT on MSDN Books Online, you've missed the right answer by one line.... you can use style no. 121 (ODBC canonical (with milliseconds)) to get the result you're looking for:
SELECT CONVERT(VARCHAR(30), GETDATE(), 121)
This gives me the output of:
2012-04-14 21:44:03.793
Update: based on your updated question - of course this won't work - you're converting a string (this: '4/14/2012 2:44:01 PM' is just a string - it's NOT a datetime!) to a string......
You need to first convert the string you have to a DATETIME and THEN convert it back to a string!
Try this:
SELECT CONVERT(VARCHAR(30), CAST('4/14/2012 2:44:01 PM' AS DATETIME), 121)
Now you should get:
2012-04-14 14:44:01.000
All zeroes for the milliseconds, obviously, since your original values didn't include any ....
CREATE FUNCTION DBO.ConvertDateToVarchar
(
#DATE DATETIME
)
RETURNS VARCHAR(24)
BEGIN
RETURN (SELECT CONVERT(VARCHAR(19),#DATE, 121))
END
select DATE_FORMAT(NOW(),'%d/%m/%Y %h:%m:%s')
from dual
Try this wherever required, I have used this in JpaRepository in SpringBoot Project.
This will be varchar but should format as you need.
RIGHT('0' + LTRIM(DAY(d)), 2) + '/'
+ RIGHT('0' + LTRIM(MONTH(d)), 2) + '/'
+ LTRIM(YEAR(d)) + ' '
+ RIGHT('0' + LTRIM(DATEPART(HOUR, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(MINUTE, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(SECOND, d)), 2)
Where d is your datetime field or variable.

SQL Server datetime in 12AM/PM format without the millisecond

I would like to return my datetime data to the following format:
mm/dd/yy hh:mi:ssAM
According to the CONVERT documentation the closest thing that matches my spec is '131'
SELECT CONVERT(varchar, GETDATE(), 131)
but it doesn't exactly match my specifications.
EDIT:
I ended up doing the date formatting in my application layer which is PHP.
It was as simple as using the strtotime function to generate a UNIX timestamp and pass it into date funciton.
$date = date('m/d/Y g:ia', strtotime($row['date_time']));
Try this:
SELECT CONVERT(varchar, GETDATE(), 101) +
REPLACE(CONVERT(varchar, GETDATE(), 0),REPLACE(CONVERT(varchar, GETDATE(),107), ',',''),'')
This basically uses a method that's what you want for the DATE, then adds it to the time portion of what you want for the time only.
Although I feel that formatting should really be part of the UI, I guess if you really need it the below works - I'm sure there is an easier way to do this - but make this a UDF, and just use it in whatever query you want.
declare #date varchar(50)
set #date = (select CONVERT(varchar, GETDATE(), 131))
set #date = (select LEFT(#date,len(#date) - 6) + ' ' + RIGHT(#date,2))
set #date = right(#date,LEN(#date) - 11)
select CONVERT(varchar, GETDATE(), 101) + #date
You can assemble it from DATEPART()'s, and create a user defined function from it for easy re-use.
This is untested off the top of my head.. give it a shot:
CREATE FUNCTION fnSpecDate()
RETURNS VARCHAR(24)
AS
BEGIN
DECLARE #outData VARCHAR(24)
set #outData =
CONVERT(varchar,DATEPART(mm,GETDATE())) + "/"
+ CONVERT(varchar,DATEPART(dd,GETDATE())) + "/"
+ CONVERT(varchar,DATEPART(yy,GETDATE())) + " "
+ CASE WHEN DATEPART(hh,GETDATE()) > 12
THEN CONVERT(varchar,DATEPART(hh,GETDATE()) - 12)
WHEN DATEPART(hh,GETDATE()) = 0
THEN '12'
ELSE CONVERT(varchar,DATEPART(hh,GETDATE()))
END + ":"
+ CONVERT(varchar,DATEPART(mm,GETDATE())) + ":"
+ CONVERT(varchar,DATEPART(ss,GETDATE()))
+ CASE WHEN DATEPART(hh,GETDATE()) > 11
THEN "PM"
ELSE "AM"
END
RETURN #outData
END
Then in any regular query, you can just include dbo.fnSpecDate() as myDate

Resources