473,400 Members | 2,163 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,400 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 12033
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...
0
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...

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.