Showing posts with label FOREIGN KEY. Show all posts
Showing posts with label FOREIGN KEY. Show all posts

Tuesday, 25 August 2015

Generating Foreign Key Definition of Database

Introduction




All the DB Developer are like to use DB Diagram to design Database. They used drag and drop process to make the Foreign key references between the table. Quite easy… is it?





But the real problem is that when we are trying to generate the foreign key definition (Script) to deploy it in the Production DB. There is no shortcut method to get the definition of foreign key in entire DB. We can list the entire foreign key in a DB but not get the definition all together.



In this article I we are trying to create a Script which can generate the definition of the entire foreign key in the Database.
Hope you will find it informative.

To list all the Foreign key Constraint in Database

SELECT RC.CONSTRAINT_NAME FK_Name, KF.TABLE_SCHEMA FK_Schema,
       KF.TABLE_NAME FK_Table, KF.COLUMN_NAME FK_Column,
       RC.UNIQUE_CONSTRAINT_NAME PK_Name, KP.TABLE_SCHEMA PK_Schema,
       KP.TABLE_NAME PK_Table, KP.COLUMN_NAME PK_Column,
       RC.MATCH_OPTION MatchOption, RC.UPDATE_RULE UpdateRule,
       RC.DELETE_RULE DeleteRule
FROM    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
        INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KF
                         ON RC.CONSTRAINT_NAME = KF.CONSTRAINT_NAME
        INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KP
                         ON RC.UNIQUE_CONSTRAINT_NAME = KP.CONSTRAINT_NAME;

By this script we can list all the Foreign key and their related table objects.



Create Script

Now we are creating a Stored Procedure to generate the Definition of Foreign key constraint

