I am creating a table of random dates with varchar(200) data type and I am unable to generate my query of getting displayed date where year > 2000
ex:
12/03/2017
12/02/1998
12/11/2002
First, you should not be storing dates as strings. It is a bad idea to store fields in the wrong type.
Second, if you do have to store dates as strings (which is occasionally necessary), then use the ISO standard formats: YYYY-MM-DD or YYYYMMDD.
For the format that you are using, you can extract the last four characters:
select right(DateWronglyStoredInStringColumn, 4) as yyyy
You should be storing your dates as a date or datetime2 or datetime datatype in sql server.
For sql server versions prior to sql server 2012, try just using convert():
For dates where the day is first, use set dateformatdmy;
set dateformat dmy;
select
year(convert(date,randomDate)) as [Year]
, randomDate
from t
where year(convert(date,randomDate)) > 2000;
For sql server 2012+, you could use try_convert():
set dateformat dmy;
select
year(try_convert(date,randomDate)) as [Year]
, randomDate
from t
where year(try_convert(date,randomDate)) > 2000;
rextester demo: http://rextester.com/DXVR82331
create table a ( date varchar(200) );
insert into a values
('13-09-2017')
,('12-12-1987')
,('27-01-2037')
,('22-04-1877')
,('02-11-1987')
,('16-08-1974');
set dateformat dmy;
select convert(date,a.[date]) as date
from a
where year(convert(date,a.[date])) > 2000;
returns:
+---------------------+
| date |
+---------------------+
| 13.09.2017 00:00:00 |
| 27.01.2037 00:00:00 |
+---------------------+
Try
select date
from a where convert(char(4),date,121) > '2000'
But be careful when you sort or order the year as You use varchar (text).
Might want to convert the year to an integer for that purpose.
Related
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
I have an SQL DateKey that looks like this
YYYYMMDD
This was created using
Convert(varchar,[ModifiedOn],112))
However I want this field in a view to display the normal dateformat in the UK as DD-MM-YYYY
how can I do that.
Thank you.
Just try CONVERT(VARCHAR(10),CAST(YourStringDate AS DATE),105)
As the date-value YYYYMMDD seems to be a string in the so called unseparated format (and not a BIGINT), SQL-Server will cast this string to DATE implicitly. CONVERT together with 105 will format this the way you want it.
Starting with SQL Server 2012 there is FORMAT(). You might use this:
SELECT FORMAT(CAST(YourStringDate AS DATE),'dd-MM-yyyy')
One method dispenses with the date stuff and just uses string arithmetic:
select (right(ModifiedOn, 2) + '-' +
substring(ModifiedOn, 3, 2) + '-' +
left(ModifiedOn, 4)
) as mmddyyyy
One approach is to add a date table to your database.
Date tables can provide a handy selection of pre-calculated formats, for you to switch between.
They are also useful aggregation targets (GROUP BY DATENAME(QUARTER, CAST(DateKey AS DATE)) Vs GROUP BY DimDate.[Quater]).
-- Basic date table.
CREATE TABLE DimDate
(
DateKey INT PRIMARY KEY,
[Date] DATE NOT NULL,
[Year] INT NOT NULL,
[Quater] VARCHAR(2) NOT NULL,
[DD_MM_YYYY] VARCHAR(10) NOT NULL,
)
;
Contains:
DateKey [Date] [Year] [Quater] [DD_MM_YYYY]
--------------------------------------------------------
20160101 2016-01-01 2016 Q1 01-01-2016
20160102 2016-01-02 2016 Q1 02-01-2016
...
20161231 2016-12-31 2016 Q4 31-12-2016
There is an argument against formatting within the database. Proponants will tell you that formatting is a cosmetic operation, best performed in the presentation layer. Your database, they say, should store only the cold hard facts. Personally I'm not so sure. I agree SQL isn't the best langaue to use for formatting, but sometimes it is the only language in play.
This question already has answers here:
Get the records of last month in SQL server
(23 answers)
Closed 8 years ago.
sql 2005 server
get previous month records
Date product
24-05-2014 ball
25-05-2014 bat
01-06-2014 hat
i need
Date Product
24-05-2014 ball
25-05-2014 bat
declare #ex datetime
set #ex '06-01-2014'
select * from tabl where DATENAME(m,DATEADD(m,0,Date)) =DATENAME(m, DATEADD(m,0, #ex))- it works
select * from tabl where DATENAME(m,DATEADD(m,0,Date)) =DATENAME(m, DATEADD(m,-1,#ex))-not works
My sample code (tested on 2008). I don't know are YEAR and MOTH function in 2005 if not you need to use some string function to extract date / month part from datetime converted to string
declare #ex datetime = '2014-01-01'
declare #prev_year int
declare #prev_month int
set #prev_year = year(dateadd(month, -1, #ex))
set #prev_month = month(dateadd(month, -1, #ex))
select * from tabl
where year(Date) = #prev_year and month(Date) = #prev_month
You're using dd-MM-yyyy format for your dates, which is a varchar in SQL Server.
Therefor, you must use CONVERT :
declare #ex varchar(10)
set #ex = '06-01-2014'
SELECT DATENAME(m,DATEADD(m,0,GETDATE())),
DATENAME(m, DATEADD(m,-1,CONVERT(date, #ex, 103)));
This yields results:
June | May
I think you can figure out your solution from here.
Note: If you use declare #ex datetime , your results will yield June | December
I using a query where I am selecting some attributes from the table based on a where condition. My where condition is-
date>GetDate();
I have tried this-
SELECT TOP 2 img,name,substring(description,1,80) as
description,Convert(nvarchar,date,106) as date
FROM tbl_test
where date>=Convert(nvarchar,GetDate(),106)
order by date Asc;
This query is running fine but showing different result as compared to a different query of similar kind in which I am not converting the date format.
SELECT TOP 2 img,name,substring(description,1,80) as description,date
FROM tbl_test
where date>=GetDate()
order by date Asc;
Please guide me where I am doing wrong?
Your first query will convert getdate() into nvarchar data type and it will compare date with string while 2nd query will compare 2 dates. So 2nd option is better. Still if you want to convert date into string then check then use 102 format like
WHERE CONVERT(varchar(20),date,102) >= CONVERT(varchar(20), getdate(),102)
For select column you can use format which you want like
SELECT CONVERT(varchar(20),date,106)
Final Query is :
SELECT TOP 2
img,
name,
SUBSTRING(description,1,80) as description,
CONVERT(varchar(20),date,106) as [DisplayDate]
FROM tbl_test
WHERE CONVERT(varchar(20),date,102) >= CONVERT(varchar(20), getdate(),102)
ORDER BY date ASC;
Without convert to varchar, you can cast getdate() to date to remove time part :
SELECT TOP 2
img,
name,
SUBSTRING(description,1,80) as description,
CONVERT(varchar(20),date,106) as [DisplayDate]
FROM tbl_test
WHERE date >= CAST(getdate() as date)
ORDER BY date ASC;
SQL Fiddle Demo
DECLARE #Date Datetime;
SET #Date = GETDATE();
SELECT CONVERT(VARCHAR(12), #Date, 113) AS Date
RESULT
╔══════════════╗
║ Date ║
╠══════════════╣
║ 01 Jan 2014 ║
╚══════════════╝
Edit
as Upendra Chaudhari has explained that when you do comparing column Date with a string =Convert(varchar(20),GetDate(),102),
what is actually happening behind the scenes is Convert(varchar(20),GetDate(),102) returns a string 2014.01.01 but to compare this string with a Datetime column SQL Server does an implicit conversion to compare both values. Sql Server have to have both values in the same datatype to compare them.
Now datatype Datetime has Precedence over nvarchar/varchar datatype so sql server converts the string into datetime datatype which returns something like
SELECT CAST('2014.01.01' AS DATETIME)
Result : 2014-01-01 00:00:00.000
Now in this process of converting your values to string and then back to datetime you have actually lost all the time values in your comparing values. and this is the reason why you are getting unexpected results back.
so make sure whenever you are comparing to have exactly the same datatype on both sides and take control of any data conversions in your code rather then sql server doing datatype conversions for you.
I hope this will explain you why you are getting different results .
You may try:
where date>=CONVERT(VARCHAR(11), GETDATE(), 113)
How do I query DateTime database field within a certain range?
I am using SQL SERVER 2005
Error code below
SELECT *
FROM TABLENAME
WHERE DateTime >= 12/04/2011 12:00:00 AM
AND DateTime <= 25/05/2011 3:53:04 AM
Note that I need to get rows within a certain time range. Example, 10 mins time range.
Currently SQL return with Incorrect syntax near '12'."
You missed single quote sign:
SELECT *
FROM TABLENAME
WHERE DateTime >= '12/04/2011 12:00:00 AM' AND DateTime <= '25/05/2011 3:53:04 AM'
Also, it is recommended to use ISO8601 format YYYY-MM-DDThh:mm:ss.nnn[ Z ], as this one will not depend on your server's local culture.
SELECT *
FROM TABLENAME
WHERE
DateTime >= '2011-04-12T00:00:00.000' AND
DateTime <= '2011-05-25T03:53:04.000'
You need quotes around the string you're trying to pass off as a date, and you can also use BETWEEN here:
SELECT *
FROM TABLENAME
WHERE DateTime BETWEEN '04/12/2011 12:00:00 AM' AND '05/25/2011 3:53:04 AM'
See answer to the following question for examples on how to explicitly convert strings to dates while specifying the format:
Sql Server string to date conversion
This has worked for me in both SQL Server 2005 and 2008:
SELECT * from TABLE
WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}
You can execute below code
SELECT Time FROM [TableName] where DATEPART(YYYY,[Time])='2018' and DATEPART(MM,[Time])='06' and DATEPART(DD,[Time])='14
SELECT *
FROM TABLENAME
WHERE [DateTime] >= '2011-04-12 12:00:00 AM'
AND [DateTime] <= '2011-05-25 3:35:04 AM'
If this doesn't work, please script out your table and post it here. this will help us get you the correct answer quickly.
select getdate()
O/P
----
2011-05-25 17:29:44.763
select convert(varchar(30),getdate(),131) >= '12/04/2011 12:00:00 AM'
O/P
---
22/06/1432 5:29:44:763PM
Others have already said that date literals in SQL Server require being surrounded with single quotes, but I wanted to add that you can solve your month/day mixup problem two ways (that is, the problem where 25 is seen as the month and 5 the day) :
Use an explicit Convert(datetime, 'datevalue', style) where style is one of the numeric style codes, see Cast and Convert. The style parameter isn't just for converting dates to strings but also for determining how strings are parsed to dates.
Use a region-independent format for dates stored as strings. The one I use is 'yyyymmdd hh:mm:ss', or consider ISO format, yyyy-mm-ddThh:mi:ss.mmm. Based on experimentation, there are NO other language-invariant format string. (Though I think you can include time zone at the end, see the above link).
if you have a type of datetime and you want to check between dates only ,,,use cast to select between two dates ....
example...
... where cast( Datetime as date) >= cast( Datetime as date) AND cast( Datetime as date) <= cast( Datetime as date)