Should we explicitly convert datetime to date or let SQL Server handle it - sql

I'm using SQL Server 2008. I have declared a variable as Date. My table has a Datetime column which I'm fetching. When I assign the datetime to date variable, I only get a Date. Everything works good. But are there any performance implications of assigning DateTime to a Date variable without Convert/Cast and letting SQL Server handle it? Or is it advisable to Convert/Cast before we assign?

Conversion from Datetime to Date is type of implicit conversion and it is defined in SQL server conversion so you do not need to be worry about conversion.
Obviously SQL Server would be using best bay of conversion for this so there is no need to add extra overhead of conversion. Because the conversion method we use has been defined for explicit conversion.

Related

Explicitly convert datetime to varbinary

I am attempting to convert a datetime column to varbinary(100), but haven't had any luck. My problem is very similar to Convert datetime to varbinary inside update query, but I still wasn't able to develop a solution.
Here is my code:
OPEN SYMMETRIC KEY SymKey_TheDate_SYMMETRIC
DECRYPTION BY CERTIFICATE Certificate_TheDate_Encryption
UPDATE PROFILE_DATA
SET A29_FDATE = EncryptByKey (Key_GUID('SymKey_TheDate_SYMMETRIC'), CONVERT(varbinary(100), A29_FDATE))
FROM PROFILE_DATA
GO
CLOSE SYMMETRIC KEY SymKey_TheDate_SYMMETRIC
Here is the error I get when trying to convert A29_FDATE from datetime to varbinary(100):
Implicit conversion from data type varbinary to datetime2 is not allowed. Use the CONVERT function to run this query.
Your error is not for datetime to varbinary(100), but for varbinary to datetime2. The function EncryptByKey() returns a varbinary that is assigned to a date field A29_FDATE. The output of EncryptByKey() needs explicit conversion if you are going to attempt it.
Something like:
...
SET A29_FDATE = convert(datetime2(0), EncryptByKey(...))
...
Re-read your error:
Implicit conversion from data type varbinary to datetime2 is not allowed. Use the CONVERT function to run this query.
You get a varbinary value just fine. The error is converting it to datetime2. The statement is converting it to datetime2 when it tries to set the field 'A29_FDATE` to the varbinary value. I assume from the field name it is a datetime2 field. I don't think you can or should convert this to a datetime2 field.
If you are in the process of encrypting the field in your table, you will have to create a new column with the type varbinary, probably A29_FVARBIN (yuck), and update that to the result of your query. Then you can drop the A29_FDATE field if you want.

Database export fails when I try to export this format '2020-04-13 14:13:54'

When I try to execute this insert
INSERT INTO BCS_EXPEDIENTES_REGISTRADOS (FOLIO, DOCUMENTO, FECHA_REGISTRO_DPS, CANT_PAGINAS)
VALUES ('24', 'Suc4437_X722INSURGEN_20200305033042.tiff', '2020-04-13 14:13:54', '79')
I get an error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The process is:
I have a value example: 04/13/2020 09:13:41
I convert this value to this format: =format([G_RECEPCION], "yyyy-MM-dd HH:mm:ss") to 2020-04-13 14:13:54
But when I execute the INSERT, it throws that error.
Any ideas for this case? I need to export the datetime in this format on SQL Server yyyy-MM-dd HH:mm:ss
Let me start by saying that datetime has no concept of display format.
The display format is only relevant when we talk about the string representations of datetime values.
Then, lets take a look at the format you're using: yyyy-MM-dd HH:mm:ss (known as ODBC canonical).
When converting strings of this format to DateTime, the result of the conversion is culture dependent.
This means that when operating in some languages (like English) SQL Server will attempt to use yyyy-MM-dd as date, but in other languages (like German) it will attempt to use yyyy-dd-MM as date.
This is the the reason you get a conversion error.
Importent note: Unless you explicitly set the language (or DateFormat, for that matter), SQL Server will use the default language of the login - so for some users conversion might fail while for other users it will succeed.
Another note is that this problem only exists with DateTime, but not with DateTime2 - converting this format to DateTime2 will always be interpreted as yyyy-MM-dd.
So, considering all this information, you have three options here:
Stop using DateTime, use DateTime2 instead.
Instead of using the unsafe ODBC canonical format use the safe ISO8601 format whenever dealing with string representation of datetime values: yyyy-mm-ddThh:mi:ss.mmm.
Explicitly set language or date format (to ymd) before your insert statement.
I would recommend combining the first two and avoid using the third if possible.
DateTime2 is a better data type than DateTime, and ISO 8601 is the universal standard and is supported throughout different platforms and languages as an unambiguous datetime format.

Creating a custom data type with specific format

I'm moving from an access database to a SQL Server database and wanted to know if I can create my own data type for dates.
I want to have my custom date type to have a format of mm/dd/yyyy instead of yyyy/mm/dd. Is this possible to do?
Use the default/built-in data type to store a specific data type. This will be more efficient and reliable as sql server will only allow the valid data to be stored (data integrity).
Also this will allow you to make use of all the built-in functions to work with that specific data type. In your case if you use Sql Server's datetime data type you will be able to make use of all the datetime functions (DATEDIFF() , DATEADD() , DAY() , YEAR() , MONTH(), DATENAME() etc).
As far as how you see the date/datetime values stored in your database, again you will always have built-in datatime functions to format the date values as it suits you.
Once you have stored the date/datetime values in sql server database and you want to view date value as mm/dd/yyyy instead of yyyy/mm/dd simply do the following:
SELECT CONVERT(VARCHAR(10), [DateColumn], 101)
Custom datatypes are there to be used but there are some very odd issues with them, avoid them whenever you can :)

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: how to check for a specific DateTime

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.