SQL: how to check for a specific DateTime - sql

i need to check for a specific DateTime value in my table from my code (VB.NET) and i don't know how to format the DateTime as a string. i've read that SQL Server will recognize my string if it's in either date, time, or date and time format. i mean:
'May 15, 2004'
'5/15/2004'
'20040515'
'2004 4 am'
will SQL Server recognize these strings as valid DateTime values? i'm curious because if i check the actual DateTime values in the table they are in this format:
2/2/2006 3:49:33 PM

Don't put the date/time value in the SQL query in the first place - use a parameterized query and then you don't need to know or care what format SQL Server would parse literals as. You put the placeholder in the SQL, and specify the value as a DateTime in the parameter collection.
You should be using parameterized SQL as a matter of course, in fact - not only does it get rid of formatting and parsing problems like this, but possibly more importantly it's the single most effective weapon against SQL injection attacks.

If not using a parameterized query, use CAST/CONVERT to explicitly change a string to a DATETIME:
SELECT CAST('2/2/2006 3:49:33 PM' AS DATETIME)
On my SQL Server 2005, that returns to me:
2006-02-02 15:49:33.000
Mind that the default date format in SQL Server can be different than what you provide.

This has always been safe that I have found:
YYYY-MM-DD HH:MI:SS

If you're comparing DateTime to DateTime, you don't have to worry about conversion, necessarilly, but yes, Sql Server (at least as of 2k8, and I believe 2k5 as well) will automatically parse a DateTime from a string. That is, if you pass '5/15/2004' it will see 5/15/2004 12:00:00 AM or something similar.
a better way, though, is to use SqlParameters in your SqlCommand from Code.

Related

How do I change the date in SQL Server 2017 to UK format?

I have got several tables in my database (with data) that is formatted in the American standard of mm/dd/yyyy. Is there a way to convert the date to a British format (i.e. dd/mm/yyyy) that doesn't involve dropping and recreating the tables?
Thanks!
I set my data type to >date when I was creating my table. I can store dates in the format mm/dd/yyyy, but not dd/mm/yyyy.
As I've mentioned in my comment, dates are not stored with their display format - in fact, you can say that dates have no display format - only string representation of dates have a display format.
Whenever dealing with string literals representing date and datetime values in SQL server, use ISO 8601 datetime format (yyyy-MM-ddTHH:mm:ss or yyyyMMddTHHmmss).
SQL Server guarantees to properly parse this string representation into date / datetime values, without ambiguity.
Please note the T seperator between the date and the time. There is a very similar standard format, where the T is replaced with a white-space, but the DateTime data type have a bug parsing this format - and it is culture-dependent (Note that DateTime2 does not have that bug) - and that's another reason why you should never use datetime again.
When you use a string literal like '25/03/2018' it's easy for a human to see that it stands for March 25th 2018, but SQL Server will raise an error trying to parse this string into a date if the current value of DATEFORMAT is not DMY.
However, SQL Server will always parse ISO 8601 string representation of dates correctly, regardless of any local settings or previous set dateformat or set language statements etc'. '2018-02-01T15:40:50' will always be parsed is February 1st 2018, 3:40:50 PM.
Unless specified, As Martin Smith wrote in his comment, the default dateformat depends on the defualt language settings of the current login - so a query that works for one login might raise an error for another login - and that's another good reason never to trust culture-specific string representation of datetime.
DECLARE #dt DATETIME = '01/20/2019';
SELECT FORMAT( #dt, 'd', 'en-gb' ) AS 'UK'
Are you referring to the date format displayed by SQL Server Management Studio or a similar application? The format is controlled by Windows Control Panel settings, not by SQL Server. There is no internal format for dates in SQL Server.
This is defined by default from the machine where is running MS SQL Server.
To see all available cultures please do:
select * from sys.syslanguages
Then, you can change SQL Server language using:
SET LANGUAGE BRITISH
... and the date format will always be like you want.
Note: this will change all the database (not just the date format), the other way is to change the date format using the FORMAT function in T-SQL.

Set timezone as IST (+5:30) in DB Browser for SQLite

I have been searching for a setting in DB BRowser for SQLite on how to change the timezone to IST (Indian Standard Time +5:30) Is there a way to set it directly without running any queries? I also found some SQL queries that can convert the db time to IST but almost all are SELECT statements. I am looking for a setting to change the timezone permanently and if that is not possible then may be an update query which can read all records in the database and change/convert/replace all times to IST. Can someone shed some light on it?
My field name is "expire_time" set as DATETIME NOT NULL in CREATE TABLE
What I searched for was
INSERT INTO MyTable(MyColumn) VALUES(datetime(CURRENT_TIMESTAMP, 'localtime'))
but I am not looking for insert statement
SELECT datetime(1092941466, 'unixepoch', 'localtime');
but I am not looking for select statement
Please help me either with a setting (if available in DB Browser for SQLite) or an update query that can change all times from GMT TO IST.
Thanks.
EDIT
SQLite has no DATETIME type. And it treats datatypes very different from other DBMS. For example
CREATE TABLE T (
Field MYTYPE
);
will run OK. Sqlite is applying so called datatype affinity https://www.sqlite.org/datatype3.html#affinity to figure out one of the implemented datatypes it will use instead of stuff specified it CREATE TABLE. DATETIME (as well as MYTYPE) affinity is NUMERIC - a special affinity which means column can store any type you want, TEXT for example.
This boils down the only way to work with DATETIME in Sqlite is datetime functions. And those functions use default timezone UTC. Any other timezone must be provided explicitly as a part of the datetime string. No PRAGMA or something to change this default.
EDIT
If expire_time is currently a string expression of UTC time you can get specific timezone text value, for example
select datetime(expire_time, '+05 hours','+30 minutes') || ' IST' as t
Note datetime(d,'utc') will most probably return NULL if string d contains explicit timezone. So i advice you standardize on storing datetime as UTC in DB and convert it to different timezone needed only when generating an output. This way you have all Sqlite toolbelt at your disposal.

Change Datetime format in Microsoft Sql Server 2012

Hi i want to change the default datetime type in sql server. I have already table who has rows and i dont want to delete them. Now the datetime format that had rows is: 2015-11-16 09:04:06.000 and i want to change in 16.11.2015 09:04:06 and every new row that i insert i want to take this datetime format.
SQL Server does not store DATETIME values in the way you're thinking it does. The value that you see is simply what the DBMS is choosing to render the data as. If you wish to change the display of the DATETIME type, you can use the FORMAT() built-in function in SQL Server 2012 or later versions, but keep in mind this is converting it to a VARCHAR
You can get the format you desire via the following:
SELECT FORMAT(YourDateField, N'dd.MM.yyyy HH:mm:ss')
There is no such thing as format of the DATETIME data type, it has no format by nature, formatted is the text representation you can set when converting to VARCHAR or some visualization settings of the client / IDE.
If you, however, want to be able to insert dates using string representations that are alternatively formatted (i.e. control the way string input is parsed to datetime type) you can check SET DATEFORMAT - as explained in the remarks section this will not change the display representation of date fields / variables.
SQL serve provide wide range of date formatting function or way by using that user can change date format as per his requirement.
Some of are giver bellow.
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)

