How to check if a Constraint exists in Sql server? - sql-server

I have this sql:
ALTER TABLE dbo.ChannelPlayerSkins
DROP CONSTRAINT FK_ChannelPlayerSkins_Channels
but apparently, on some other databases we use, the constraint has a different name. How do I check if there's a constraint with the name FK_ChannelPlayerSkins_Channels.

try this:
SELECT
*
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_NAME ='FK_ChannelPlayerSkins_Channels'
-- EDIT --
When I originally answered this question, I was thinking "Foreign Key" because the original question asked about finding "FK_ChannelPlayerSkins_Channels". Since then many people have commented on finding other "constraints" here are some other queries for that:
--Returns one row for each CHECK, UNIQUE, PRIMARY KEY, and/or FOREIGN KEY
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME='XYZ'
--Returns one row for each FOREIGN KEY constrain
SELECT *
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_NAME='XYZ'
--Returns one row for each CHECK constraint
SELECT *
FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS
WHERE CONSTRAINT_NAME='XYZ'
here is an alternate method
--Returns 1 row for each CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY, and/or DEFAULT
SELECT
OBJECT_NAME(OBJECT_ID) AS NameofConstraint
,SCHEMA_NAME(schema_id) AS SchemaName
,OBJECT_NAME(parent_object_id) AS TableName
,type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT'
AND OBJECT_NAME(OBJECT_ID)='XYZ'
If you need even more constraint information, look inside the system stored procedure master.sys.sp_helpconstraint to see how to get certain information. To view the source code using SQL Server Management Studio get into the "Object Explorer". From there you expand the "Master" database, then expand "Programmability", then "Stored Procedures", then "System Stored Procedures". You can then find "sys.sp_helpconstraint" and right click it and select "modify". Just be careful to not save any changes to it. Also, you can just use this system stored procedure on any table by using it like EXEC sp_helpconstraint YourTableNameHere.

Easiest way to check for the existence of a constraint (and then do something such as drop it if it exists) is to use the OBJECT_ID() function...
IF OBJECT_ID('dbo.[CK_ConstraintName]', 'C') IS NOT NULL
ALTER TABLE dbo.[tablename] DROP CONSTRAINT CK_ConstraintName
OBJECT_ID can be used without the second parameter ('C' for check constraints only) and that may also work, but if your constraint name matches the name of other objects in the database you may get unexpected results.
IF OBJECT_ID('dbo.[CK_ConstraintName]') IS NOT NULL
ALTER TABLE dbo.[tablename] DROP CONSTRAINT CK_ConstraintName
OBJECT_ID can also be used with other "constraints" such as Foreign Key constraints or Primary Key constraints, etc. For best results, always include the appropriate object type as the second parameter for the OBJECT_ID function:
Constraint Object Types:
C = CHECK constraint
D = DEFAULT (constraint or stand-alone)
F = FOREIGN KEY constraint
PK = PRIMARY KEY constraint
R = Rule (old-style, stand-alone)
UQ = UNIQUE constraint
Also note that the schema is often required. The schema of constraints generally takes the schema of the parent table.
Failure to put your constraints (or whatever you are checking) in brackets when using this method may also cause a false negative -- if your object uses unusual characters (such as a .), the brackets are required.

If you are looking for other type of constraint, e.g. defaults, you should use different query
(From How do I find a default constraint using INFORMATION_SCHEMA? answered by devio). Use:
SELECT * FROM sys.objects WHERE type = 'D' AND name = #name
to find a default constraint by name.
I've put together different 'IF not Exists" checks in my post "DDL 'IF not Exists" conditions to make SQL scripts re-runnable"

IF (OBJECT_ID('FK_ChannelPlayerSkins_Channels') IS NOT NULL)

Are you looking at something like this, below is tested in SQL Server 2005
SELECT * FROM sys.check_constraints WHERE
object_id = OBJECT_ID(N'[dbo].[CK_accounts]') AND
parent_object_id = OBJECT_ID(N'[dbo]. [accounts]')

