Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

How do you add a CONSTRAINT for a VARCHAR(10) column to checks the Date format as yyyy/mm/dd

$
0
0
I have tried:
ALTER TABLE dbo.tablename
ADD CONSTRAINT DF_Date_format
check (SDate LIKE '%[1-2][0-9][0-9][0-9]/[0-1][0-9]/[0-3][0-9]%')
******But this does not work for VARCHAR data type ********

and

I also tried creating a function as shown below but I got an error when trying to add a constraint with this function.
(error is:
'The ALTER TABLE statement conflicted with the CHECK constraint "DF_Date_format". The conflict occurred in database " databasename ", table "dbo.tablename", column 'Date'.)


Create FUNCTION [dbo].[CheckDateFormat]
(@Date varchar(10))
Returns BIT
AS
BEGIN
Declare @RETURN BIT


SELECT @Return =
Case when (substring (@Date, 5, 1) + substring (@Date, 8, 1)) = '//'
then 0
else 1
end

Return @Return
END


ALTER TABLE dbo.tablename
ADD CONSTRAINT DF_Date_format
check
( dbo.CheckDateFormat(SDate) = 0 )

Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>