How do you convert SQL mm/dd/yy to mm/dd only?

How do you convert SQL mm/dd/yy datetime to mm/dd only? On Microsoft server.
Thanks all.
With dates and times it is an extremely common mistake to believe that what you see is what is stored. If the field is date, datetime, smalldatetime or datetime2 then what is stored are integers, not strings. So if the field is one of these, then:
convert(varchar(5),[date_field],1)
or
format([date_field],'MM/dd') -- mssql 2012 onward
If the information is a string already then left() will do the job.
Since you have specified an input format, the input must already be a string. Simply truncate with
cast(dateIn as char(5)).
You can use LEFT to just return the day and month:
SELECT LEFT('12/12/2000', 5)
I realize this isn't directly answering your question the way you asked it, but the best advice I can give is: Don't.
Instead, send back the field in its native datetime type. The database is not the place to be doing formatting. Instead, format the date in your application code.
For example, if you are calling SQL Server from a C#/.NET application, you could retrieve the value from a DataReader like this:
DateTime dt = (DateTime) reader["YourDateTime"];
Then you would format it as a string like this:
string s = dt.ToString("MM/dd");
This will ensure that the date is formatted correctly. If you are using a different language to call SQL Server, there are probably similar methods in that language.
One of the problems with the other approach mentioned (trunacating the string) is that the original value might not be formatted in mm/dd/yyyy to begin with. That all depends on the environment settings where the SQL Server is running. If you run the same code on an environment with dd/mm/yyyy settings, you would have unexpected results. This is avoided by using the native data type, the way I described.

SQL Server : error conversion of a varchar data type

I'm trying to run a SQL query however I'm getting an error
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Code:
SELECT
ClientId,
DatePassed,
Lender
FROM
dbo.tbl_Profile_Mortgage
WHERE
DatePassed = '2011-04-28 00:00:00.000'
I have converted the data type as so
SELECT
ClientId,
Convert (Date, DatePassed)
Lender
FROM
dbo.tbl_Profile_Mortgage
WHERE
DatePassed = '2011-04-28 00:00:00.000'
This however is still giving me the same error
Column DatePassed is of type datetime null
Any suggestions would be appreciated
Conceptually, you think the where clause is performed before the convert(). But that is not necessarily how the query is run. The only SQL statement that guarantees order of execution is case (and then not all the time).
You can try this:
SELECT ClientId,
(case when isdate(DatePassed) = 1 then Convert (Date, DatePassed) end),
Lender
FROM dbo.tbl_Profile_Mortgage
WHERE DatePassed = '2011-04-28 00:00:00.000';
EDIT:
Given that DatePassed is already in a date time format, then your error is highly unusual. This is not a problem from the conversion of this column, because no varchar is involved.
The only thing I can think of is the constant. Perhaps you have a strange setting for default dates and it is trying to get the 4th day of the 28th month. If so, you can readily fix this by putting in an explicit conversion with a format:
SELECT ClientId,
Convert(Date, DatePassed),
Lender
FROM dbo.tbl_Profile_Mortgage
WHERE DatePassed = convert(date, '2011-04-28 00:00:00.000', 121);
Aaron Bertrand has a rather extended discussion of this issue in his blog. By the way, even though I recognize the problem that he mentions with the YYYY-MM-DD format, I still use that by default. I consider it a bug that Microsoft has chosen not to recognize this ISO standard format (but just because I think it is a bug doesn't necessarily convince anyone else).
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not. I guess in your case, you're using a language setting that just plain doesn't work with that string literal you're using.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible.
In your concrete case - use this string in your WHERE clause:
WHERE DatePassed = '2011-04-28T00:00:00.000';
(notice the literal T between the date and time portions)