Just something to watch out for......
In SQL Server 2008 R2 SSMS, the "Script Constraint as -> DROP And CREATE To" command produces T-SQL like below
USE [MyDatabase]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DEF_Detail_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [Patient].[Detail] DROP CONSTRAINT [DEF_Detail_IsDeleted]
END
GO
USE [MyDatabase]
GO
ALTER TABLE [Patient].[Detail] ADD CONSTRAINT [DEF_Detail_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]
GO
Out of the box, this script does NOT drop the constraint because the SELECT returns 0 rows. (see post Microsoft Connect).
The name of the default constraint is wrong but I gather it also has something to do with the OBJECT_ID function because changing the name doesn't fix the problem.
To fix this, I removed the usage of OBJECT_ID and used the default constraint name instead.
(SELECT * FROM dbo.sysobjects WHERE [name] = (N'DEF_Detail_IsDeleted') AND type = 'D')

I use the following query to check for an existing constraint before I create it.
IF (NOT EXISTS(SELECT 1 FROM sysconstraints WHERE OBJECT_NAME(constid) = 'UX_CONSTRAINT_NAME' AND OBJECT_NAME(id) = 'TABLE_NAME')) BEGIN
...
END
This queries for the constraint by name targeting a given table name. Hope this helps.

IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName'))
BEGIN
ALTER TABLE TableName DROP CONSTRAINT CONSTRAINTNAME
END

IF EXISTS(SELECT TOP 1 1 FROM sys.default_constraints WHERE parent_object_id = OBJECT_ID(N'[dbo].[ChannelPlayerSkins]') AND name = 'FK_ChannelPlayerSkins_Channels')
BEGIN
DROP CONSTRAINT FK_ChannelPlayerSkins_Channels
END
GO

INFORMATION_SCHEMA is your friend. It has all kinds of views that show all kinds of schema information. Check your system views. You will find you have three views dealing with constraints, one being CHECK_CONSTRAINTS.

