views:

426

answers:

1

Is it possible to disable Unique and Foreign Key constraints before creating the tables of a database using T-SQL?. Like for example, in MySQL (tested in version 5.1) if you have a SQL script that creates the database schema you can put the following:

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;

at the beginning of the script (before any CREATE TABLE statement) to disable the mentioned constraints. Then at the end of the script you can use the following to enable them again.

/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;

Is there something similar for SQL Server 2005?

+2  A: 

I am not super familiar with MySQL, but the way I would approach what you are try to achieve in SQL Server would be to remove the constraint definitions from the create table statements, and then add the constraints at the end of the script, along the lines of the below.

Create table table1 (id int not null, val varchar(10))
Create table table2 (id int, t1id int, val varchar(10))

...Do other statements

   Alter table table1 add 
        Constraint pk_table1 Primary Key (id)
    Alter table table2 Add 
        Constraint fk_table1 Foreign Key (t1id) References table1(id)
cmsjr
This would also be the technique that I'd recommend. This or make sure that your objects are being created in the correct order.
mrdenny
Regretfully for me this solution is not an option. I'm guessing there's no equivalent approach in SQL Server.
Elliot Vargas
I am not aware of a method to globally disable constraints in SQL Server. Can you clarify why you can't use this approach?
cmsjr
To do this for all tables in the db in one shot use the undocumented ForEAchTable proc: sp_MSForEachTable 'select count (*) as ''?'' from ?'
Rob Allen
Thanks for the tip, I'm going to check that out.
cmsjr