BEGIN

    DECLARE @v_FK_Name     VARCHAR(Max),
            @v_FK_Schema    VARCHAR(Max),
            @v_FK_Table     VARCHAR(Max),
            @v_FK_Column    VARCHAR(Max),
            @v_PK_Name      VARCHAR(Max),
            @v_PK_Schema    VARCHAR(Max),
            @v_PK_Table     VARCHAR(Max),
            @v_PK_Column    VARCHAR(Max),
            @v_MatchOption  VARCHAR(Max),
            @v_UpdateRule   VARCHAR(Max),
            @v_DeleteRule   VARCHAR(Max);
                    
    DECLARE @v_TotalRecords BIGINT,
            @v_StartRecords BIGINT;

    DECLARE @v_SQLScript   VARCHAR(Max);

      
    IF OBJECT_ID('tempdb..#temp_FKDefination')IS NOT NULL
          DROP TABLE #temp_FKDefination;

    CREATE TABLE #temp_FKDefination
        (
            Defination            VARCHAR(Max)
        );
                                          
    IF OBJECT_ID('tempdb..#tbl_FK')IS NOT NULL
          DROP TABLE #tbl_FK;

    SELECT    ROW_NUMBER() OVER(ORDER BY  RC.CONSTRAINT_NAME) AS SrlNo,
              RC.CONSTRAINT_NAME FK_Name, KF.TABLE_SCHEMA FK_Schema,
              KF.TABLE_NAME FK_Table, KF.COLUMN_NAME FK_Column,
              RC.UNIQUE_CONSTRAINT_NAME PK_Name, KP.TABLE_SCHEMA PK_Schema,
              KP.TABLE_NAME PK_Table, KP.COLUMN_NAME PK_Column,
              RC.MATCH_OPTION MatchOption, RC.UPDATE_RULE UpdateRule,
              RC.DELETE_RULE DeleteRule
    INTO    #tbl_FK
    FROM    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KF
                        ON RC.CONSTRAINT_NAME = KF.CONSTRAINT_NAME
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KP
                        ON RC.UNIQUE_CONSTRAINT_NAME = KP.CONSTRAINT_NAME;

    SET  @v_TotalRecords = (SELECT COUNT(*) FROM #tbl_FK);
    SET  @v_StartRecords = 1;

    WHILE @v_StartRecords <=  @v_TotalRecords
         BEGIN
             SELECT  @v_FK_Name = FK_Name,
                     @v_FK_Schema = FK_Schema,
                     @v_FK_Table = FK_Table,
                     @v_FK_Column = FK_Column,
                     @v_PK_Name = PK_Name,
                     @v_PK_Schema = PK_Schema,
                     @v_PK_Table = PK_Table,
                     @v_PK_Column = PK_Column,
                     @v_MatchOption = MatchOption,
                     @v_UpdateRule = UpdateRule,
                     @v_DeleteRule = DeleteRule
              FROM    #tbl_FK
              WHERE   SrlNo = @v_StartRecords;
      
       SET @v_SQLScript = '';
              SET @v_SQLScript = 'ALTER TABLE ['+ @v_FK_Schema +'].[' + @v_FK_Table +']'; 
               SET @v_SQLScript = @v_SQLScript + ' WITH NOCHECK ADD  CONSTRAINT ['+ @v_FK_Name +']';
              SET @v_SQLScript = @v_SQLScript + ' FOREIGN KEY(['+ @v_FK_Column +'])';
              SET @v_SQLScript = @v_SQLScript + ' REFERENCES ['+ @v_PK_Schema +'].[' + @v_PK_Table +']';
              SET @v_SQLScript = @v_SQLScript + ' (['+ @v_PK_Column +'])';
                 
               INSERT INTO #temp_FKDefination (Defination)
              VALUES ( @v_SQLScript );

              SET @v_SQLScript = 'ALTER TABLE ['+ @v_FK_Schema +'].[' + @v_FK_Table +']';
              SET @v_SQLScript = @v_SQLScript + ' CHECK CONSTRAINT ['+ @v_FK_Name +']'


              INSERT INTO #temp_FKDefination (Defination)
              VALUES ( @v_SQLScript );

              SET  @v_StartRecords = @v_StartRecords + 1;

        END

         SELECT * FROM #temp_FKDefination;

END
GO

Output is:



Analyze the Output

If we analyze the output we find

ALTER TABLE [dbo].[CancerHistory] WITH NOCHECK
ADD  CONSTRAINT [FK_CancerHistory_MasterSystemSiteOfRadiationTherapy]
FOREIGN KEY([idSiteOfRadiationTherapy])
REFERENCES [dbo].[MasterSystemSiteOfRadiationTherapy] ([idSiteOfRadiationTherapy]);

ALTER TABLE [dbo].[CancerHistory]
CHECK CONSTRAINT [FK_CancerHistory_MasterSystemSiteOfRadiationTherapy];



Hope you like it.



Posted By: JOYDEEP DAS


Sunday, 7 June 2015

Foreign key Relation Across Database


Introduction

As we all know about the foreign key reference. But what happens when we want foreign key references across the Database. This article is related to it. Hope, it will be informative.

Understand the Case
To understand it properly, we are trying to make a pictorial diagram.



Here we have a Microsoft SQL Server named DB Server that has two Database named DB1 and DB2. The DB1 database has a table named Table1 and DB2 database has a table named Table2. We are trying to make the Foreign Key relation between the Table1 and Table2.

Let’s Take an Example to understand it

Step-1 [ Creating the base table ]

USE [DB1];
GO

IF OBJECT_ID(N'[dbo].[tbl_ITEM]', N'U')IS NOT NULL
   BEGIN
       DROP TABLE [dbo].[tbl_ITEM];
   END
GO

CREATE TABLE [dbo].[tbl_ITEM]
       (
          ITEMCODE   INT             NOT NULL PRIMARY KEY,
          ITEMMNAME  VARCHAR(50)     NOT NULL
       );
GO

INSERT INTO [dbo].[tbl_ITEM]
       (ITEMCODE, ITEMMNAME)
VALUES (101, 'Tooth Paste'),
       (102, 'Tooth Brush'),
       (103, 'Saving Lootion');
GO

ITEMCODE    ITEMMNAME
----------- --------------------------------------------------
101         Tooth Paste
102         Tooth Brush
103         Saving Lootion

(3 row(s) affected)

USE [DB2];
GO

IF OBJECT_ID(N'[dbo].[tbl_ITEMORDER]', N'U')IS NOT NULL
   BEGIN
       DROP TABLE [dbo].[tbl_ITEMORDER];
   END
GO

CREATE TABLE [dbo].[tbl_ITEMORDER]
  (
    ORDERNO    INT            NOT NULL IDENTITY PRIMARY KEY,   
    ITEMCODE   INT            NOT NULL,
    QTY        DECIMAL(18,2)  NOT NULL
  );
GO

Step-2 [ Try to Creating the Foreign key Relation ]

ALTER TABLE [dbo].[tbl_ITEMORDER]
ADD CONSTRAINT FK_ITEMCODE_tbl_ITEMORDER FOREIGN KEY(ITEMCODE)
REFERENCES [DB1].[dbo].[tbl_ITEM](ITEMCODE);

It gives error.

Msg 1763, Level 16, State 0, Line 1
Cross-database foreign key references are not supported. Foreign key 'DB1.dbo.tbl_ITEM'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

So the Cross Database Foreign key Relation is not possible Directly.

Step-3 [ What the Solution ]

We can do the something by CHECK Constraint. Here the example is.
First we create a Function

IF OBJECT_ID(N'[dbo].[func_CHECK_ITEMCODEREFERENCE]', N'FN')IS NOT NULL
   BEGIN
       DROP FUNCTION [dbo].[func_CHECK_ITEMCODEREFERENCE];
   END
GO

CREATE FUNCTION [dbo].[func_CHECK_ITEMCODEREFERENCE]
       (
          @p_ITEMCODE   INT = 0
       )
RETURNS INT
AS
BEGIN
    DECLARE @v_RetVal   INT;
     SET @v_RetVal = 0;

     IF EXISTS(SELECT *
                FROM [DB1].[dbo].[tbl_ITEM]
                WHERE ITEMCODE = @p_ITEMCODE)
        BEGIN
           SET @v_RetVal = 1;
        END

    RETURN @v_RetVal;
END

Use the function in Alter statement CHECK Constraint.

ALTER TABLE [dbo].[tbl_ITEMORDER]
ADD CONSTRAINT CHECK_ITEMCODE_tbl_ITEMORDER
CHECK([dbo].[func_CHECK_ITEMCODEREFERENCE](ITEMCODE)=1);

Step-4 [ Now Check it ]

INSERT INTO [dbo].[tbl_ITEMORDER]
       (ITEMCODE, QTY)
VALUES (101, 200);

It inserted perfectly as the ITEMCODE 101 is present in the Table TBL_ITEM in the Database DB1.

INSERT INTO [dbo].[tbl_ITEMORDER]
       (ITEMCODE, QTY)
VALUES (110, 200);

Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the CHECK constraint "CHECK_ITEMCODE_tbl_ITEMORDER". The conflict occurred in database "DB2", table "dbo.tbl_ITEMORDER", column 'ITEMCODE'.
The statement has been terminated.

So it is working like Foreign Key Constraint and Hence the Solution is.


Hope you like it.





Posted by: MR. JOYDEEP DAS

Sunday, 28 December 2014

Foreign Key Refers the Columns of Same Table

Introduction

We all know about the Foreign Key constraint. Here in this article, we are not going to discuss about the definition or implementation concept of Foreign Key. But here we are trying to discuss about the Foreign key that refers the another a column of same table.

What is That?

EMPID
EMPNAME
DESIGNATION
MANAGERID
101
Sudip Das
Manager
101
102
Joydeep Das
Group Lead
101
103
Sukamal Jana
Group Lead
105

Here EPID is the Primary Key and the MANAHERID is the foreign key which refers the EMPID of the same table.

In the above situation Employee ID 101 is in manager position, so its Manager ID is same 101. But for Employee ID 102 the Manager ID is 101 and we can insert data without any error.

But in case of Employee ID 103 if we provide the Manager ID 105 it gives us an error as no such employee id (105) is not present and Foreign key gives us an Error over there.

How we implement That

Step-1 [ The Base Table with Foreign Key References ]

IF OBJECT_ID(N'dbo.tbl_EMPLOYEEMASTER', N'U')IS NOT NULL
   BEGIN
      DROP TABLE [dbo].[tbl_EMPLOYEEMASTER];
   END
GO
CREATE TABLE [dbo].[tbl_EMPLOYEEMASTER]
    (
        EMPID        INT          NOT NULL PRIMARY KEY,
        EMPNAME      VARCHAR(50)  NOT NULL,
        DESIGNATION  VARCHAR(50)  NOT NULL,
        MANAGERID    INT          NOT NULL,
        CONSTRAINT FK_MANAGERID_tbl_EMPLOYEEMASTER FOREIGN KEY(MANAGERID)
        REFERENCES [dbo].[tbl_EMPLOYEEMASTER](EMPID)
      );

Here just look at the definition of foreign key specially the REFERENCES section.

Step-2 [ Insert Firs Record ]

INSERT INTO [dbo].[tbl_EMPLOYEEMASTER]
       (EMPID, EMPNAME, DESIGNATION, MANAGERID)
VALUES (101, 'Sudip Das', 'Manager', 101);
GO

Here we not find any error as Manager ID is the Same as the Employee ID and Foreign key Satisfied.

Step-3 [ Insert Second Record ]

INSERT INTO [dbo].[tbl_EMPLOYEEMASTER]
       (EMPID, EMPNAME, DESIGNATION, MANAGERID)
VALUES (102, 'Joydeep Das', 'Group Lead', 101);

GO

Here we do not get any error as Manager ID 101 is present in the table and Foreign key satisfied.

Step-4 [ Insert Third Record ]

INSERT INTO [dbo].[tbl_EMPLOYEEMASTER]
       (EMPID, EMPNAME, DESIGNATION, MANAGERID)
VALUES (103, 'Sukamal Jana', 'Group Lead', 104);     

GO

Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_MANAGERID_tbl_EMPLOYEEMASTER". The conflict occurred in database "PRACTICE_DB", table "dbo.tbl_EMPLOYEEMASTER", column 'EMPID'.
The statement has been terminated.

Here it gives error as Manager ID 104 is not present in the Table.

Hope you like it.



Posted by: MR. JOYDEEP DAS