title: How to add foreign keys with IF EXISTS/IF NOT EXISTS statement?
body: <p>Im trying to insert a foreign key into multiple tables by checking if the key exists already, if not it should insert it.
  But when I try to run my script it just skips the whole insert part, even when all the individual commands work properly.
  (i use MS SQL Server 2008)</p>
  
  <pre><code>begin transaction;
  
  declare @isid as nvarchar(50);
  declare @fk as nvarchar(50);
  declare @statement as VARCHAR(2000);
  
  declare @db_cursor CURSOR;
  set @db_cursor = cursor FOR SELECT Name FROM [sys.Component] order by Name;
  
  open @db_cursor;
  fetch next from @db_cursor into @isid;
  
  while @@FETCH_STATUS = 0
  begin
      SELECT @fk = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
      WHERE CONSTRAINT_NAME = 'FK_' + @isid + '_Firma';
      if not exists (select @fk) 
          begin
          print 'NULL: ' + @fk;
          select @statement = 'ALTER TABLE ' + @isid + ' add constraint FK_' + 
             @isid + '_Firma FOREIGN KEY(FirmaCode) REFERENCES Firma(FirmaCode)';
          exec(@statement);
      end
      print 'NOT NULL: ' + @fk;
      fetch next from @db_cursor into @isid;
  end
  close @db_cursor;
  
  commit transaction;
  </code></pre>
  
  <p>basic output i get is '<code>NOT NULL: FK_&lt;TableName&gt;_Firma</code>'</p>
  
  <p>Thank you for any help you can provide with my problem. </p>