472,950 Members | 2,013 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,950 software developers and data experts.

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 12012
Wes Groleau (gr**********@freeshell.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 EmployeeProjects 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****@sommarskog.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
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...
0
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...
1
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...
1
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...
0
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...
2
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...
1
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...
5
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 (...
0
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...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...

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.