I need to do a SELECT in my SQL Server 2008 database and I'm not getting it.
I need to convert a date to the formatted yyyy/MM/dd HH:mm:ss
, however I need to convert it somehow that works on any SQL Server from 2008.
I need to do a SELECT in my SQL Server 2008 database and I'm not getting it.
I need to convert a date to the formatted yyyy/MM/dd HH:mm:ss
, however I need to convert it somehow that works on any SQL Server from 2008.
This code below is fully functional. Note that the convert is for varchar, but the DateTime type receives varchar values with no problems.
select convert(varchar,getdate(),121)
Another thing you can see is the formatting of dates per session, within the sql server command
SET DATEFORMAT dmy;
SELECT * FROM TABLE WHERE Campo > 0 AND Convert(varchar,DataHora,103) = '2016-03-15 16:50:25'
If your field is DateTime
you do not need to do varchar
conversions to put WHERE
, just send the date in 'yyyyMMdd hh:mm:ss'
format that SQL Server will recognize regardless of version or DATEFORMAT
that is on the server.
If the field is only of type date, just be in the format 'yyyyMMdd'
Example:
SELECT * FROM TABLE WHERE Campo > 0 AND DataHora = '20160315 16:50:25'
Or, if the field is just for date:
SELECT * FROM TABLE WHERE Campo > 0 AND Data = '20160315'
The problem with queries involving date is that you should remember that if the type includes date and time, you only get the equality result only if the date and time are the same. If you want to do a search only on the date regardless of the time, you have to do a WHERE with a track, for example:
SELECT * FROM TABLE WHERE Campo > 0 AND DataHora >= '20160315' AND DataHora < '20160316'