SQL Server: Convert a month name (string) to a date - sql-server

I have a table with a month name in it as type varchar. e.g. "November". Can I convert this to a date field?
CONVERT(DATETIME,main.ReportMonth) AS ReportMonthDate
CAST(main.ReportMonth AS DATETIME) AS ReportMonthDate
both result in a conversion failure.
I'm using SQL Server 2008.

You can hard code a string value at the end of your input value. Something like this.
declare #ReportMonth varchar(10) = 'November'
select cast(#ReportMonth + ' 1, 2015' as date)
Or if you want to make the year portion be dynamic based on the current date you could modify that slightly like this.
select cast(#ReportMonth + ' 1, ' + cast(datepart(year, getdate()) as char(4)) as date)

Related

Convert a date format as text - day month

Insert a column: received_by as text in the format of Day Month.
i.e. 25/06/2018 should be inserted as 25 June. The format dd/mm/yyyy should be converted into day month - whereby month should be written out.
You can use below select statement to get the desired return
select FORMAT(convert(datetime, '25/06/2018', 103), 'dd MMMM')
Or You can create the custom function in SQL server which will take a date in 'dd/mm/yyyy' format and return day and month as required. use below code to achieve the desired result.
create function GetDateDaynMonth(#date varchar(20))
returns varchar(20)
as
begin
declare #DaynMonth varchar (20)
SELECT #DaynMonth = FORMAT (convert(datetime, #date, 103), 'dd MMMM')
return #DaynMonth;
end
go
select dbo.GetDateDaynMonth('25/06/2018')

SQL Server: Transfer YYYYMMDD-HHMMSS to mm/dd/yyyy hh:mm:ss

My SQL Server system is 2016.
As topic, I want to convert YYYYMMDD-HHMMSS to mm/dd/yyyy hh:mm:ss, and use dynamic SQL to fulfill this.
My data looks like this:
ID
20161119-075950
20161117-110952
20161118-153406
The datatype is nvarchar.
While I used the syntax below:
SELECT convert(date,convert(varchar(max),id,130), 130) from abc
An error Conversion failed when converting date and/or time from character string. shows up. I am thinking whether it is because SQL Server cannot identify this YYYYMMDD-HHMMSS as date type, and I need to convert this to YYYYMMDD hh:mm:ss first and then mm/dd/yyyy hh:mm:ss? Feel free to shed some lights. Thanks!
Select CONVERT(VARCHAR(25) , CAST(LEFT(ID , 8) AS DATETIME), 101)
+ ' ' + LEFT(RIGHT(ID , 6) ,2) + ':'
+ SUBSTRING(RIGHT(ID , 6) , 3,2) + ':'
+ RIGHT(ID , 2)
FROM TableName
Try it like this
DECLARE #tbl TABLE(ID NVARCHAR(100));
INSERT INTO #tbl VALUES
('20161119-075950')
,('20161117-110952')
,('20161118-153406');
--This is the actual select you need:
SELECT CAST(LEFT(ID,8) AS DATETIME) + STUFF(STUFF(RIGHT(ID,6),5,0,':'),3,0,':')
FROM #tbl
Your first part is strictly 8 chars long and implicitly casteable (unseperated datetime yyyymmdd). The time part is strictly 6 chars long. I use STUFF to insert the colons. This time can be added to a DATETIME. It will be - again implicitly - casted to DATETIME.
EDIT
To reach the given format you stated in the title just convert the first part first with code 101:
SELECT CONVERT(VARCHAR(10),CAST(LEFT(ID,8) AS DATETIME),101) + ' ' + STUFF(STUFF(RIGHT(ID,6),5,0,':'),3,0,':')
FROM #tbl
This should get the format you want... but there are probably better ways.
select
convert(varchar(16),convert(date,left(ID,8)),101) +
' ' +
substring(substring(ID,10,6),1,2) +
':' +
substring(substring(ID,10,6),3,2) +
':' + substring(substring(ID,10,6),5,2)

TSQL Month and Year to Date Conversion

I have a table that stores an int for month and year. I need to convert that to a date (we can use the first day of the month and the day).
I tried something like below but got an error about converting int to date
AND CAST(ym.year + '-' + ym.month + '-' + '01' AS DATE) BETWEEN #startDate AND #endDate
End result should be be something like 2016-05-01 so I can check the date against a start and end date that I pass to the function.
You could try something like this, modified for your use:
declare #YY int = 2016
declare #MM int = 5
select CAST(CAST(#YY as varchar(4)) + '-' + RIGHT('00' + CAST(#MM as varchar(2)),2) + '-01' as DATE)
From SQL Server 2012 on you can use DATEFROMPARTS
AND DATEFROMPARTS(ym.year, ym.month, 1) BETWEEN #startDate AND #endDate
AND DateFromParts(ym.year, ym.month, 1) BETWEEN #startDate AND #endDate
EDIT: For old versions of SQL:
SELECT CAST(CAST(ym.year*10000+ym.month*100+1 AS CHAR(8)) AS DATETIME)
Try this :
CAST(CAST(ym.year AS varchar) + '-' + CAST(ym.month AS varchar) + '-01' AS DATETIME)
This will work if you are on 2008 or lower
select cast(
cast(ym.year as varchar(4))+
case when len(ym.month) < 2 then '0' + cast(ym.month as varchar(2)) else cast(ym.month as varchar(2)) end +
'01' as date)
The Error you are getting is because when you CONCAT your INT values there is no leading 0 for days before 10, or months before October, thus your CAST to DATE is essentially missing values to do the conversion. Here we are padding based off the length.
You could go the data way and create a table of year, month and date as first of month then join the tables. this may be faster for a large table especially if the number of years and months in the original table is limited.
So if you have a years data in your original table there would only be 12 records required, which as a join added into your processing should be quick.
To avoid missing dates, build the lookup table from original data:
SELECT year, month, cast(cast(year*10000+month*100+1 as char(8)) as date) as FirstOfMonth
INTO #FirstOfMonth FROM mytable GROUP BY year, month

Get data after year 2012 SQL Server

I am trying to get data after year 2012.
Date is saved in nvarchar format in a table. For example: 12/31/2010
Column also has some other values like 'Confidential', I don't want this row.
I am trying a query (shown below) but it is not succeed :-
select *
from tbl_ProductionWells
where CONVERT(NVARCHAR(10), wellstatusdate, 103) > CONVERT(NVARCHAR(10), '01/01/2012', 103)
Edited :-
I tried this :-
SELECT *
FROM tbl_ProductionWells
WHERE DATEPART(YEAR, CAST(wellstatusdate AS date)) > 2012
But it is giving an error (shown below), This column also has some text values like 'not available','Confidential' .. :-
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Note:- I can't change column datatype as it also contains some other texts.
Thanks in advance
First of all: Store date values in DATE columns, datetimes in DATETIME2 columns. Always choose proper data type for your data
You have to convert your NVARCHAR to DATE, then compare it to 2012-01-01
OR you can extract the 'year' part of your string.
SELECT *
FROM tbl_ProductionWells
WHERE CONVERT(DATE, wellstatusdate) >= '2012-01-01'
The best choice is to change your column's data type to DATE. After that, you can do lots of magicial things with those values. Store the 'Confidental' flag in another column.
EDIT
Some additional info:
Please note, that the STRING -> DATE conversion depends on the current session's language.
Run this batch to see the difference:
DECLARE #DateAsChar VARCHAR(32) = '01/02/12';
SET LANGUAGE us_english
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
SET LANGUAGE Hungarian
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
SET LANGUAGE Deutsch
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
How about:
WITH cte
AS ( SELECT *
FROM tbl_ProductionWells
WHERE ISDATE(wellstatusdate) = 1
)
SELECT *
FROM cte
WHERE DATEPART(YEAR, CAST(wellstatusdate AS DATE)) > 2012
Select all data from the table that is a date using IsDate, then work with that dataset only.
SELECT * FROM
(SELECT * FROM tbl_ProductionWells WHERE ISDATE(wellstatusdate) = 1)
WHERE CAST(wellstatusdate as Date) > #YOURDATE

How to convert date to 104 format without zero in month using T-SQL

For example have query :
declare #date datetime = '2014-06-18'
SELECT CONVERT(varchar,#date,104)
Response is : 18.06.2014 , but I want month without zero, it should be like : 18.6.2014 is it possible to do something like this ?
declare #date datetime = '2014-06-18'
SELECT CAST(DAY(#date) AS VARCHAR(2)) + '.' +
CAST(MONTH(#date) AS VARCHAR(2)) + '.' +
CAST(YEAR(#date) AS VARCHAR(4))
RESULT: 18.6.2014
It feels a little "kludgy", but the only place the sequence .0 can appear in the output date (assuming you're working with dates after 1000 A.D., which you are for datetime which cannot represent dates before 1753) is when there's a leading 0 on the month. So:
declare #date datetime = '2014-06-18'
SELECT REPLACE(CONVERT(varchar,#date,104),'.0','.')
Produces:
18.6.2014
If you are using SQL Server 2012 or above you can use the CONCAT function:
DECLARE #date DATETIME = '2014-06-18'
SELECT
CONCAT(DAY(#date),'.',MONTH(#date),'.',YEAR(#date))
This will return 18.6.2014
Also, if you want to strip the leading zero of the day (say for 2014-06-06), this will take care of that too (which damien_the_unbeliever's solution will not. Not that it is wrong, the behavior is just different so I wanted to make the distinction since it wasn't explicitly stated)
Reference: http://msdn.microsoft.com/en-us/library/hh231515(v=sql.110).aspx

Resources