How to convert nvarchar having yyyymm values to date? - sql

I have a table which has a column 'performance month'. The data type of this column is nvarchar(255) and the values are starting from '202001' to '202012'. How can I select last 5 month data from this table?

The simplest way is:
select convert(date, performance_month + '01')
The standard string representation for dates is YYYYMMDD.
For data from the last five months, you can simply use:
performance_month >= format(dateadd(month, -5, getdate()), 'yyyyMM')
That is, don't convert the string to a date. Convert the date to a string -- this helps the optimizer because it can "see" performance_month without the cloud of function calls.

Related

How to subtract one month from a date using SQL Server

I have a date in format dd/mm/yyyy. I want to subtract one month from it.
I am using this code but the output is "09/10/2020" I don't know why my code does the subtraction of the year -2 also.
This is my request
SELECT
FORMAT(CONVERT (DATE, DATEADD(MONTH, -1, CONVERT(char(9), GETDATE()))), 'dd/MM/yyyy')
you need to change it to:
select format(CONVERT (date,DATEADD(MONTH, -1,GETDATE())), 'dd/MM/yyyy' )
but as Larnu stated. it seems like you need to change the column.
Your current code doesn't work as expected because:
SELECT CONVERT(char(9), GETDATE());
Returns this (at least in my language):
Nov 9 20
Which is, unfortunately, and again in my language, a valid date (but in {20}20, not {20}22).
Even in the right style (103), char(9) would yield 10/11/202 tomorrow, since 9 digits is only enough if either the day or month is a single digit.
Don't know why you are converting GETDATE() to a string. Just perform date math on it and then format it if you need to (using a specific style number, e.g. 103 for d/m/y):
SELECT CONVERT(char(10), DATEADD(MONTH, -1, GETDATE()), 103);
I really wouldn't use FORMAT() for such simple output, as the CLR overhead really isn't worth it. Ideally you leave it as a date/time type until presentation time - surely your presentation layer can present your date as d/m/y if that's really a wise idea.
And if you are storing or passing dates as strings (and worse, in regional formats like d/m/y) you really should consider fixing that.
First of all,
You should be storing your Date as a string for easier manipulation. If you don't want to change the column, you can always convert from Date to Varchar and then (re)convert it.
Example:
First, convert Date to varchar using the style code '112' ISO for formatting as yyyyMMdd:
DECLARE #date DATE = GETDATE();
DECLARE #dateConverted as VARCHAR (8) = (SELECT CONVERT(VARCHAR, #date, 112));
Then you just subtract the month using DATEADD():
DECLARE #previousMonth AS VARCHAR (8) = (SELECT FORMAT(DATEADD(month, -1, #dateConverted), 'yyyyMMdd'));
Finally, convert varchar do Date again:
DECLARE #previousMonthConverted AS DATE = (SELECT CONVERT(CHAR(10), CONVERT(date, #previousMonth), 120));

Convert/get varchar variable to YYYYMM

I have 4 CTE's in this table and the third one contains a DATETIME converted to VARCHAR (with format based on the requirement) as startDate in DD/MM/YYYY format. The last cte does calculations based on the data generated and one of the columns needs to store YYYYMM date based on startDate.
The problem it's getting the year and the month from this converted DATETIME, using convert() it shows this:
IDPER
-------
01/01/ --DD/MM/
These 2 show YYYYMM correctly when startDate isn't converted:
Select *, left(convert(nvarchar(6),new_ini,112),6) as IDPER from table
Select *, convert(nvarchar(6),new_ini,112) as IDPER from table
How could I get YYYYMM format having startDate converted? Or what could be a more smart approach to the requirement
If you have a string in the format DD/MM/YYYY and you want YYYYMM, then use string operations:
select right(new_ini, 4) + substring(new_ini, 4, 2)
You should be storing date values as dates or a related type, not as string. But given that you have already stored this as a string, string operations can do what you need.
My way would be slightly different
SELECT CONVERT(NVARCHAR(6), CONVERT(DATE, new_ini, 103), 112);
Here, I first converted it to date and then formatted to YYYYMMDD and taken 6 chars only
declare #date DATE = GETDATE();
select REPLACE(LEFT(CONVERT(DATE,#date,112),8),'-','') -- 1st approach
select FORMAT(#date,'yyyyMM') --2nd approach

date time stored as varchar in sql how to filter on varchar

I am working on a project in which dates and times ar stored as a varchar e.g. "30-11-2017,7:30" first date in dd-mm-yyy format and then time separated with a comma. I am trying to filter on it but it is not working correctly kindly guide me how to filter data on date.
select *
from timetrack
where startDateAndTime >= '30-11-2017,7:30'
In attached image records have been shown. When I apply above query it shows no records
You can easily convert your date to SQL datatype datetime uisng parse function, for example select parse('30-11-2017,7:30' as datetime using 'it-IT').
So, in your case, you can apply this function in where clause, so you can easily apply comparison between dates:
select *
from timetrack
where parse(startDateAndTime as datetime using 'it-IT') >= '2017-11-30 07:30:00.000'
Your format is apparently italian :) But you have to specify your own date in the format convertable to datetime, as I have done in above example.
NOTE: parse is available starting with SQL Management Studio 2012.
Unless you are using ISO date format (yyyy-MM-dd HH:mm:ss or close) applying ordering (which inequalities like greater than or equal use) will not work: the date order is disconnected from the string ordering.
You'll need to parse the date and times into a real date time type and then compare to that (details of this depend on which RDBMS you are using).
If, you want to just filter out the date then you could use convert() function for SQL Server
select *
from timetrack
where startDateAndTime >= convert(date, left(#date, 10), 103)
Else convert it to datetime as follow
select *
from timetrack
where startDateAndTime >= convert(datetime, left(#date, 10)+' ' +
reverse(left(reverse(#date), charindex(',', reverse(#date))-1)), 103)
You need the date in a datetime column, Otherwise you can't filter with your current varchar format of your date.
Without changing the existing columns, this can be achieved by making a computed column and making it persisted to optimize performance.
ALTER TABLE test add CstartDateTime
as convert(datetime, substring(startDateAndTime, 7,4)+ substring(startDateAndTime, 4,2)
+ left(startDateAndTime, 2) +' '+ right(startDateAndTime, 5), 112) persisted
Note: this require all rows in the column contains a valid date with the current format
Firstly, you need to check what is the data that is entered in the 'startDateAndTime' column,then you can convert that varchar into date format
If the data in 'startDateAndTime' column has data like '30-11-2017,07:30', you would then have to convert it into date:
SELECT to_date('30-11-2017,07:30','dd-mm-yyyy,hh:mm') from dual; --check this
--Your query:
SELECT to_date(startDateAndTime ,'dd-mm-yyyy,hh:mm') from timetrack;

Format varchar type and convert it to date variable

I have a varchar value in this format “YYYYMM-LL” where: YYYY is four digit year; MM is two digit month.LL is two digit length of reporting period. This is the number of whole months included in the calculations (from first to last day of each month).
My questions is how I could use this varchar value to decide two variables:#First_Date and #Last_Date.
Example: 201409-06
This scenario is for the six months ending in September of 2014.
The range of calendar dates in this scenario is 04/01/2014 through 09/30/2014.
So how could I use t-sql to find this two dates #First_Date : 04/01/2014 and #Last_Date: 09/30/2014.
Any help would be really appreciated!
You can do something like this:
select #firstdate = dateadd(month, 1 - cast(right('201409-06', 2) as int),
convert(date, left('201409-06', 6) + '01')
),
#lastdate = dateadd(day, -1,
dateadd(month, 1,
convert(date, left('201409-06', 6) + '01')
)
)
This parses the string to do the date arithmetic that you want. SQL Server recognizes a string in the form of "YYYYMMDD" as a date, regardless of internationalization settings.
And a SQL Fiddle.

Microsoft SQL Server 2008 - Dates

I have a couple of questions in regards to dates in SQL Server.
How do I separate a datetime value "2011-08-10 14:56:17.267" into date and timestamp in two separate columns. Eg. Date "2011-08-10" and timestamp "14:56:17"
I want remove the timestamp from datetime value into "2011-08-10" and still be able to order the data by date (therefore not converted to varchar). Also is there away to change the date value as '10 Aug 2011' and still can sort (not alphabetically but in real date order).
Thank you,
HL
For the first one:
UPDATE atable
SET
DateColumn = CAST(DateTimeColumn AS date),
TimeColumn = CAST(DateTimeColumn AS time)
As for the second one, date display format is something that is unrelated to the date value. You can order the result set by your date column, but in the SELECT clause you can use CONVERT to display the date in the desired format. For example:
SELECT
CONVERT(varchar, DateColumn, 106) AS Date,
…
FROM atable
ORDER BY DateColumn
use CONVERT function with parameters from resource http://www.mssqltips.com/tip.asp?tip=1145
-- simple conversion example:
SELECT CONVERT(VARCHAR(10), GETDATE(), 102) -- for date
SELECT CONVERT(VARCHAR(10), GETDATE(), 8) -- for time