在SQL Server中动态构建和执行语句

时间:2016-05-18 04:51:55

标签: sql-server

您好我正在尝试禁用数据库上的所有外键约束,因为我正在加载一些数据。因为它是每月工作的一部分,我想动态地做它,以便它可以处理任何变化。我试图在不使用游标或临时表的情况下执行此操作。我已经构建了下面的语句,但到目前为止,这只创建了一个alter语句,而我希望它执行alter语句

declare @SQLStatement as nvarchar(4000)
SET @SQLStatement = 'exec (''select ''''alter table prpcref_mjp''''        + ''''.'''' + b.name + ''''.'''' + parent_tbl.name +  '''' NOCHECK CONSTRAINT '''' +  fk.name
from prpcref_mjp.sys.foreign_keys fk
inner join prpcref_mjp.sys.all_objects parent_tbl
    on fk.parent_object_id = parent_tbl.object_id
inner join prpcref_mjp.sys.schemas b
    on fk.schema_id = b.schema_id'')'
EXECUTE sp_executesql @SQLStatement

3 个答案:

答案 0 :(得分:1)

将exec保留在字符串之外:

 select exec('alter table prpcref_mjp''' + 
'';'.'''' + 
        b.name + ''''.'''' + parent_tbl.name +  
            '''' NOCHECK CONSTRAINT '''' +  fk.name
                from prpcref_mjp.sys.foreign_keys fk
                inner join prpcref_mjp.sys.all_objects parent_tbl
                    on fk.parent_object_id = parent_tbl.object_id
                inner join prpcref_mjp.sys.schemas b
                    on fk.schema_id = b.schema_id')

答案 1 :(得分:0)

这是另一种创建包含所有DDL语句的字符串的方法:

declare @SQLStatement nvarchar(4000) = ''
select @SQLStatement += 'ALTER TABLE prpcref_mjp.' + b.name + '.' + parent_tbl.name + ' DROP CONSTRAINT ' + fk.name + ';' + char(13) + char(10)
  from prpcref_mjp.sys.foreign_keys fk
 inner join prpcref_mjp.sys.all_objects parent_tbl
    on fk.parent_object_id = parent_tbl.object_id
 inner join prpcref_mjp.sys.schemas b
    on fk.schema_id = b.schema_id
print @SQLStatement
exec(@SQLStatement)

您可以添加where子句来限制您要修改的表格。如果您想在实际运行代码之前查看代码,请在最后注释掉exec()

请注意,我添加了+ char(13) + char(10)以使print语句的输出更易于阅读。

答案 2 :(得分:0)

    select @NSQL = 'set @SQLStatement_out = ''''
select @SQLStatement_out += ''ALTER TABLE ' + @dbname + '.'' + b.name + ''.'' + parent_tbl.name + '' NOCHECK CONSTRAINT '' + fk.name + '';'' + char(13) + char(10)
  from ' + @dbname + '.' + 'sys.foreign_keys fk
 inner join ' + @dbname + '.' +'sys.all_objects parent_tbl
    on fk.parent_object_id = parent_tbl.object_id
 inner join ' + @dbname + '.' + 'sys.schemas b
    on fk.schema_id = b.schema_id
    exec(@SQLStatement_out) '

SET @ParmDefinition = N'@SQLStatement_out varchar(max) OUTPUT';

exec sp_executesql @NSQL, @ParmDefinition, @SQLStatement_out=@SQLStatement OUTPUT;

exec(@SQLStatement)