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.