SQL Server default date time stamp? - sql

I have a field that when something is inserted I want it to get the current Date & Time and insert this into the database. Is there a way to get the date & time, and set it as the default value?
Currently the default value is: (getdate()) Which sets only the date. How do I also set the time?

GETDATE() is a date and time in SQL Server.
Run SELECT GETDATE() to verify this.
What is the datatype of your field? If it's DATE then it will not hold time values as well.

One easy way is to give the field a default constraint:
create table YourTable
(
... other columns ...
CreateDt datetime default getdate(),
... other columns ...
)
A disadvantage of this method is that you can overwrite the value by specifying it in an insert clause.

Personally I would like to use GETUTCDATE() instead GETDATE() to avoid confusions.

SYSDATETIME() will get the current date and time.
Make sure the data type of the column is datetime, and not just date or it won't be able to hold a datetime.

Most SQL implementations (engines) do have CURRENT_TIMESTAMP function.

Related

How to order by date when a column is of type nvarchar in Microsoft SQL Server

I have an issue where I created a column sent_Date of type nvarchar while it's storing date and time.
Now when I try to sort it by date, it's not doing so correctly.
I am using this query:
select *
from tbl_skip
where sent_date > '9/27/2020 7:29:11 PM'
order by SENT_DATE desc
Like the comments have said, the real solution here is fix your design. That means changing the column's data type an nvarchar to a date and time data type, I'm going to use a datetime2(0) here, as your data is accurate to a second, so seems the most appropriate.
Firstly we need to convert the value to as ISO value. I'm also, however, going to create a new column called Bad_Sent_Date, to store values that could not be converted. Experience has taught many of us that systems that incorrectly use string data types to store dates (or numerical data) rarely have good data integrity rules on the value (because if they did, it wouldn't be an nvarchar) to start, so have bad values like '29/02/2019' or mix styles, such as having both '09/29/2020' and '29/09/2020'.
Based on the single example we have, I will assume your data is supposed to be in the format MM/dd/yy hh:mm:ss AM/PM:
ALTER TABLE dbo.tbl_skip ADD Bad_Sent_Date nvarchar(30) NULL;
GO
UPDATE TABLE dbo.tbl_skip
SET Bad_Sent_Date = CASE WHEN TRY_CONVERT(datetime2(0),Sent_date,101) IS NULL THEN Sent_date END,
Sent_Date = CONVERT(nvarchar(30),TRY_CONVERT(datetime2(0),Sent_date,101),126);
GO
Now we have an ISO format, we can change the table's data type:
ALTER TABLE dbo.tbl_skip ALTER COLUMN Sent_date datetime2(0) NULL;
Note that if you do have constraints on the column Sent_date, or it isn't NULLable, you will first need to DROP said CONSTRAINTs, change the column to be NULLable and then recreate said CONSTRAINTs after you have altered the column.
You can also review the "dates" that failed to be converted with the following:
SELECT bad_sent_date
FROM dbo.tbl_skip
WHERE bad_sent_date IS NOT NULL
AND Sent_date IS NULL;
Once that's all done, then your query simply needs an update to use an unambiguous date literal, and it'll work:
SELECT *
FROM tbl_skip
WHERE sent_date > '2020-09-27T19:29:11' --'9/27/2020 7:29:11 PM'
ORDER BY SENT_DATE DESC;
You can convert the data from string to datetime.
Please note i used 100 as an example to convert to date time. You can use below link to see if its behaving correctly. link -https://www.w3schools.com/sql/func_sqlserver_convert.asp
select *
from tbl_skip
where sent_date > convert(datetime,'9/27/2020 7:29:11 PM',100)
ORDER BY CONVERT(datetime,SENT_DATE,100) desc
You should be able to convert it to a datetime
select *
from tbl_skip
where sent_date > '9/27/2020 7:29:11 PM'
order by convert(datetime,SENT_DATE) desc
Just make sure the data in column is legit. If so, it would make sense to convert the column type to a datetime.
alter table tbl_skip alter column SENT_DATE datetime
If the data is mixed, you may need to fix it or use something like
order by try_convert(datetime,SENT_DATE) desc

SELECT min date for a varchar column

The date column of my table is VARCHAR not datetime.
Eg
entry
'03/01/2011'
'03/22/2011'
'05/22/2010'
when I do a
SELECT min(entry) FROM table
I will get '03/01/2011' as it is the min in alphabetical order. I want to retrieve '05/22/2010' instead which is the min date. How do I convert the column to datetime and get the min.
Thanks
Assuming all entries are 'castable' as datetime:
SELECT MIN(CAST(entry as datetime))
FROM table
Assuming there might be some cases where entry isnt a datetime:
SELECT MIN(CAST(ISNULL(NULLIF(ISDATE([entry]),0),'31/12/9999') as datetime))
FROM table
If all records are a date column, as #Steve Wellens recommended, I would change the datetype to a datetime field to save future problems
I would fix your database schema. Change the column type to a datetime. Otherwise you'll have problems forever.
Make your varchar a date (or datetime) by using CAST or CONVERT of course.
Try CASTing it.
SELECT min(CAST(entry AS DATETIME)) FROM table
Hope this helps.

SQL Server 2005 - Add Milliseconds column onto DateTime column

How do i combine 2 column using SQL server 2005 ?
Problem is that The DateTime is stored in 1 column and the milliseconds is stored in another column.
I want to add the Milliseconds onto DateTime column to give it a more accurate DateTime.
I need to use this DateTime to query record accurate to milliseconds.
Any idea?
I need to replace DateTime with the added values.
SELECT *
FROM TABLENAME
WHERE [DateTime] >= '2011-04-12 12:00:00 AM'
AND [DateTime] <= '2011-05-25 3:35:04 AM'
and run the query.
Well, first solve your problem:
SELECT DATEADD(millisecond,<milliscolumn>,<datetimecolumn>) from <table>
And then file a bug report that these should just be stored in one column anyway.
You can do this, based on your sample query, but note that this destroys the possibility of the server being able to use an index:
SELECT * FROM TABLENAME WHERE
DATEADD(millisecond,[MillisecondColumn],[DateTime]) between
'2011-04-12T12:00:00' AND '2011-05-25T03:35:04'
If this is a large table, then indexes may be important. If you can't alter whatever's populating this data, you might want to add this calculation as a persisted computed column to this table, and then index and query against that.
Note that I've replaced your two comparisons with a single BETWEEN, and also adjusted the datetime strings so that they're not affected by regional settings.
SELECT (ColumnA + ColumnB) AS ColumnZ
FROM Table
might solve your problem.

inserting only date in a column in sql server

Is there a way to insert only date in a datetime column in sql server without the time?
for example
date (datetime)
===============
12-01-2000
16-02-2000
or i should store this as a varchar and cast it when retriving so that i can convert to whatever form i need.
my solution is to store it as varchar and convert it to datetime whenever needed
SELECT CONVERT(VARCHAR(10),GETDATE(),111) -- get datepart only
or
also check this post about creating date type :
create user defined data types:
create type Date from dateTime
http://weblogs.sqlteam.com/jeffs/archive/2007/10/31/sql-server-2005-date-time-only-data-types.aspx
If you are using SQLServer 2008 you can use the date data type.
The following SQL will strip out any time values and set them all to zero. So you won't need to worry whether a time value is there or not.
Select Cast(Floor(Cast(MyDateColumn as float)) as DateTime) as MyDateColumn
From dbo.MyTable
Just use smalldatetime or date. Convert your dates to your format before you update your date values or after you select date values in your app.
You can change format of date format in sql queries or in your app.
Here is a list on date formats in sql
http://www.sql-server-helper.com/tips/date-formats.aspx
Here's a link on date data types
http://databases.about.com/od/sqlserver/a/date_time.htm
Good Luck!

extract date from datetime stamp

Anyone know how to extract the date from a datetime stamp as part of the where clause?
eg.
select *
from tableA
where date between '01/08/2009' and '31/08/2009'
(Date is a timestamp!)
Many thanks,
Fiona
If this is sql server, it's not possible. The timestamp data type's name is misleading, as it does not store any date information of any kind. All it holds is a sequential value that allows you to establish record order (eg, item A was created before item B), and therefore you don't have enough information in that column alone to know on what day the row was created.
Since the link I provided is Sql Server 2000 specific, also check this link for information on SQL Server 2008:
http://msdn.microsoft.com/en-us/library/ms182776.aspx
timestamp is the synonym for the rowversion data type and is subject to the behavior of data type synonyms. In DDL statements, use rowversion instead of timestamp wherever possible.
To build a real timestamp column in Sql Server, use a DateTime (or DateTime2) data type and set it's default value to getdate() or current_timestamp.
If a real datetime value, not TIMESTAMP/ROWVERSION which is binary(8)...
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, #MyValue), 0)