在T-SQL中创建server.database.table的动态路径

时间:2012-10-02 09:06:33

标签: sql-server sql-server-2008 tsql dynamic-sql

我正在尝试动态创建表格。一个数据库(@sourcedatabase)中的表用于在另一个数据库(@targetdatabase)中创建表。

当我明确命名数据库时,这很好用。但是,我希望它们是动态的,如下例所示。我已经阅读了很多关于这一点,我很喜欢使用像

这样的东西
set @sql = 'DROP TABLE ' + @targetdatabase + '.' + @SomeNAME 
execute (@sql)

但是当它变得更复杂时,我感到很茫然:

declare @sourcedatabase as varchar(max) = 'DATABASE1'
declare @targetdatabase as varchar(max) = 'DATABASE2'

declare @HighestID as int = (SELECT  max(Id) FROM @sourcedatabase.system.Organisationtype)
declare @i as int = (SELECT  max(Id) FROM @sourcedatabase.system.Organisationtype)

while @i >= (SELECT  min(Id) FROM @sourcedatabase.system.LaagTypeOrganisatie)
BEGIN
--SOME ACTIONS
set @i = @i + 1 
END 

declare @x as int = (select count(*) from @targetdatabase.sys.tables where name = @SomeNAME)

IF   @x <> 0
BEGIN
set @sql = 'DROP TABLE ' + @targetdatabase + '.' + @SomeNAME 
execute (@sql)
END

如您所见,我希望拥有数据库命名变量。 将整个脚本转换为一个exec语句非常复杂,阅读起来不是很漂亮。 在文本文件中读取此脚本,在@targetdatabase和@sourcedatabase上替换然后执行它是不是一个想法?如果是这样,将如何做?

我期待着您的想法和贡献!

编辑:脚本作为作业者执行

1 个答案:

答案 0 :(得分:0)

目前尚不清楚如何执行脚本,但假设您使用的是sqlcmd.exe或SSMS,则可以使用sqlcmd scripting variables在运行时替换变量。