i'm trying to do this line of sql script
select *
from content
where first_broadcast_date <= CONVERT(datetime, '26-11-2014', 105)
the result show me the content which have the value of 'first_broadcast_date' less than '26-11-2014' but not the content which have 'first_broadcast_date = 26-11-2014'
the type of 'first_broadcast_date' field is datetime2(7)
because its a date time field you either have a choice to convert to date might give you a bad performance or you can pass date by concatenating 23:59:59 so that you can filter any row in that day
CREATE TABLE #t (id INT IDENTITY(1,1), d DATETIME2(7))
INSERT INTO #t (d)
VALUES(GETDATE())
SELECT * FROM #t WHERE d <= '02/12/2015 23:59:59'
Related
I'm trying to set a column with a default value or binding of the current date in MSSQL.
I'm currently using GETDATE(), but this gives me the timestamp with the hours, minutes, seconds and milliseconds, I only need the day part (2015-03-05).
Only results I found on the web were these of changing it in the SELECT statement.
If you use it in a date context SQL Server will auto cast it for you
DECLARE #date DATE = GETDATE();
SELECT #date
-- result: 2015-03-05
or you could simply use a cast
SELECT CAST(GETDATE() as DATE)
EDIT:
I'm still not sure if I get what you want, but if you want to do it as a default constraints it works the same way:
create table #table
(
id int,
insertDate date default GETDATE()
)
insert into #table (id) values (1)
select top 1 insertDate from #table
-- result: 2015-03-05
If you want to store only date, excluding time you can use this:
CREATE TABLE #dts(id INT IDENTITY, d_date datetime2 DEFAULT CONVERT(char(10), GETDATE(), 126))
INSERT #dts DEFAULT VALUES
SELECT * FROM #dts
However it will return you zeroes instead of time, as seen here:
id d_date
-------------------------------
1 2015-03-05 00:00:00.0000000
You can remove unwanted characters using LEFT function:
SELECT id, LEFT(d_date, 10) FROM #dts
It will return you:
id d_date
--------------
1 2015-03-05
You could achieve this by using varchar as datatype, but i dont think it would be appropiate solution and it's better to format date in select statement. But if you really need it, then this works:
CREATE TABLE #dts(id INT IDENTITY, d_date VARCHAR(10) DEFAULT CONVERT(char(10), GETDATE(), 126))
INSERT #dts DEFAULT VALUES
SELECT * FROM #dts
Output:
id d_date
--------------
1 2015-03-05
Set your default value on the column to
(CONVERT([date],getdate(),0))
I have used it many times
In other ways to convert DATETIME to DATE (get only date without time) you can use CAST to DATE format.
SELECT CAST(GETDATE() AS DATE)
In your case you can set default value type DATE without CASTing.
CREATE TABLE #TempTable
(
Id INT,
..... ,
CurrentDate DATE DEFAULT GETDATE()
)
The answer to your problem is simple. Change the format of the column that is going to hold the value to a DATE (as opposed to a data type that will hold the time portion, i.e: DATETIME).
Then set the default to GETDATE() and because the destination column is a DATE the time portion will be stripped off for you.
Take this sample code:
CREATE TABLE #temp (id INT, CreatedDate DATE DEFAULT GETDATE())
INSERT INTO #temp ( id)
VALUES ( 1 ),( 2 ),( 3 )
SELECT * FROM #temp
DROP TABLE #temp
Output:
id CreatedDate
1 2015-03-05
2 2015-03-05
3 2015-03-05
You can use CONVERT() to get date in different formats. From http://www.w3schools.com/sql/func_convert.asp :
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
gives you the following results:
Nov 04 2011 11:45 PM
11-04-11
11-04-2011
04 Nov 11
04 Nov 2011
04 Nov 2011 11:45:34:243
I need to perform a query on a large table that has a datetime column that is indexed.
We need to query the data for a range from a month (at a minimum) to multiple months.
This query would be executed from Cognos TM1 and the input would be a period like YYYYMM. My question is - how to convert the YYYYMM input to a format that can be used to query that table (with the index being used).
Let's say if the input is
From Date: '201312'
To Date: '201312'
then, we need convert the same to 'between 01-12-2013 and 31-12-2013' in the query
Since we need this to be hooked up in Cognos TM1, so would not be able to write a procedure or declare variables (TM1 somehow does not like it).
Thanks in advance for your reply.
I would do something like this:
create procedure dbo.getDataForMonth
#yyyymm char(6) = null
as
--
-- use the current year/month if the year or month is invalid was omitted
--
set #yyyymm = case coalesce(#yyyymm,'')
when '' then convert(char(6),current_timestamp,112)
else #yyyymm
end
--
-- this should throw an exception if the date is invalid
--
declare #dtFrom date = convert(date,#yyyymm+'01') -- 1st of specified month
declare #dtThru date = dateadd(month,1,#dtFrom) -- 1st of next month
--
-- your Big Ugly Query Here
--
select *
from dbo.some_table t
where t.date_of_record >= #dtFrom
and t.date_of_record < #dtThru
--
-- That's about all there is to it.
--
return 0
go
Suppose you are getting this value of YYYYMM in a varchar variable #datefrom .
You can do something like
DECLARE #DateFrom VARCHAR(6) = '201201';
-- Append '01' to any passed string and it will get all
-- records starting from that month in that year
DECLARE #Date VARCHAR(8) = #DateFrom + '01'
-- in your query do something like
SELECT * FROM TableName WHERE DateTimeColumn >= #Date
Passing Datetime in a ansi-standard format i.e YYYYMMDD is a sargable expression and allows sql server to take advantage of indexes defined on that datetime column.
here is an article written by Rob Farley about SARGable functions in SQL Server.
Try this...
declare #startdate date,#endate date
select #startdate =convert(date,left('201312',4)+'-'+right('201312',2)+'-01')
select #endate= DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, #startdate) + 1, 0))
select convert(date,#startdate,102) startdate,convert(date,#endate,102) endate
In the datasource of your TM1 Turbo Integrator process, you can use parameters in the SQL query. E.g. you could take this SQL query:
SELECT Col1, Col2
FROM Table
WHERE Col1 = 'Green'
AND Col2 < 30
In TM1, to parameterise this, you would create two parameters e.g. P1 and P2 and put them in the query:
SELECT Col1, Col2
FROM Table
WHERE Col1 = '?P1?'
AND Col2 < ?P2?
I have a table in a server that outputs the date in the following format YEARMONTHDAY
Example 20140410.
Question is how to I convert it to be as MONTH/DAY/YEAR, example 04/10/2014
Thanks!
David
Try this:
declare #theDate varchar(8)
set #theDate = '20140410'
select convert(varchar(10),cast(#theDate as date),101)
I think you can use:
SELECT convert(varchar, getdate(), 101);
Here is one way to do it:
declare #dt CHAR(8) = '20140131'
select #dt, CONVERT(DATE,#dt) as newDt
Here is a link on the CONVERT function http://msdn.microsoft.com/en-us/library/ms187928.aspx and one on date types http://msdn.microsoft.com/en-us/library/bb630352.aspx
Here are 2 different versions, one version for if all values are valid YYYYMMDD format, and one that will still work with invalid dates (but will return null for invalids).
DECLARE #tblTest TABLE (id int not null identity, myDate int not null)
INSERT INTO #tblTest(myDate)
VALUES(20140308),(20140410)
;
--QUERY 1: if all values in your table are valid dates, then you can use this
SELECT t.id, t.myDate
, myDateFormatted = CONVERT(varchar(10),CONVERT(DATE, CONVERT(VARCHAR(10),t.myDate)),101)
FROM #tblTest t
--NOW INSERT SOME INVALID DATES AS WELL
INSERT INTO #tblTest(myDate)
VALUES(20140132),(48)
;
--NOW IF THERE ARE INVALID DATE, THEN USING QUERY 1 WOULD CAUSE AN ERROR: Conversion failed when converting date and/or time from character string
--QUERY 2: if there are ANY invalid values in your table, then you can use this
SELECT t.id, t.myDate
, myDateFormatted =
CASE
WHEN ISDATE(t.mydate) = 1 and len(t.myDate) = 8
THEN CONVERT(varchar(10),CONVERT(DATE, CONVERT(VARCHAR(10),t.myDate)),101)
ELSE NULL --THIS IS AN INVALID DATE
END
FROM #tblTest t
;
I'm using SQL SERVER 2008.
I have a table that stores dates in datetime format (i.e.2012-01-21 15:00:00.000)
I'm trying to filter out all the dates older than "today". So I was attempting to do so by using the query below.
SELECT Date
FROM MyTable
WHERE Date >= GETDATE()
When I run that though, I get the following error.
Conversion failed when converting date and/or time from character string.
Is there something I'm doing wrong? Thanks for the help and let me know if I need to provide more information!
More Information:
[Date] is of type DateTime in MyTable.
I also have a View that simply selects [Date] and does no manipulation
I'm accessing [Date] via the View
It looks like your column is not a DATETIME data type after all. It is probably VARCHAR or similar. If you provide the DDL for the creation of the table, that would allow a more specific answer.
You don't say what locale your in as this will matter. The most likely possibility is that your DATE column isn't a DATETIME. You don't say what locale your in, but (as an example) US and UK datetime formats are treated differently when in reverse format.
UK sees the date as yyyy-dd-mm hh:mm:ss.fff
US sees the date as yyyy-mm-dd hh:mm:ss.fff
For example, this throws an error:
SET LANGUAGE british
GO
SELECT CAST ('1999-01-21 10:11:12.345' AS DATETIME)
GO
However if you change the locale to us_english, it will parse correctly.
If you want to gurantee it's always going to be parsed as yyyy-mm-dd, then you need to be strict and use the full ISO spec by specifying Z between the date and time, e.g.,: 1999-01-21Z10:11:12.345 will parse in the same way in both locales.
Ultimately, you want to change the Date column to a datatype of DATETIME, but you may need to temporarialy change your locale to be able to do this sucessfully; i.e.:
SET LANGUAGE us_english
GO
ALTER TABLE [...]
GO
SET LANGUAGE british
GO
Yet another fun 'gotcha' to watch out for when manipulating date/time data.
Sidenote: no I don't know why the Microsoft think us over in Blighty see the date as yyyy-dd-mm ... I've never encountered this format. Could be inherited from European formats?
First of all you should change this to:
SELECT [Date]
FROM MyTable
WHERE [Date] <= GETDATE()
That type of Column is [Date]????
If your date column is VARCHAR/NVARCHAR you need to convert that value to DATETIME. From your example, the right format should be:
SELECT [Date]
FROM MyTable
WHERE CONVERT(DATETIME,[Date],121) >= GETDATE()
SQL will implicitly convert a varchar to a datatime if you are comparing it to a datetime. The issue you're getting is that there is a record in your table that is not in a datetime format.
GOOD EXAMPLE:
SELECT *
INTO #Temp
FROM
(
SELECT '2010-01-21 15:00:00.000' [Date] UNION
SELECT '2012-01-21 05:30:00.000' [Date] UNION
SELECT '2015-01-21 07:45:00.000' [Date] UNION
SELECT '2020-01-21 11:20:00.000' [Date]
) x
SELECT *
FROM #Temp
WHERE [Date] > GETDATE()
DROP TABLE #Temp
BROKEN EXAMPLE:
SELECT *
INTO #Temp
FROM
(
SELECT '2010-01-21 15:00:00.000' [Date] UNION
SELECT '2012-01-21 05:30:00.000' [Date] UNION
SELECT '2015-01-21 07:45:00.000' [Date] UNION
SELECT 'a2020-01-21 11:20:00.000' [Date]
) x
SELECT *
FROM #Temp
WHERE [Date] > GETDATE()
DROP TABLE #Temp
The 'a' in the last record of the broken example will cause the error your getting.
WORK AROUND
SELECT *
INTO #Temp
FROM
(
SELECT '2010-01-21 15:00:00.000' [Date] UNION
SELECT '2012-01-21 05:30:00.000' [Date] UNION
SELECT '2015-01-21 07:45:00.000' [Date] UNION
SELECT 'a2020-01-21 11:20:00.000' [Date]
) x
SELECT *
FROM
(
SELECT CASE WHEN ISDATE([Date]) = 1 THEN [Date] ELSE '' END [Date]
FROM #Temp
) x
WHERE [Date] > GETDATE()
DROP TABLE #Temp
BETTER OPTION
SELECT *
INTO #Temp
FROM
(
SELECT '2010-01-21 15:00:00.000' [Date] UNION
SELECT '2012-01-21 05:30:00.000' [Date] UNION
SELECT '2015-01-21 07:45:00.000' [Date] UNION
SELECT 'a2020-01-21 11:20:00.000' [Date]
) x
SELECT *
FROM #Temp
WHERE CASE WHEN ISDATE([Date]) = 1 THEN [Date] ELSE '' END > GETDATE()
DROP TABLE #Temp
I have start time and end time in my application. I now need to check if there is any time falling between those time in SQL Query.
How do I write the query.
Thanks
This should work for you.
Select * From MyTable
Where timecreated Between Cast('7/20/08 12:01:01' As DateTime) And Cast('7/20/09 12:01:01' as DateTime)
I would recommend to not use between when comparing datetime. The result is often not what you want.
BETWEEN returns TRUE if the value of
test_expression is greater than or
equal to the value of begin_expression
and less than or equal to the value of
end_expression.
Test data for demo
declare #T table (dt datetime)
insert into #T values('2011-04-12T09:00:00')
insert into #T values('2011-04-12T10:00:00')
insert into #T values('2011-04-12T11:00:00')
insert into #T values('2011-04-12T12:00:00')
Query using between
select *
from #T
where dt between '2011-04-12T10:00:00' and '2011-04-12T11:00:00'
Result: 11:00 is included in the result.
dt
2011-04-12 10:00:00.000
2011-04-12 11:00:00.000
Rewrite the query using >= and < instead.
select *
from #T
where
dt >= '2011-04-12T10:00:00' and
dt < '2011-04-12T11:00:00'
Result
dt
2011-04-12 10:00:00.000
The title of the question hints at that you want to check for overlapping date intervals. If that is the case you can have a look at this question How can I determine in SQL Server if a dateTime range overlaps another.
This will also work :-
select * from tablename where time between '7/7/2009 12:35:35' and '7/7/2010 23:35:35'