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
Related
I want to select records by date using variable.
DECLARE #estDate datetime
SET #estDate = (SELECT GETDATE())
SELECT Meta FROM T_TData WHERE Estt_Date=#estDate
My table:
Meta
Estt_Date
12
2023-01-31 16:34:36.143
99
2023-01-31 16:34:36.143
45
2022-12-31 16:34:30.145
95
2023-01-25 16:34:36.143
My meta column in table int and Estt_Date is datetime.
How can I select records of particular date using variable.
You can do this. Please find the following example
CREATE TABLE #tempData
(
Meta INT,
Estt_Date DATETIME
)
INSERT INTO #tempData(Meta,Estt_Date)
VALUES
(12,'2023-01-31 16:34:36.143'),
(12,'2023-01-31 16:34:36.143'),
(12,'2022-12-31 16:34:30.145'),
(12,'2023-01-25 16:34:36.143')
SELECT * FROM #tempData
DECLARE #estDate DATE = CAST(GETDATE() AS DATE)
SELECT * from #tempData WHERE CAST(Estt_Date AS DATE)=#estDate
DROP TABLE IF EXISTS #tempData
DECLARE #ESTDATE DATE
SET #ESTDATE=GETDATE()
SELECT META FROM T_TDATA WHERE ESTT_DATE>=#ESTDATE AND ESTT_DATE<DATEADD(DD,1,#ESTDATE)
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'
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
;
How do I add time to a datetime field with an indexing value?
My RDBMS is SQL Server 2008 R2.
I want to start at noon for a datetime field and for every record, take the base value of noon and add 15 seconds and set it for the record.
Example
Record 1: DateTime Value = '12:00:00 pm'
Record 2: DateTime Value = '12:00:15 pm'
Record 3: DateTime Value = '12:00:30 pm'
...n...
I toyed with a UPDATE query, but I couldn't get it to index. I'm feeling this might require a function, but I'm not sure.
Ideas?
Respectfully,
Ray
Assuming that you have a table YourTable with a datetime column Value that you need to fill with a datetime value incremented by 15 seconds for each row. Here I use a column ID to specify the order of the rows.
declare #Start datetime = '2011-05-18T12:00:00'
;with cte as
(
select Value,
row_number() over(order by ID) as rn
from YourTable
)
update cte set
Value = dateadd(s, 15*(rn-1), #Start)
With a recursive CTE (Common Table Expression) you could do this pretty easily:
;WITH DateTimes AS
(
SELECT
CAST('2011-05-18T12:00:00pm' AS DATETIME) AS YourTime,
1 AS RowNum
UNION ALL
SELECT
DATEADD(SECOND, 15, dt.YourTime),
dt.RowNum + 1
FROM
DateTimes dt
WHERE
dt.RowNum < 50
)
SELECT *
FROM DateTimes
Mind you: you need to make sure yourself to stop the recursion before the default max recursion depth of 100 has been reached (that's what I use the RowNum column for) - otherwise, SQL Server will tell you loud and clear that it doesn't like this recursive CTE :-)
This produces an output of:
YourTime RowNum
2011-05-18 12:00:00.000 1
2011-05-18 12:00:15.000 2
2011-05-18 12:00:30.000 3
2011-05-18 12:00:45.000 4
....
....
2011-05-18 12:12:00.000 49
2011-05-18 12:12:15.000 50
So if you have a DATETIME value that has no time like this:
DECLARE #Today DATETIME
SET #Today = CAST(GETDATE() AS DATE)
SELECT #Today -- gives: 2011-05-18 00:00:00.000
you could easily add time values to it from your recursive CTE (you could even adapt it to return only TIME and add that to your DATETIME column):
SELECT
CAST(YourTime AS TIME),
#Today + CAST(YourTime AS TIME) AS 'NewValue'
FROM TimeValues
Look at the DATEADD function and this may help you.
http://msdn.microsoft.com/en-us/library/ms186819.aspx
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'