Check subcategory id with main category using check constraint

Some time we have to insert in a foreign key reference table where we have to check subcategory id along with
main category id for that we can use CHECK CONSTRAINT

like below

1)First create a user defined function which will check main category id and sub category id from a view.


/****** Object:  UserDefinedFunction [dbo].[Check_S_MainCategory]    Script Date: 01/28/2015 13:30:29 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[Check_S_MainCategory] (
@TopMainId int,
@TopSubId int
)
RETURNS bit
AS 
BEGIN
   DECLARE @retval bit
   IF EXISTS(select * from VwTopMainSubcategory where TopMainID=@TopMainId AND 
   
   ISNULL(TopSubID,0)=
   CASE WHEN @TopSubId IS NULL THEN TopSubID ELSE
   ISNULL(@TopSubId,0) END) 
   BEGIN
   SET @retval=1
   END
   ELSE
   BEGIN
   SET @retval=0
   END
   RETURN @retval
END;
GO

2)Now create a check constraint like below

ALTER TABLE dbo.Admin_S_SubCategory
ADD CONSTRAINT chkSubSCatExist CHECK (dbo.Check_S_MainCategory(TopMainID,TopSubID) = 1 );

Now using check constraint while inserting and updating it will check the subcategory id along with main category id.

You Might Also Like

Leave a Reply