简体   繁体   中英

How to add a primary (Surrogate) key from one table into a foreign key of another table?

I am trying to add my CustId(Primary Key) from Customers table into CustID(Foreign Key) from CustomerAddress Table. But I am unable to add the foreign key automatically. what should i do. Below is my schema (I copied it from my SQL Server Instance)

CREATE TABLE [dbo].[Customers] 
(
           [CustId]           INT           IDENTITY (1, 1) NOT NULL,
           [FirstName]        NVARCHAR (50) NOT NULL,
           [MiddleName]       NVARCHAR (50) NULL,
            [LastName]         NVARCHAR (50) NOT NULL,
            [Salutation]       NVARCHAR (10) NULL,
            [Position]         NVARCHAR (50) NULL,
            [OrganizationType] NVARCHAR (50) NULL,
            [PhoneNumber]      NVARCHAR (50) NOT NULL,
            [Ext]              NCHAR (10)    NULL,
            [FaxNumber]        NVARCHAR (50) NULL,
            [CellNumber]       NVARCHAR (50) NULL,
            [EmailAddress]     NVARCHAR (50) NOT NULL,
            [EmailPermission]  NCHAR (10)    NOT NULL,
            [Password]         NVARCHAR (50) NOT NULL,
            PRIMARY KEY CLUSTERED ([CustId] ASC)
);

CREATE TABLE [dbo].[CustomerAddress] 
(
            [AddressID] INT NOT NULL IDENTITY (1, 1),
            [CustID]           INT,
            [OrganizationName] NVARCHAR (50) NOT NULL,
            [Division]         NVARCHAR (50) NULL,
            [Department]       NVARCHAR (50) NOT NULL,
            [BuildingRoom]     NVARCHAR (50) NULL,
            [Street]           NVARCHAR (50) NULL,
            [City]             NVARCHAR (50) NULL,
            [POBox]            NVARCHAR (50) NULL,
            [Province]         NVARCHAR (50) NULL,
            [PostalCode]       NCHAR (10)    NOT NULL,
            [Country]          NVARCHAR (30) NOT NULL,
            [AddressType]      CHAR (10)     NOT NULL,
            PRIMARY KEY CLUSTERED ([AddressID]),
            CONSTRAINT [FK_CustID] FOREIGN KEY ([CustID]) REFERENCES [dbo].[Customers] ([CustId])
);

C# code for inserting data:

public int AddCustomerDeliveryAddress(CustomerAddressBLL NewCustomerDeliveryAddressBLL)
{
            string sql = string.Format(@"Insert into CustomerAddress (OrganizationName,Division,Department,BuildingRoom,Street,City,POBox,Province,PostalCode,Country,AddressType)
                        Values(@OrganizationName,@Division,@Department,@BuildingRoom,@Street,@City,@POBox,@Province,@PostalCode,@Country,@AddressType)");

            db.AddParameter("@OrganizationName", NewCustomerDeliveryAddressBLL.Organization);
            db.AddParameter("@Division", NewCustomerDeliveryAddressBLL.Division);
            db.AddParameter("@Department", NewCustomerDeliveryAddressBLL.Department);
            db.AddParameter("@BuildingRoom", NewCustomerDeliveryAddressBLL.BuildingRoom);
            db.AddParameter("@Street", NewCustomerDeliveryAddressBLL.Street);
            db.AddParameter("@City", NewCustomerDeliveryAddressBLL.City);
            db.AddParameter("@POBox", NewCustomerDeliveryAddressBLL.PoBox);
            db.AddParameter("@Province", NewCustomerDeliveryAddressBLL.Province);
            db.AddParameter("@PostalCode", NewCustomerDeliveryAddressBLL.PostalCode);
            db.AddParameter("@Country", NewCustomerDeliveryAddressBLL.Country);
            db.AddParameter("@AddressType", NewCustomerDeliveryAddressBLL.AddressType);

            return db.ExecuteNonQuery(sql);
}

If you do it in "pure" T-SQL, you need to use code something like this:

-- declare variable for your identity
DECLARE @NewCustId INT;

-- insert into your Customers table
INSERT INTO dbo.Customers([FirstName], [MiddleName], [LastName], ......)
VALUES ('John', 'Robert', 'Doe', ........);

-- get the newly inserted Identity value
SET @NewCustId = SCOPE_IDENTITY();

-- insert into CustomerAddress table
INSERT INTO dbo.CustomerAddress ([CustID], [OrganizationName], [Division], ......)
VALUES(@NewCustId, 'Orgname', 'Division', .....)

Update: OK, it's C# code - you need to change it to include SELECT SCOPE_IDENTITY() at the end:

string sql = string.Format(@"INSERT INTO dbo.CustomerAddress (OrganizationName, Division, Department, BuildingRoom, Street, City, POBox, Province, PostalCode, Country, AddressType)
                             VALUES (@OrganizationName, @Division, @Department, @BuildingRoom, @Street, @City, @POBox, @Province, @PostalCode, @Country, @AddressType); 
                             SELECT SCOPE_IDENTITY();");

and the use this call:

int newCustId = (int)db.ExecuteScalar(sql);

so you now get back the NewCustID from your INSERT call - now use that value in the second insert you need to insert your data into CustomerAddress

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM