SQL Server - Calculate Age from date of birth in Varchar - sql-server

Using SQL Server 2008 R2
I have a database of my friend's project. He used varchar to store date of birth of members because he was getting errors parsing entries to date. I want to show the age using a procedure code.
the format of date stored in mm/dd/yyyy where today's date is stored as 3/4/2016 . I wanted to use DATEDIFF function but it is not a good option with varchar.

Create procedure spCalculateAge
#dob varchar(10)
as
Begin
Select DATEDIFF(year,Convert(date,#dob),getdate()) as Age
End
I used this and it worked. Before it was giving conversion error but opening and closing SQL Server caused it to work.

Related

Error in SQL Server Agent: "the conversation of a varchar data type to a datetime data type resulted in an out-of-range.""

I created a small script that works in SQL Server Management Studio, then I created a SQL Server Agent job with that same script; but after I run it, I get an error:
The conversation of a varchar data type to a datetime data type resulted in an out-of-range
I fixed the problem by change the format of date to ISO 8601, but I don't release how my first script works on SSMS and not in SQL Server Agent.
First script:
declare #teste datetime
set #teste = '31/12/2099 00:00:00'
select #teste
Fix error:
declare #teste datetime
set #teste = '20991231 00:00:00'
select #teste
This is one reason why using unambiguous formats are so important when using date(time) datatypes. The only formats that an unambgious in SQL Server, regardless of language and datatype are the formats yyyyMMdd and yyyy-MM-ddThh:mm:ss.
For the date '31/12/2099 00:00:00' and the language your Login is using it appears that SQL Server is interpreting the value as the 12th day, of the 31st month, of the year 2099. There aren't 31 months in the year, and hence the error. (DB<>Fiddle). It's worth noting that date (and the other "new" datetime data types) behave differently and also can unambiguously understand the format yyyy-MM-dd; notice in this DB<>fiddle the difference in the values for the datetime values simply due to the language setting.
As you can see, the solution is to use a unambiguous format. So, as you're using a date and time, I would suggest the string '2099-12-31T00:00:00'.

Importing Flat File into SQL Server stores incorrect dates In the database

I am a SQL student who has been tasked with loading data into SQL Server for a company that I intern with.
I have tried loading multiple flat files with dates formatted as 1/23/04 into SSMS and when going through the wizard the dates preview correctly. Once they're loaded into the actual database and a select query is performed, all dates return as 2023-01-04 format.
I'm not sure where to even begin to fix this. I've loaded columns as nvarchar(50) as opposed to date, datetime, and datetime2 to see if it would make a difference, and each case returns the same format. Is this a setting in the flat file, SSMS, or the computer itself?
In SSIS bring in the column (with the dates) as a string and add a derived column transform that will transform the column (using the substring function) to the correct date. SQL Server loves seeing dates as YYYY-MM-DD so that is why without explicitly telling it how to read the string it defaults to thinking that the inputted date is of that format.
If you are using SQL Server (SSMS) you should input it as a string (char(8)) and then use cast or convert functions to change the string into a date. You can then issue a 'Alter table drop column' to drop the string version column of the date.

SQL Server stored procedure: datetime parameter is wrong format sometimes depending on dateformat of country

This SQL Server stored procedure takes several parameters, and one of them is a datetime data type.
We've just began to localize the application in Europe, and the problem is that they're receiving this:
Error converting data type nvarchar to datetime.
I've done my reading on datetime, so I believe what is happening is the application is posting the date as dd/mm/yyyy to SQL Server, but since the database has a default language of English and expects mm/dd/yyyy, there is an error.
Sample input that produces error:
#LastUpdatedDate = N'21.01.2016 03:54:08'
My coworker in Europe said that when he set the default language of the database to German, the error quit occurring.
This error has not shown up in the USA/Canada, and I'm assuming that if the application AND SQL Server are running the same default datetime format, then no issues. However, we (here in USA), need to work with their application and database in Europe, so now we get the error.
Here's the stored procedure:
CREATE PROCEDURE [dbo].[addUser]
(
#UserID NVARCHAR ( 50 ),
#AccountID NVARCHAR( 50 ) = '00000000000000000000000000000000',
#Password NVARCHAR( 50 ),
#FirstName nvarchar(50),
#LastName nvarchar(50),
#Telephone nvarchar(25),
#Mobile nvarchar(25),
#FAX nvarchar(25),
#EmailAddress nvarchar(50),
#CurrentUserID nvarchar(50),
#LastUpdatedBy nvarchar(50),
#LastUpdatedDate datetime
)
AS
BEGIN TRANSACTION
INSERT INTO tbUsers (UserID, AccountID, Password, Status, VPID, EvalStatusID, FirstName, LastName, Telephone, Mobile, FAX, EmailAddress, LastUpdatedBy, LastUpdatedDate)
VALUES (#UserID, #AccountID, #Password, 'A', 'PM', 'ACTIVE', #FirstName, #LastName, #Telephone, #Mobile, #FAX, #EmailAddress, #LastUpdatedBy, #LastUpdatedDate)
I don't have access to the application code yet, but question is:
Is there a way to catch the error and fix the datetime input value depending on how database is configured?
I tried using SET DATEFORMAT dmy before the BEGIN TRANSACTION, but it errors out before that.
Yes, we could probably alter the application code to use a language-neutral datetime format, but that may not be feasible.
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.
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
Update: if you're on SQL Server 2012 or newer, you could use the new TRY_PARSE function in T-SQL which allows you to parse strings representing dates safely. You can specify a locale to use, and if the parse doesn't work, you get back a NULL instead of an exception.
Try this:
DECLARE #input NVARCHAR(100) = N'21.01.2016 03:54:08'
SELECT
TRY_PARSE(#input AS DATE USING 'en-gb')
Should return a valid DATE value of Jan-21, 2016 - no matter what language/locale your SQL Server is set to

Converting various date formats into a single date object

I have a table in SQL Server 2008 R2 with a nvarchar(50) column which stores different formats of date such as 'dd/mm/yyyy', 'mm/dd/yyyy', 'yyyy-mm-dd', etc.
Now I am writing a procedure that will convert/cast this column as a date type. Something as below:
SELECT CONVERT(DATE, Column1) as [Date]
But due to varying formats of date I tend to get the following error in my C# application:
"Conversion failed when converting date and/or time from character string"
I know of a function TRY_CONVERT and TRY_PARSE which can solve this problem but it's only available in SQL Server 2012 and above. Any workaround for this in SQL Server 2008?

Inserting CDate to SQL Server 2012 Flip Day and Month

I have a problem inserting a date from a VB.net Program to a SqlServer2012 instance.
First here is how i generate the data (Vb.net)
ExitTime = CDate("1.1.1970 00:00:00").AddSeconds(currentField).ToLocalTime
We add this value to a stored procedure (Vb.net)
With comsql5.Parameters.AddWithValue("#ExitTime", ExitTime)
In the Sql Server stored procedure
#ExitTime datetime, [...]
[...]
Insert into [table] ([ExitTime]) VALUES (#ExitTime)
Here is the output of the exit time in the vb.net
Exit Time : 08/07/2014 2:06:31 PM
Here is the same row in the Sql server database
2014-08-07 14:06:31.000
What I would like to see in the database is 2014-07-08 14:06:31.00
Because another part in the program does a check on the field but as a String... and it does not match because it flip the month and day
EDIT: TO be clear, I can't change the other part that does the comparison as a string. I know this is a poor way to compare datetime.
Thank for your time
Have you tried using the Convert function?
SELECT CONVERT (VARCHAR, getdate(), 121);
Check this links for more information MSDN - CAST and CONVERT and SQL Server Datetime Format

Resources