Home > Ask the SQL Server Experts > Andrew Novick - Development Questions & Answers > Using newid in SQL Server to insert records in parent-child tables
Ask The SQL Server Expert: Questions & Answers
EMAIL THIS

Using newid in SQL Server to insert records in parent-child tables

Andrew Novick EXPERT RESPONSE FROM: Andrew Novick

Pose a Question
Other SQL Server Categories
Meet all SQL Server Experts
Become an Expert for this site


Expert advice on database administration
Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google


>
QUESTION POSED ON: 19 July 2005
In my project I have two (parent-child) tables that are bound by a primary key (PK)/foreign key (FK) relation. To insert new records in my tables, I would like to use the newid() function (in the PK of the parent and FK of the child). While this would work fine with the parent, the child records seem to have no information about the unique ID given by SQL to the parent record.

Is there a way to get the required information so that I am able to insert records in both the parent and the child at the same time and keep the relation in place?



Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google



RELATED CONTENT
Andrew Novick - Development
Nullable fields in a table
Connecting Visual Basic to SQL Server
Stored procedures in Crystal Reports
Storing an image file in SQL Server
Storing large amounts of data as ntext data type
Stored procedures looking at different databases
Code trigger that captures login and system date
Stored procedures and remote procedure calls
How to use results from one stored procedure in another
How to display the XML result of 'Select For XML Explicit'

SQL Server Database Modeling and Design
Optimizing SQL Server indexes –- even when they're not your indexes
Top tips and tricks for SQL Server database development
Managing the development lifecycle with Visual Studio Team System 2008
A first look at Visual Studio Team System 2008 Database Edition
Testing transaction log autogrowth behavior in SQL Server
Top 10 SQL Server Tips of 2008
Tutorial: SQL Server indexing tips to improve performance
Tutorial: Learn SQL Server basics from A-Z
SQL Server database design disasters: How it all starts
Can you shrink your SQL Server database to death?

SQL/Transact SQL (T-SQL)
Using DELETE and TRUNCATE TABLE statements to delete data in SQL Server
SQL language crash course (just enough to be dangerous)
Working with IntelliSense in SQL Server 2008 Management Studio
SQL Server Mailbag: Stored procedures, triggers and SSRS reports
Working with sparse columns in SQL Server 2008
Determining the source of full transaction logs in SQL Server
New GROUP BY option provides better data control in SQL Server 2008
Using the OPENROWSET function in SQL Server
Loading data files with SQL Server's BULK INSERT statement
Importing and exporting bulk data with SQL Server's bcp utility
SQL/Transact SQL (T-SQL) Research

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
binary tree  (SearchSQLServer.com)
block  (SearchSQLServer.com)
data structure  (SearchSQLServer.com)
DDBMS  (SearchSQLServer.com)
entity-relationship model  (SearchSQLServer.com)
initial extent  (SearchSQLServer.com)
primary key  (SearchSQLServer.com)
segment  (SearchSQLServer.com)
tablespace  (SearchSQLServer.com)
view  (SearchSQLServer.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary


Yes. Uniqueidentier, also known as a GUID (Globally Unique ID), can be a very useful type for a primary key. To get the result that you require, the newid can be placed into a local variable in your SQL script and used to insert into both tables. Let's start with the tables and the foreign key:

CREATE TABLE dbo.ParentTable (ParentKey uniqueidentifier PRIMARY KEY
                       ,  DataCol1 varchar(10)
                       ,  DataCol2 varchar(10)
                         )
GO
CREATE TABLE dbo.ChildTable  (
                          ChildKey uniqueidentifier DEFAULT (NEWID())
                       ,  ParentKey uniqueidentifier 
                       ,  DataCol3 varchar(10)
                       ,  DataCol4 varchar(10)
                         )
GO
 
ALTER TABLE dbo.ChildTAble ADD 
    CONSTRAINT FK_ChildTable_ParentTable_ParentKey FOREIGN KEY
       (ParentKey)
       REFERENCES dbo.ParentTable(ParentKey)
GO

Now to do the insert, the @myNewID is created and used in both inserts:

DECLARE @myNewID uniqueidentifier
select @myNewID = NEWID()
 
INSERT INTO ParentTable (ParentKey, DataCol1, DataCol2)
    VALUES (@myNEWID, 'ABC', 'DEF')
 
INSERT INTO ChildTable (ParentKey, DataCol3, DataCol4)
    VALUES (@myNEWID, 'GHI', 'JKL')
 
go

Note that ChildTable's primary key is created by the default and is not supplied in the insert statement. It's a different uniqueidentifier. Because we don't need to use ChildKey in any other table it doesn't have to be created by the script.


Do you have comments on this Ask the Expert Q&A? Let us know.




Search and Browse the Expert Answer Center
Search and browse more than 25,000 question and answer pairs from more than 250 TechTarget industry experts.
Browse our Expert Advice



SQL Solutions - SQL Database Design
HomeNewsTopicsITKnowledge ExchangeTipsAsk the ExpertsMultimediaWhite PapersIT Downloads
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Site Map




All Rights Reserved, Copyright 2005 - 2009, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts