HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

How are foreign keys resolved when creating tables in batch?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
tablesarecreatingforeignbatchkeyshowwhenresolved

Problem

I am creating a database version management tool with the goal of being able to recreate a database from scratch using text/sql files contained in source control. As part of establishing a baseline version of the database I have exported the CREATE TABLE statement for each table into it's own sql file.

I plan to combine the contents of each file into a single batch when initializing the database.

However, each file contains foreign key constraints within the CREATE TABLE statement.

I am wondering if the RDMS (in this case MSSQL and Sybase) is going to be able to handle the batch? Will it be able to create the tables and then create the constraints?

Or is it going to fail when it comes across the first table where the table containing the candidate key has not been created yet?

I've read about batch execution in MSSQL, and my understanding is the database will create a execution plan for the batch. Will the database be able to reorder my create table statements into the right order?

My database contains 366 tables and it would be difficult to order the CREATE TABLE statements in the correct order.

Solution

the batch will fail.

do all the table creates first, then do all the foreign key constraints AFTER all the tables are created.

OR

create the tables with constraints in the correct ORDER so that constraints don't fail.

Context

StackExchange Database Administrators Q#27614, answer score: 3

Revisions (0)

No revisions yet.