I use this to check for and remote constraints on a column. It should have everything you need.
DECLARE
#ps_TableName VARCHAR(300)
, #ps_ColumnName VARCHAR(300)
SET #ps_TableName = 'mytable'
SET #ps_ColumnName = 'mycolumn'
DECLARE c_ConsList CURSOR LOCAL STATIC FORWARD_ONLY FOR
SELECT
'ALTER TABLE ' + RTRIM(tb.name) + ' drop constraint ' + sco.name AS csql
FROM
sys.Objects tb
INNER JOIN sys.Columns tc on (tb.Object_id = tc.object_id)
INNER JOIN sys.sysconstraints sc ON (tc.Object_ID = sc.id and tc.column_id = sc.colid)
INNER JOIN sys.objects sco ON (sc.Constid = sco.object_id)
where
tb.name=#ps_TableName
AND tc.name=#ps_ColumnName
OPEN c_ConsList
FETCH c_ConsList INTO #ls_SQL
WHILE (##FETCH_STATUS = 0) BEGIN
IF RTRIM(ISNULL(#ls_SQL, '')) <> '' BEGIN
EXECUTE(#ls_SQL)
END
FETCH c_ConsList INTO #ls_SQL
END
CLOSE c_ConsList
DEALLOCATE c_ConsList

SELECT tabla.name as Tabla,
restriccion.name as Restriccion,
restriccion.type as Tipo,
restriccion.type_desc as Tipo_Desc
FROM {DATABASE_NAME}.sys.objects tabla
INNER JOIN {DATABASE_NAME}.sys.objects restriccion
ON tabla.object_id = restriccion.parent_object_id
WHERE tabla.type = 'U' - Solo tablas creadas por el usuario.
AND restriccion.type = 'UQ' --Tipo de Restriccion UNIQUE
ORDER BY tabla.name, restriccion.type_desc

You can use the one above with one caveat:
IF EXISTS(
SELECT 1 FROM sys.foreign_keys
WHERE parent_object_id = OBJECT_ID(N'dbo.TableName')
AND name = 'CONSTRAINTNAME'
)
BEGIN
ALTER TABLE TableName DROP CONSTRAINT CONSTRAINTNAME
END
Need to use the name = [Constraint name] since a table may have multiple foreign keys and still not have the foreign key being checked for

In mySql you need to make sure you are querying the right database!
Hence table_schema=DATABASE()
Here are my functions using knex to check if a specific Foreign Key or Index defined in specific database and table
const isFKExists = async (knex, tableName, fkName) => {
const result = await knex.raw(
`SELECT COUNT(*) AS 'isExists' FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE table_schema=DATABASE() AND table_name='${tableName}' AND CONSTRAINT_NAME='${fkName}' AND CONSTRAINT_TYPE = 'FOREIGN KEY'`
)
return (result[0][0].isExists === 1)
}
const isIndexExists = async (knex, tableName, indexName) => {
const result = await knex.raw(
`SELECT COUNT(*) AS 'isExists' FROM INFORMATION_SCHEMA.STATISTICS WHERE table_schema=DATABASE() AND table_name='${tableName}' AND index_name='${indexName}'`
)
return (result[0][0].isExists > 0)
}
Enjoy 😊

As of SQL Server 2016, you can just use the IF EXISTS keywords.
ALTER TABLE dbo.ChannelPlayerSkins
DROP CONSTRAINT IF EXISTS FK_ChannelPlayerSkins_Channels
I'm using SQL Server 2019, but this mentions that it was available since SQL Server 2016.
The SQL Server docs mention it here under the ALTER TABLE page, and not under this Delete Check Constraints page. I'm not sure why.
IF EXISTS
Applies to: SQL Server (SQL Server 2016 (13.x) and later) and Azure SQL Database.
Conditionally drops the column or constraint only if it already exists.

Related

Find if an unique index exists in MSSQL

I have a reason to drop a Unique constraint if it already exists, where I may be modifying a field that it references.
My basic attempt is:
IF EXISTS (SELECT OBJECTPROPERTY(OBJECT_ID(N'[dbo].[TableY].[UQ_X]'),'IsUniqueCnst'))
BEGIN
ALTER TABLE [dbo].[TableY]
DROP CONSTRAINT [UQ_X]
END
The OBJECT_ID call always returns null and the code proceeds to try to drop the constraint, whether [UQ_X] exists or not.
Thanks to the clues from the comments, I have a working option.
The solution seems to be to look at the sys.key_constraints data
IF EXISTS( SELECT 1
FROM sys.key_constraints k
WHERE k.parent_object_id =OBJECT_ID(N'[dbo].[TableY]')
AND k.[type] = 'UQ'
AND k.[name] ='UQ_X')
BEGIN
ALTER TABLE [dbo].[TableY]
DROP CONSTRAINT [UQ_X]
END

How to DROP table in correct order in SQL SERVER 2014?

I have following 5 tables and 1 table is connected as Foreign key in 2 tables. My dilemma is that I cannot figure out which table to drop first. below is the drop table code I am trying and I have created tables in following order
Updated Drop Table Code:
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='[Student Major]')
BEGIN
DROP TABLE [Student Major]
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Major')
BEGIN
DROP TABLE Major
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Citizenship')
BEGIN
DROP TABLE Citizenship
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Country')
BEGIN
DROP TABLE Country
END
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Student')
BEGIN
DROP TABLE Student
END
GO
CREATE TABLE Student(
[Student ID] INT IDENTITY PRIMARY KEY
,[First Name] varchar (50) NOT NULL
,[Last Name] varchar (30) NOT NULL
)
GO
CREATE TABLE Country(
[Country ID] int identity PRIMARY KEY NOT NULL
,[Country of Birth] varchar (10)
,[Student ID] int FOREIGN KEY REFERENCES Student([Student ID]) NOT NULL
)
GO
CREATE TABLE Citizenship(
[Citizenship ID] int identity PRIMARY KEY
,[Country of Citizenship1] varchar (10)
,[Country of Citizenship2] varchar (10)
,[Student ID] int FOREIGN KEY REFERENCES Student([Student ID]) NOT NULL
,[Country ID] int FOREIGN KEY REFERENCES Country([Country ID]) NOT NULL
)
GO
CREATE TABLE Major(
[Major ID] int identity PRIMARY KEY
,[Major Name] varchar(30) NOT NULL
)
GO
CREATE TABLE [Student Major](
[Student MajorID] int identity
,[Student ID] int FOREIGN KEY REFERENCES Student([Student ID])
,[Major ID] int FOREIGN KEY REFERENCES Major([Major ID])
,[Graduated Major] varchar (30) NOT NULL
)
GO
I Would like to drop table in correct order
Errors:
Could not drop object 'Student' because it is referenced by a FOREIGN KEY constraint.
Also,Please provide explanation of dropping the table. I am new to SQL.
Thanks in advance!
Here is the way that I usually do it:
SELECT 'ALTER TABLE [' + O.[name] + '] DROP ' + F.[name]
FROM sys.objects O
INNER JOIN sys.foreign_keys F ON (F.parent_object_id = O.object_id)
WHERE O.[type] = 'U'
SELECT 'DROP TABLE [' + [name] + ']'
FROM sys.objects
WHERE [type] = 'U'
ORDER BY create_date DESC
This will generate a record set such as
ALTER TABLE Foo DROP FK_BLAH
ALTER TABLE Bar DROP FK_BAH
...
DROP TABLE Foo
DROP TABLE Bar
Which, you can then just copy and paste into a query window, and run from there.
(At the time that I'm writing this answer, I don't have access to an instance of SQL server, but I use code like the above all the time.)
DROP TABLE Student_Major; GO
SELECT 1 FROM Citizenship; GO
DROP TABLE Citizenship; GO
SELECT 1 FROM Major; GO
DROP TABLE Major; GO
SELECT 1 FROM Country; GO
DROP TABLE Country; GO
SELECT 1 FROM Student; GO
DROP TABLE Student; GO
It's just like you said, it has to be in the order so that any table that is referenced by a FK is not dropped, as long as the FK is there.
EDIT: GO forces the end of the batch
EDIT: I notice you have the GO in there already. You could use Information_schema to find the constraints associated with the table and drop them first, but I feel like you shouldn't need to do that. What if you injected a dummy query imbetween each DROP statement. It's hacky but if you don't feel like having to understand all the information_schema stuff it might be easier if it works.
You could first remove all FK constraints by:
ALTER TABLE ... DROP CONSTRAINT ...;
Then drop tables in any order.
If you are using SQL Server 2016 and above you could use DIE(drop if exists) and multiple tables at-once (still order matters):
DROP TABLE IF EXISTS [Student Major], Major, Citizenship, Country,Student;
DBFiddle Demo
If you are in doubt, and don't want to remove your constraints for some reason, you can always drop your tables in the exact opposite order in which you created them.
Since the first table doesn't reference any other, but maybe is referenced by other tables created after it, you should delete it last.
For the remaining tables, apply same logic. The first of the remaining tables is to be deleted last among them, and so on.

How can I delete or alter a default constraint from table in SQL Server database for multiple database?

I have gone thorough these previous questions Q1, Q2, Q3. Using this I can catch my exact constraint name. But it is not enough for me.
For example I have done somthing
ALTER TABLE dbo.Documents ADD ShowOnHandset BIT NOT NULL DEFAULT 'FALSE'
Here automatically my constrant named by the machine was DF__Documents__ShowO__7AB2122C on my machine. But I have run the same script in multiple PC, on those PC those constraint are almost same except the last hashed value. DF__Documents__ShowO__54A20B0D DF__Documents__ShowO__5D5216D7
I have seen that the last 8 bit hashed value is not similar. But I need to remove this constraint from all table and I want to replace them with
ALTER TABLE dbo.Documents ADD ShowOnHandset BIT NOT NULL DEFAULT ((1))
But I can't identify the the exact constraint name, so how can I drop it using a single script?
I have found hard-coded solution by those mentioned questions. But I need a single script to do it. Please help me to solve this.
I can catch the constraint name using this code
select name from sys.objects where name like 'DF__Documents__ShowO%'
I know the way how to delete it. Here it is.
ALTER TABLE dbo.AppSystems DROP constraint [constraint_name]
But I am unable to do it. Because I couldn't put the value constraint_name even if I can caught it. So how could I put this name here to drop it.
Update Modified the Question.
Run this and output as text, then copy the result and run in another query window
Fritz with the code below to ADD the updated constraint:
;With cte As (select object_id From sys.objects where name like 'DF__Documents__ShowO%')
Select 'Alter Table ' + Object_Name(df.object_id) + N' Add Constraint Default (1) For ShowOnHandset'
From sys.default_constraints As df
Join cte As c
On c.object_id = df.object_id
This deletes the constraints
;With cte As (select object_id From sys.objects where name like 'DF__Documents__ShowO%')
Select 'Alter Table ' + Object_Name(df.object_id) + N' Drop Constraint [' + df.Name + ']'
From sys.default_constraints As df
Join cte As c
On c.object_id = df.object_id
In MS SQL you can specify constraint name explicit:
ALTER TABLE dbo.Documents ADD ShowOnHandset BIT NOT NULL CONSTRAINT DF_Documents_ShowOnHandset DEFAULT 'FALSE'
Try dynamic query:
Declare #MyVariable varchar(max)
Declare #Variable varchar(max)
Set #MyVariable=(Select name from sys.objects
where parent_object_id=Object_ID('Documents','U') and name like 'DF__Documents__Show%')
Set #variable='ALTER TABLE dbo.AppSystems DROP constraint' +#MyVariable
Exec(#variable)

How to drop a table if it exists?

The table name is Scores.
Is it correct to do the following?
IF EXISTS(SELECT *
FROM dbo.Scores)
DROP TABLE dbo.Scores
Is it correct to do the following?
IF EXISTS(SELECT *
FROM dbo.Scores)
DROP TABLE dbo.Scores
No. That will drop the table only if it contains any rows (and will raise an error if the table does not exist).
Instead, for a permanent table you can use
IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL
DROP TABLE dbo.Scores;
Or, for a temporary table you can use
IF OBJECT_ID('tempdb.dbo.#TempTableName', 'U') IS NOT NULL
DROP TABLE #TempTableName;
SQL Server 2016+ has a better way, using DROP TABLE IF EXISTS …. See the answer by #Jovan.
From SQL Server 2016 you can use
DROP TABLE IF EXISTS dbo.Scores
Reference: DROP IF EXISTS - new thing in SQL Server 2016
It will be in SQL Azure Database soon.
The ANSI SQL/cross-platform way is to use the INFORMATION_SCHEMA, which was specifically designed to query meta data about objects within SQL databases.
if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'Scores' AND TABLE_SCHEMA = 'dbo')
drop table dbo.Scores;
Most modern RDBMS servers provide, at least, basic INFORMATION_SCHEMA support, including: MySQL, Postgres, Oracle, IBM DB2, and Microsoft SQL Server 7.0 (and greater).
Have seen so many that don't really work.
when a temp table is created it must be deleted from the tempdb!
The only code that works is:
IF OBJECT_ID('tempdb..#tempdbname') IS NOT NULL --Remove dbo here
DROP TABLE #tempdbname -- Remoeve "tempdb.dbo"
In SQL Server 2016 (13.x) and above
DROP TABLE IF EXISTS dbo.Scores
In earlier versions
IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL
DROP TABLE dbo.Scores;
U is your table type
Or:
if exists (select * from sys.objects where name = 'Scores' and type = 'u')
drop table Scores
I hope this helps:
begin try drop table #tempTable end try
begin catch end catch
I wrote a little UDF that returns 1 if its argument is the name of an extant table, 0 otherwise:
CREATE FUNCTION [dbo].[Table_exists]
(
#TableName VARCHAR(200)
)
RETURNS BIT
AS
BEGIN
If Exists(select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = #TableName)
RETURN 1;
RETURN 0;
END
GO
To delete table User if it exists, call it like so:
IF [dbo].[Table_exists]('User') = 1 Drop table [User]
Simple is that:
IF OBJECT_ID(dbo.TableName, 'U') IS NOT NULL
DROP TABLE dbo.TableName
where dbo.TableName is your desired table and 'U' is type of your table.
IF EXISTS (SELECT NAME FROM SYS.OBJECTS WHERE object_id = OBJECT_ID(N'Scores') AND TYPE in (N'U'))
DROP TABLE Scores
GO
SQL Server 2016 and above the best and simple one is
DROP TABLE IF EXISTS [TABLE NAME]
Ex:
DROP TABLE IF EXISTS dbo.Scores
if suppose the above one is not working then you can use the below one
IF OBJECT_ID('dbo.Scores', 'u') IS NOT NULL
DROP TABLE dbo.Scores;
I use:
if exists (select *
from sys.tables
where name = 'tableName'
and schema_id = schema_id('dbo'))
begin
drop table dbo.tableName
end
Make sure to use cascade constraint at the end to automatically drop all objects that depend on the table (such as views and projections).
drop table if exists tableName cascade;
If you use long codes and want to write less for temporary table create this procedure:
CREATE PROCEDURE MF_DROP (#TEMP AS VARCHAR(100)) AS
EXEC('IF OBJECT_ID(''TEMPDB.DBO.' + #TEMP + ''', ''U'') IS NOT NULL DROP TABLE ' + #TEMP)
In execution:
EXEC MF_DROP #A
CREATE TABLE #A (I INT) ....
A better visual and easy way, if you are using Visual Studio, just open from menu bar,
View -> SQL Server Object Explorer
it should open like shown here
Select and Right Click the Table you wish to delete, then delete. Such a screen should be displayed. Click Update Database to confirm.
This method is very safe as it gives you the feedback and will warn of any relations of the deleted table with other tables.

How do I combine these two SQL statements into one, in a manner compatible with both MSSQL 2000 and 2005?

My end goal is to accomplish something like:
CREATE FOREIGN KEY IF NOT EXISTS FOREIGN KEY
Since that statement doesn't appear to exist, I'm attempting to sort of kludge it together.
I have a statement that will return the FK name if it exists:
SELECT f.name AS ForeignKey
FROM sys.foreign_keys AS f
WHERE OBJECT_NAME(f.parent_object_id) = 'myTableName'
And I have a statement that adds the desired foreign key:
ALTER TABLE myTableName
WITH CHECK
ADD CONSTRAINT [FK_myTableName_otherTable]
FOREIGN KEY([columnName])
REFERENCES otherTable ([otherColumn])
I just can't, for the life of me, figure out how to mash them together into a single statement.
It's an absolute requirement that the solution work in both MS SQL 2000 as well as MS SQL 2005.
if not exists (SELECT f.name AS ForeignKey
FROM sys.foreign_keys AS f
WHERE OBJECT_NAME(f.parent_object_id) = 'myTableName'
)
begin
ALTER TABLE myTableName
WITH CHECK
ADD CONSTRAINT [FK_myTableName_otherTable]
FOREIGN KEY([columnName])
REFERENCES otherTable ([otherColumn])
end
sys.foreign_keys was introduced in SQL Server 2005. You'll have to use sysobjects to be compatible with both SQL Server 2000 & 2005.
Try this SQL:
IF NOT EXISTS (
SELECT NULL FROM sysobjects
WHERE name = 'FK_myTableName_otherTable'
AND parent_obj = OBJECT_ID(N'myTableName'))
ALTER TABLE myTableName
WITH CHECK
ADD CONSTRAINT [FK_myTableName_otherTable]
FOREIGN KEY([columnName])
REFERENCES otherTable ([otherColumn])
if not exists (
SELECT f.name AS ForeignKey
FROM sys.foreign_keys AS f
WHERE OBJECT_NAME(f.parent_object_id) = 'myTableName')
begin
ALTER TABLE myTableName
WITH CHECK
ADD CONSTRAINT [FK_myTableName_otherTable]
FOREIGN KEY([columnName])
REFERENCES otherTable ([otherColumn])
end

Resources