How to check if column having date of birth format has yyyymmdd in sql server? - sql

How to check if column having date of birth format has yyyymmdd in sql server?

You can verify with the ISDATE Function, but I don't know which SQL edition do you have
Example
select ISDATE ( 1 )
------------------
0
select ISDATE ( 11111111 )
------------------
0
select ISDATE ( 20170501)
------------------
1

You can use:
select (case when try_convert(date, dob) is not null and
try_convert(int, dob) is not null
then 1 else 0
end)
I'm not 100% sure, but I think that yyyymmdd is the only format that will generally pass both conditions. Note: There is no way to know if 20170601 is really June 1st or Jan 6th, so this cannot actually validate the contents of the field.
But why do you care what the format is, so long as you can convert it to a date? You should then change the column to a date type and henceforth know that the "format" is correct.

If the column is a Char type (yuck) then Like '[12][0-9][0-9][0-9][0-1][0-9][0-3][0-9]' (off the top of my head)
If it's a DateTime then who cares, it's a date.

Related

Handling a value of zero in a date datatype

I'm reporting out of a database that is using decimal(17,6) as the datatype for a date field. For example, the current date/time in this field would be 20210820.171900. Unusual, but whatever. I need to convert the original date field from decimal(17,6) to datetime. This is what I have:
SELECT convert(datetime, convert(varchar,convert(int, lastmoddatetime)), 0)
from Table1
The above statement works correctly as long as none of the records have a value of zero in this column. Unfortunately, the column value defaults to zero (0.000000) if no date has been calculated for it. Whenever a column has a zero value, I get the following error:
Conversion failed when converting date from character string.
How can I overcome this issue? Ultimately, I'm needing to apply a dateadd function to the lastmoddatetime field.
Note: Before you suggest changing the column definition, this database originated in the 1990's and I'm not allowed to make any changes to the database structure.
You can use NULLIF to null out those values
convert(datetime, convert(varchar(15), convert(int, NULLIF(lastmoddatetime, 0.0))), 0)
Either use TRY_CONVERT or CASE - depending how you want to handle the zero case.
SELECT
-- If desiring null for 0 and SQL Server 2012+
TRY_CONVERT(date, CONVERT(varchar, CONVERT(int, lastmoddatetime)), 0)
, CASE WHEN lastmoddatetime <> 0
-- If desiring some other valid date or < SQL Server 2012
THEN CONVERT(date, CONVERT(varchar, CONVERT(int, lastmoddatetime)), 0)
ELSE NULL /* Whatever valid datetime value you want */ END
FROM (
VALUES (20210820.171900), (0.0)
) x (lastmoddatetime);
I note that this ignores the time component - so am converting to a date not datetime above. If you need to handle the time component you need to update your question.
Yet another option.
You can thin it out a bit by using left() and try_convert()
Example
Declare #YourTable table (lastmoddatetime numeric(17,6))
Insert into #YourTable values
(20210820.171900)
,(0.0)
Select AsDate = try_convert(date,left(lastmoddatetime,8))
,AsDateTime = try_convert(datetime,left(lastmoddatetime,8))
From #YourTable
Results
AsDate AsDateTime
2021-08-20 2021-08-20 00:00:00.000
NULL NULL
use
convert(datetime,convert(int,lastmoddatetime),0)

Convert and Operation Not working as expected. Ignoring Year value

I have the following code:
CONVERT(VARCHAR(20), TimeCard_Date, 101) <
CONVERT(VARCHAR(20), dateadd(dd,-3,getdate()), 101)
The Original TimeCard_Date value = 2018-06-01
The GetDate() return = 11/14/2017
Can anyone assist as to why it thinks the Timecard_Date value set for June 2018 is less than the GetDate() minus 3 days value?
When you convert, it converts to a varchar datatype. 06/01/2018 is less than 11/14/2017 as a varchar since it is an alphabetical (or by number?) comparison. If you compare by date, the comparison is by the date datatype, which is as you expect.
You can change your code to:
TimeCard_Date < dateadd(dd,-3,getdate())
You don't need to convert DATETIME to VARCHAR in order to compare dates. Just use:
TimeCard_Date < DATEADD(dd,-3,GETDATE())
On the other hand, if you ever have to convert them to do it, you have to standarize the format (yyyyMMdd). You can check the FORMAT function https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql

Regular expression for mm/yy in Microsoft SQL Server

I am trying to execute a regular expression in SQL Server to match a MM/YY formatted VARCHAR string.
I have tried
WHERE ExpiryDate LIKE '[0-9][0-9]/[0-9][0-9]'
which allows incorrect dates like 30/18.
I also tried
WHERE ExpiryDate LIKE '0[1-9]|1[012]/[0-3][0-9]'
But SQL Server does not accept pipe separated as an OR operator.
I need the month to match 01 - 12
I can do
WHERE ExpiryDate LIKE '0[1-9]/[0-9][0-9]'
OR ExpiryDate LIKE '10/[0-9][0-9]'
OR ExpiryDate LIKE '11/[0-9][0-9]'
OR ExpiryDate LIKE '12/[0-9][0-9]'
but I would prefer it to be within the regular expression.
Thanks in advance for any help.
If 2012+, you could use try_convert() to convert the expiration string into a date. Try_Convert() will return a NULL value if the conversion fails.
Example
Declare #YourTable table (ID int, ExpiryDate varchar(25))
Insert Into #YourTable values
(1,'09/17')
,(2,'30/17')
Select *
From #YourTable
Where try_convert(date,replace(ExpiryDate,'/','/01/')) >= '2017-09-01'
-- Where try_convert(date,replace(ExpiryDate,'/','/01/')) is null
Returns
ID ExpiryDate
1 09/17
If you need to convalidate dates, you could try something like this:
SET DATEFORMAT dmy
;WITH A AS (SELECT '18/12' AS EXPDATE UNION ALL SELECT '10/17' UNION ALL SELECT 'x2/16' )
SELECT *, ISDATE('01/'+EXPDATE) AS CHK FROM A
Output:
EXPDATE CHK
18/12 0
10/17 1
x2/16 0
date LIKE '0[1-9]/[0-9][0-9]' OR
date LIKE '1[0-2]/[0-9][0-9]'
Is much shorter. But without | it is hard to make variants... Notice, that LIKE takes not regexes, but wildcards.
Don't forget, that '[1-9]/[0-9][0-9]' can also happen. And other variants, with inner spaces and so on. If you are not absolutely sure in month format used, and don't depend on high speed, use #JohnCampeletti variant.

