SQL Server: Convert varchar numbers to date - sql

Is it possible to convert a varchar numbers to date? I am fetching data from a table and I want it converted into date. Can you help me figure this out?
There is an error on the last part:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
declare #year varchar(6)
declare #month varchar(2)
declare #test varchar (8)
set #year = right(left('F20160316-1000',5),4)
select #year
set #month = right(left('F20160316-1000',7),2)
select #month
set #test = #month +''+ #year
select #test
SELECT CONVERT (DATETIME, CONVERT(varchar(12),#test))
Anyway, the the result that I want to achieve is MAR2016.

The way you are storing and converting is not good as Jarlh pointed out.You could use datetimefrom parts to get output ,in your case day is missing ,i added it..
declare #year varchar(6)
declare #month varchar(2)
declare #day varchar (8)
set #year = right(left('F20160316-1000',5),4)
set #month = right(left('F20160316-1000',7),2)
Set #day=right(left('F20160316-1000',5),2)
select datetimefromparts(#year,#month,#day)
further if your string pattern is same ,you can do this as well..
declare #string varchar(15)
set #string='F20160316-1000'
select convert(datetime,substring(#string,2,charindex('-',#string,1)-2)
Output:
2016-03-16 00:00:00.000

Try like this,
DECLARE #year VARCHAR(6)
DECLARE #month VARCHAR(2)
DECLARE #test VARCHAR(8)
SET #year = right(left('F20160316-1000', 5), 4)
SET #month = right(left('F20160316-1000', 7), 2)
SET #test = #year + #month + '01'
SELECT UPPER(CONVERT(VARCHAR(3), DATENAME(MM, #test), 100)) + #year AS MonthYear

Related

SQL Select statement, change Format mmddyy to dd-mon-yyyy with convert

I want to select field opendate mmddyy data type decimal(6,0) to dd-mon-yyyy. How do I modify this statement?
select convert(varchar(10),M.opendate, 106)
FROM All.Customer M
The above results in the following error:
[SQL0204] CONVERT in *LIBL type *N not found
You can try this:
DECLARE #InputDate VARCHAR(8)
SET #InputDate = '073019'
DECLARE #InputYear VARCHAR(4)
DECLARE #InputMonth VARCHAR(2)
DECLARE #InputDay VARCHAR(2)
SET #InputYear = '20' + SUBSTRING(#InputDate, 5, 2)
SET #InputMonth = LEFT(#InputDate, 2)
SET #InputDay = SUBSTRING(#InputDate, 3, 2)
DECLARE #OutputDate DATE
SET #OutputDate = #InputYear +'-'+ #InputMonth +'-'+ #InputDay
SELECT CONVERT(VARCHAR(15), #OutputDate, 106)
Still you should know how to define the first 2 digits of the year. I have used '20' as default.

How to create a Date in SQL Server given the Day, Month and Year as Integers

FOR Example if I have:
DECLARE #Day int = 25
DECLARE #Month int = 10
DECLARE #Year int = 2016
I want to return
2016-10-25
As Date or datetime
In SQL Server 2012+, you can use datefromparts():
select datefromparts(#year, #month, #day)
In earlier versions, you can cast a string. Here is one method:
select cast(cast(#year*10000 + #month*100 + #day as varchar(255)) as date)
In SQL Server 2012+, you can use DATEFROMPARTS():
DECLARE #Year int = 2016, #Month int = 10, #Day int = 25;
SELECT DATEFROMPARTS (#Year, #Month, #Day);
In earlier versions, one method is to create and convert a string.
There are a few string date formats which SQL Server reliably interprets regardless of the date, language, or internationalization settings.
A six- or eight-digit string is always interpreted as ymd. The month
and day must always be two digits.
https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql
So a string in the format 'yyyymmdd' will always be properly interpreted.
(ISO 8601-- YYYY-MM-DDThh:mm:ss-- also works, but you have to specify time and therefore it's more complicated than you need.)
While you can simply CAST this string as a date, you must use CONVERT in order to specify a style, and you must specify a style in order to be deterministic (if that matters to you).
The "yyyymmdd" format is style 112, so your conversion looks like this:
DECLARE #Year int = 2016, #Month int = 10, #Day int = 25;
SELECT CONVERT(date,CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),112);
And it results in:
2016-10-25
Technically, the ISO/112/yyyymmdd format works even with other styles specified. For example, using that text format with style 104 (German, dd.mm.yyyy):
DECLARE #Year int = 2016, #Month int = 10, #Day int = 25;
SELECT CONVERT(date,CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),104);
Also still results in:
2016-10-25
Other formats are not as robust. For example this:
SELECT CASE WHEN CONVERT(date,'01-02-1900',110) = CONVERT(date,'01-02-1900',105) THEN 1 ELSE 0 END;
Results in:
0
As a side note, with this method, beware that nonsense inputs can yield valid but incorrect dates:
DECLARE #Year int = 2016, #Month int = 0, #Day int = 1025;
SELECT CONVERT(date,CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),112);
Also yields:
2016-10-25
DATEFROMPARTS protects you from invalid inputs. This:
DECLARE #Year int = 2016, #Month int = 10, #Day int = 32;
SELECT DATEFROMPARTS (#Year, #Month, #Day);
Yields:
Msg 289, Level 16, State 1, Line 2 Cannot construct data type date,
some of the arguments have values which are not valid.
Also beware that this method does not work for dates prior to 1000-01-01. For example:
DECLARE #Year int = 900, #Month int = 1, #Day int = 1;
SELECT CONVERT(date,CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),112);
Yields:
Msg 241, Level 16, State 1, Line 2 Conversion failed when converting
date and/or time from character string.
That's because the resulting string, '9000101', is not in the 'yyyymmdd' format. To ensure proper formatting, you'd have to pad it with leading zeroes, at the sacrifice of some small amount of performance. For example:
DECLARE #Year int = 900, #Month int = 1, #Day int = 1;
SELECT CONVERT(date,RIGHT('000' + CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),8),112);
Results in:
0900-01-01
There are other methods aside from string conversion. Several are provided in answers to "Create a date with T-SQL". A notable example involves creating the date by adding years, months, and days to the "zero date".
(This answer was inspired by Gordon Linoff's answer, which I expanded on and provided additional documentation and notes.)
Old Microsoft Sql Sever (< 2012)
RETURN dateadd(month, 12 * #year + #month - 22801, #day - 1)
The following code should work on all versions of sql server I believe:
SELECT CAST(CONCAT(CAST(#Year AS VARCHAR(4)), '-',CAST(#Month AS VARCHAR(2)), '-',CAST(#Day AS VARCHAR(2))) AS DATE)
Simple and most flexible solution
Use FORMAT function to make any type of format you like.
Here is copy paste working example:
DECLARE #year int = 2021, #month int = 12, #day int = 16
DECLARE #date varchar(20)
SET #date = cast((format(#year,'####') +'-'+format(#month,'##')+'-'+format(#day,'##')) as date)
SELECT #date
It will also display leading zeros for days and months.
So, you can try this solution:
DECLARE #DAY INT = 25
DECLARE #MONTH INT = 10
DECLARE #YEAR INT = 2016
DECLARE #DATE AS DATETIME
SET #DATE = CAST(RTRIM(#YEAR * 10000 + #MONTH * 100 + #DAY) AS DATETIME)
SELECT REPLACE(CONVERT(VARCHAR(10), #DATE, 102), '.', '-') AS EXPECTDATE
Or you can try this a few lines of code:
DECLARE #DAY INT = 25
DECLARE #MONTH INT = 10
DECLARE #YEAR INT = 2016
SELECT CAST(RTRIM(#YEAR * 10000 +'-' + #MONTH * 100+ '-' + #DAY) AS DATE) AS EXPECTDATE
select convert(varchar(11), transfer_date, 106)
got me my desired result of date formatted as 07 Mar 2018
My column 'transfer_date' is a datetime type column and I am using SQL Server 2017 on azure
CREATE DATE USING MONTH YEAR IN SQL::
DECLARE #FromMonth int=NULL,
#ToMonth int=NULL,
#FromYear int=NULL,
#ToYear int=NULL
/**Region For Create Date**/
DECLARE #FromDate DATE=NULL
DECLARE #ToDate DATE=NULL
SET #FromDate=DateAdd(day,0, DateAdd(month, #FromMonth - 1,DateAdd(Year, #FromYear-1900, 0)))
SET #ToDate=DateAdd(day,-1, DateAdd(month, #ToMonth - 0,DateAdd(Year, #ToYear-1900, 0)))
/**Region For Create Date**/
For SQL Server 2008 users, I made a custom function:
CREATE FUNCTION sql2012_datefromparts
(
#Year int, #Month int, #Day int
)
RETURNS DATETIME
AS
BEGIN
RETURN convert(datetime,convert(varchar,#year)+right('0'+convert(varchar,#month),2)+right('0'+convert(varchar,#day),2))
END
GO
To use it:
DECLARE #day int=29, #month int=10, #year int=1971
SELECT dbo.sql2012_datefromparts(#year,#month,#day)

Error when running SQL stored procedure coversion failed when converting date and/or time from character string

DECLARE #i varchar(13)
DECLARE #Year varchar(30)
SET #i = 2
SET #Year = 2013
SELECT SUM(CAST([totalAfterMultiplier] as money)) as 'totalAfterMultiplier' FROM [postfinanceAfterMultiplier]
WHERE CAST([ORDER] as date) >= '01/'+#i+'/'+ #Year +'' AND CAST([ORDER] as date) <= '31/'+#i+'/'+ #Year +''
I am getting this error: Conversion failed when converting date and/or time from character string.
All values in the database are varchar(50)
I have looked at the other posts and can't seem to get it working
Thank you all for your help
Don't store dates as varchar.
if you want to convert to date from string 'dd/mm/yyyy', use explicit format 103, like select convert(date, '01/12/2013', 103). See other formats here - CAST and CONVERT (Transact-SQL)
I found that the following solution works:
DECLARE #i varchar(13)
DECLARE #Year varchar(30)
SET #i = 2
SET #Year = 2013
SELECT SUM(CAST([totalAfterMultiplier] as money)) as 'totalAfterMultiplier' FROM [postfinanceAfterMultiplier]
WHERE MONTH([ORDER]) = #i AND YEAR([ORDER]) = #Year

SQL Server : setting two variables month and year for previous month, year roll over safe

I'm trying to basically dynamically set two variables (#month and #year) to be whatever the previous month and year were.
So in today's case #month = 7 and #year = 2012
But I want something safe for the year roll around, so if it's 1/1/2013 I would get #month = 12 and #year = 2012.
Thanks!
This is what I have.
declare #month int
declare #year int
set #month = month (getDate ())-1
set #year = 2012
You can use DATEADD to subtract a month from the current date, then grab the MONTH and YEAR portions:
DECLARE #monthAgo dateTime
DECLARE #month int
DECLARE #year int
SET #monthAgo = DATEADD(month, -1, GETDATE())
SET #month = MONTH(#monthAgo)
SET #year = YEAR(#monthAgo)
Shown in steps. You can modify the value assigned to #Now to test.
DECLARE #Now DateTime = GETDATE();
DECLARE #Then DateTime = DATEADD(Month, -1, #Now);
DECLARE #Month Int = DATEPART(Month, #Then);
DECLARE #Year Int = DATEPART(Year, #Then);
SELECT #Month, #Year;
can you not just add, after what you already have:
if #month = 0
begin
set #month = 12
set #year = #year - 1
end
As a single query, this gives the first day of last month:
select DATEADD(month,DATEDIFF(month,'20010101',CURRENT_TIMESTAMP),'20001201')
You can, if you choose, pull that apart into two separate variables, but why bother? (I assume the rest of what you're doing is working with datetimes also, rather than ints)
The two datetime strings above are selected because they have the desired relationship between them - that the second starts 1 month before the first.
Try this
declare #month int
declare #year int
Declare #dt datetime=getdate()
set #month = DATEPART(mm,DATEADD(mm,-1,#dt))
select #month
set #year = DATEPART(yy,DATEADD(mm,-1,#dt))
select #year

How to get year and month separately from this string in sql server?

I have this string format mm/yyyy-
01/2010
how do i get the month and year separately from it. I want it separately 01 and 2010 in a way i could compare them?
This should hook you up (assumes that #Date represents your date string):
DECLARE #SlashPos int;
SET #SlashPos = CHARINDEX('/', #Date);
Declare #Month varchar(2);
Declare #Year varchar(4);
SET #Month = SUBSTRING(#Date, 1, #SlashPos - 1);
Set #Year = SUBSTRING(#Date, #SlashPos + 1, LEN(#Date) - #SlashPos);
At this point, #Month and #Year will contain strings representing the month and year.
Example:
declare #d char(7);
declare #Month varchar(2);
declare #Year varchar(4);
set #d = '01/2010';
SET #Month = LEFT(#d, 2);
SET #Year = RIGHT(#d, 4);
check out help for substring and charindex functions