473,657 Members | 2,572 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Setting foreign key on insert

INSERT INTO X ...... ( A, B, C )
INSERT INTO Y ...... ( J, K, L )

If Y has a foreign key M which is the primary key D of X,
is there an easy and/or efficient way to have SQL Server
assign D, and tell us what it is so we can add M to the
list for Y ?

I know I can select D where A, B, C but I wondered about
other tricks.

--
Wes Groleau
Alive and Well
http://freepages.religions.rootsweb.com/~wgroleau/
Dec 2 '06 #1
1 12057
Wes Groleau (gr**********@f reeshell.org) writes:
INSERT INTO X ...... ( A, B, C )
INSERT INTO Y ...... ( J, K, L )

If Y has a foreign key M which is the primary key D of X,
is there an easy and/or efficient way to have SQL Server
assign D, and tell us what it is so we can add M to the
list for Y ?

I know I can select D where A, B, C but I wondered about
other tricks.
The first question is: why would you want SQL Server to assign the
primary key?

Normally, the primary key of tbe table is to be found in the data. For
instance, if you have a table EmployeeProject s which specifies which
employee that are members of which projects, then that table would
have a primary of (EmployeeID, ProjectCode), and there would not be
any one-column key.

Thus, in the example above, the columns A, B and C would be the primary
key in X, and they would appear in Y as well,

There are of course cases where a system-generated surrogate key is
called for. For instance, the natural key may be difficult to determine
exactly, or it may be mutable. In the cases of multi-column keys, you
may sometimes prefer to introduce a surrogate key to reduce the size
of foreign keys in referring tables. Personally, I've more or less adding
surrogate keys of this reason to my tables, because I've seen cases
where it did more harm than benefit.

If you need to use surrogate keys, it's often best to roll your own:

BEGIN TRANSACTION

SELECT @D = coaelsce(MAX(D) , 0) + 1 FROM X WITH (UPDLOCK, HOLDLOCK)

INSERT X (A, B, C, D, ...)
VALUES (..., @D, ...)

INSERT Y (J, K, L, M, ...)
VALUES(..., @D, ...)

COMMIT TRANSACTION

This can easily be extended if you insert more than one row at a time.

To have SQL Server to generate the surrogate key for you, you can use
the IDENTITY property. This is particularly a good idea, if you expect
plenty of concurrent inserts. The code above serlializes parallel
inserts on the SELECT statement. In this case you do:

BEGIN TRANSACTION

INSERT X (A, B, C, ...)
VALUES (...)

SELECT @D = scope_identity( )

INSERT Y (J, K, L, M, ...)
VALUES(..., @D, ...)

COMMIT TRANSACTION

But this only works for single-row inserts. For multi-row inserts, you
are better off mapping from the natural keys in X. And if there are no
natural keys in X to map back to, you are in trouble. Overlall, there
several places where IDENTITY gives you issues when rolling your own
does not, so I recommend that you only use it when concurrency calls
for it.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Dec 2 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
4519
by: Ron | last post by:
Mandatories: Ver 7.3.4, Redhat Linux 8.0, P4, 2GB RAM I want to add a 'nullable' foreign key to a column in a table. I have tables "company" and "project" which may be related by company.companyID <-> project.companyID. project.companyID is allowed to be null. However, when someone tries to delete a company which is still referenced in "project" I want a constraint restricting deletion. I tried:
0
2624
by: Jeremiah Jacks | last post by:
I just upgraded to MySQL 4.0.14-standard for RedHat Linux and am using = the pre-compiled binaries. I have a database with INNODB tables. When I insert a row into one of the child tables, I get the following = MySQL error: INSERT INTO product_access_level (product_id,access_level_id) VALUES
1
8889
by: Andrew DeFaria | last post by:
I created the following .sql file to demonstrate a problem I'm having. According to the manual: If |ON DELETE CASCADE| is specified, and a row in the parent table is deleted, then InnoDB automatically deletes also all those rows in the child table whose foreign key values are equal to the referenced key value in the parent row. However:
1
3096
by: James E | last post by:
I have a question about best practices of how to deal with lookup data from my C# apps. On a couple of occasions I have come across a problem where I have to automate inserting a record into a table that has a foreign key constraint that is linked to a lookup table. E.g. Take the following database structure: SQL-Server Database: Table 1:
0
1418
by: Scott Ribe | last post by:
I've got a problem which I think may be a bug in Postgres, but I wonder if I'm missing something. Two tables, A & B have foreign key relations to each other. A 3rd table C, inherits from A. A stored procedure updates a row in C, adds a row each in B & C. I get an integrity violation. All the foreign keys are deferrable, and the stored procedure is called from within a transaction with constraints deferred. (And the foreign keys do refer to...
2
12955
by: Tim::.. | last post by:
Can someone please tell me why I keep getting the following error from the code below! Error: INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'FK_tblOfficePageContent_tblPageContent'. The conflict occurred in database 'CPNCMS', table 'tblPageContent', column 'pageID'. The statement has been terminated. I cant seem to see why I keep getting an error when I do the insert!
1
2077
by: Thomas T. Thai | last post by:
I'm looking for a better way to make use of foreign keys. Here is a sample setup: -- TESTING Foreign Keys create table mod ( mod_id int not null primary key, name varchar(32) not null default '' );
5
7290
by: coosa | last post by:
Dear all, I'm new under mysql and have installed mysql5.0.24a community edition for win32. I have tried to implement a foreign key for this following sample scenario: CREATE TABLE student ( student_id INTEGER NOT NULL AUTO_INCREMENT, student_name VARCHAR(100) NOT NULL,
0
3027
by: Frank Swarbrick | last post by:
So we're trying to decide if it's better to use IDENTITY columns or sequences to create a surrogate key as the primary key for our tables. I kind of like the identity column, because it's more 'tightly integrated' in to the table. With a sequence you have to make sure that each application that inserts records uses the same sequence. (Probably not likely that it wouldn't, but...) One thing where it seems like a SEQUENCE would be...
0
8425
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8845
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8743
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8522
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7355
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6177
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.