DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Designing a Blog Application Using Document Databases
  • Relational DB Migration to S3 Data Lake Via AWS DMS, Part I
  • NoSQL for Relational Minds
  • Business Logic Database Agent

Trending

  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Four Essential Tips for Building a Robust REST API in Java
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  1. DZone
  2. Data Engineering
  3. Databases
  4. Foreign Key Relation Across Database

Foreign Key Relation Across Database

Foreign key references can be found across the database with a simple Microsoft SQL Server code. This code will work between the tables to get the keys.

By 
Joydeep Das user avatar
Joydeep Das
·
Jun. 14, 15 · Interview
Likes (1)
Comment
Save
Tweet
Share
22.5K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction


We all know about the foreign key reference. But what happens when we want foreign key references across the Database? This article shows you how. 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 the 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's 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.




Relational database Database

Published at DZone with permission of Joydeep Das, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Designing a Blog Application Using Document Databases
  • Relational DB Migration to S3 Data Lake Via AWS DMS, Part I
  • NoSQL for Relational Minds
  • Business Logic Database Agent

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!