如何使用IF EXISTS / IF NOT EXISTS语句添加外键?

时间:2014-07-17 10:11:45

标签: sql sql-server cursor foreign-keys sql-insert

我试图通过检查密钥是否已经存在而将外键插入多个表中,如果不存在则应该插入它。 但是当我尝试运行我的脚本时,它只是跳过整个插入部分,即使所有单个命令都正常工作。 (我使用MS SQL Server 2008)

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;

我得到的基本输出是&#39; NOT NULL: FK_<TableName>_Firma&#39;

感谢您提供有关我的问题的任何帮助。

1 个答案:

答案 0 :(得分:1)

尝试

begin transaction;

declare @isid as nvarchar(500);
declare @fk as nvarchar(500);
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 = null
    SELECT @fk = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
    WHERE CONSTRAINT_NAME = 'FK_' + @isid + '_Firma';
    if (@fk is null) 
        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;