I have created a check constraint in SQL Server 2005, but this check constraint doesn't work. The SQL Server Management Studio tells me by an insert statement the following message:
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the CHECK constraint "MY_CHECK_CONSTAINT". The conflict occurred in database "MY_DB", table "dbo.MY_TABLE", column 'MY_COLUMN'.
I have added the check constraint with the following code:
ALTER TABLE MY_TABLE WITH NOCHECK
ADD CONSTRAINT CK_MY_CHECK_CONSTRAINT CHECK (dbo.MY_FUNCTION(MY_PARAMETER)<1)
The calling function "MY_FUNCTION" returns an int.
My target is that if my function returns an int which is less than 1 the insert statement can successfully be completed and if the return value is bigger than 0 the insert statement has to be terminated.
My problem now is that my function returns the value 0 but the insert statement has been terminated always. What am I doing wrong?
The code of my function is the following:
CREATE FUNCTION MY_FUNCTION(@MY_PARAMETER uniqueidentifier)
RETURNS int
AS
BEGIN
declare @return int = 0
SET @return = (SELECT COUNT(MY_COLUMN) FROM MY_TABLE WHERE MY_COLUMN= @MY_PARAMETER )
return @return
END
Thanks for your help.