Click here to Skip to main content
15,901,035 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all,

I need to do a check in sql - to find wheteher the supplied string is in the form 'YYYYMMdd'

please help me to do this.

@datepart varchar(10) 
@datepart = '20130611'

i need to check the @datepart is in the form - YYYYMMdd.

Thanks in advance,
Posted
Updated 23-Jun-13 22:54pm
v2

You can do it using Regex[^].
Have a look here:
Regular Expressions Make Pattern Matching And Data Extraction Easier[^]
Search Text with Regular Expressions[^]
Working with Regular Expressions[^]

Another way is to define pattern with LIKE[^] and PATINDEX[^] keyword:
Pattern Matching in Search Conditions[^]

Or
Using CONVERT[^] function ;)
Example:
SQL
DECLARE @myStringDates TABLE (myDate VARCHAR(30))

INSERT INTO @myStringDates (myDate)
SELECT '20130618' AS myDate
UNION ALL SELECT '18062013'
UNION ALL SELECT '06182013'

SELECT myDate
FROM @myStringDates
WHERE (CONVERT(INT, LEFT(myDate,4)) BETWEEN 1901 AND 2013) AND
	(CONVERT(INT, SUBSTRING(myDate,5,2)) BETWEEN 1 AND 12) AND
	(CONVERT(INT, SUBSTRING(myDate,7,2)) BETWEEN 1 AND 31)

Result:
20130618
 
Share this answer
 
Check bellow e.g

SQL
IF ISDATE('20130611') = 1
    PRINT 'VALID'
ELSE
    PRINT 'INVALID'
 
Share this answer
 
Comments
SruthiR 24-Jun-13 6:34am    
this checks only if the string is datestring. But i need to find the format YYYYMMDD.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900