Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop Foreign Key without knowing the name of the constraint?

Tags:

sql-server

I have created one table using below command:

create table Table1(     Id int Not Null          Foreign key          references Table2(Id)           on delete cascade          on update cascade,     UserName nvarchar(150),     TimeInSeconds int Not Null       primary key(Id,TimeInSeconds) ); 

But now I want to drop the foreign key. As i havent given constraint name I cant use:

Alter table <tablename> drop foreign key <foreign key name> 

Is there any way? Pls help.

like image 679
Wondering Avatar asked May 05 '09 12:05

Wondering


People also ask

How do you drop a constraint without a name?

Run this command to browse all constraints: exec sp_helpconstraint 'mytable' --and look under constraint_name. It will look something like this: DF__Mytable__Column__[ABC123] . Then you can just drop the constraint.

How do I get rid of unnamed foreign key?

You could remove without know the name, creating a concatenate query and executing automatically: set @s:=''; select @s:=concat(@s, 'alter table ', 'your_table', ' drop foreign key ',CONSTRAINT_NAME, ';') from information_schema.

Can you have a foreign key without a constraint?

Foreign Keys without the constraintsYou don't have to configure a foreign key constraint on a column just because it refers to another column. You could instead configure two tables such that one refers to the other, but without any defined foreign key.


1 Answers

You can find the name of the constraint in INFORMATION_SCHEMA.TABLE_CONSTRAINTS

select CONSTRAINT_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME = 'Table1' 
like image 93
Ed Guiness Avatar answered Nov 09 '22 05:11

Ed Guiness