Convert VARCHAR to DATE in SQL SERVER

I have VARCHAR column (MyValue) in my table. It has date value in two different format.
MyValue
----------
25-10-2016
2016-10-13
I would like to show them in DATE format.
I wrote query like below:
SELECT CONVERT(date, MyValue, 105) FROM MyTable
SELECT CAST(MyValue as date) FROM MyTable
Both are giving me this error. Conversion failed when converting date and/or time from character string.
Is there anyway convert to DATE datatype format even the value stored in different formats like above?
Expecting your answers. Thanks in advance.
Does this help?
declare #varchardates table
(
vcdate varchar(20)
)
INSERT INTO #varchardates VALUES
('25-10-2016'),
('2016-10-13')
SELECT CONVERT(date,vcdate, case when SUBSTRING(vcdate, 3, 1) = '-'
THEN 105 ELSE 126 END) as mydate
FROM #varchardates
Depending on how many different formats you have in your data, you may need to extend the case statement!
See here for list of the different format numbers
You can use TRY_CONVERT and COALESCE. TRY_CONVERT returns NULL if the conversion fails, COALESCE returns the first NOT NULL value:
SELECT COALESCE(TRY_CONVERT(DATETIME, x, 105), TRY_CONVERT(DATETIME, x, 120))
FROM (VALUES('25-10-2016'), ('2016-10-13')) a(x)
I assumed the value 2016-10-13 is in format yyyy-MM-dd.
You mention in a comment you may have other formats as well. In that case it gets very tricky. If you get a value 01-12-2017 and you have no idea about the format, there is no way to tell whether this is a date in januari or in december.

How to convert GetDate() in 1 Jan 2014 format?

I using a query where I am selecting some attributes from the table based on a where condition. My where condition is-
date>GetDate();
I have tried this-
SELECT TOP 2 img,name,substring(description,1,80) as
description,Convert(nvarchar,date,106) as date
FROM tbl_test
where date>=Convert(nvarchar,GetDate(),106)
order by date Asc;
This query is running fine but showing different result as compared to a different query of similar kind in which I am not converting the date format.
SELECT TOP 2 img,name,substring(description,1,80) as description,date
FROM tbl_test
where date>=GetDate()
order by date Asc;
Please guide me where I am doing wrong?
Your first query will convert getdate() into nvarchar data type and it will compare date with string while 2nd query will compare 2 dates. So 2nd option is better. Still if you want to convert date into string then check then use 102 format like
WHERE CONVERT(varchar(20),date,102) >= CONVERT(varchar(20), getdate(),102)
For select column you can use format which you want like
SELECT CONVERT(varchar(20),date,106)
Final Query is :
SELECT TOP 2
img,
name,
SUBSTRING(description,1,80) as description,
CONVERT(varchar(20),date,106) as [DisplayDate]
FROM tbl_test
WHERE CONVERT(varchar(20),date,102) >= CONVERT(varchar(20), getdate(),102)
ORDER BY date ASC;
Without convert to varchar, you can cast getdate() to date to remove time part :
SELECT TOP 2
img,
name,
SUBSTRING(description,1,80) as description,
CONVERT(varchar(20),date,106) as [DisplayDate]
FROM tbl_test
WHERE date >= CAST(getdate() as date)
ORDER BY date ASC;
SQL Fiddle Demo
DECLARE #Date Datetime;
SET #Date = GETDATE();
SELECT CONVERT(VARCHAR(12), #Date, 113) AS Date
RESULT
╔══════════════╗
║ Date ║
╠══════════════╣
║ 01 Jan 2014 ║
╚══════════════╝
Edit
as Upendra Chaudhari has explained that when you do comparing column Date with a string =Convert(varchar(20),GetDate(),102),
what is actually happening behind the scenes is Convert(varchar(20),GetDate(),102) returns a string 2014.01.01 but to compare this string with a Datetime column SQL Server does an implicit conversion to compare both values. Sql Server have to have both values in the same datatype to compare them.
Now datatype Datetime has Precedence over nvarchar/varchar datatype so sql server converts the string into datetime datatype which returns something like
SELECT CAST('2014.01.01' AS DATETIME)
Result : 2014-01-01 00:00:00.000
Now in this process of converting your values to string and then back to datetime you have actually lost all the time values in your comparing values. and this is the reason why you are getting unexpected results back.
so make sure whenever you are comparing to have exactly the same datatype on both sides and take control of any data conversions in your code rather then sql server doing datatype conversions for you.
I hope this will explain you why you are getting different results .
You may try:
where date>=CONVERT(VARCHAR(11), GETDATE(), 113)