SQL过程中的动态更改架构

时间:2014-03-10 15:51:34

标签: sql sql-server azure-sql-database

我有一个包含多个模式的数据库。在每个模式中,我得到了一个名为[Logs]的表,所以我的数据库表看起来像:

[s1].[Logs]
[s2].[Logs]
[s3].[Logs]
...
[sN].[Logs]

我每天都想运行存储过程,它将在上面的每个表上执行相同的操作。有没有办法将模式名称传递给存储过程?我在Azure上使用SQL。

2 个答案:

答案 0 :(得分:0)

不,它不是 - 除非SP使用动态SQL来执行你在SP中构造的一些SQL String。

这是通过sp_executesql存储过程

发生的

http://technet.microsoft.com/en-us/library/ms188001.aspx

有更多信息。

答案 1 :(得分:0)

Microsoft有一些未记录的过程,可以对表(sp_msforeachtable)和数据库(sp_msforeachdb)执行“foreach”操作。这两个都依赖于另一个名为sp_msforeachworker的未记录的proc,您可以利用它来创建foreachschema类型的例程。这是一篇展示这种方法的文章(需要注册)here

也就是说,它不太可能支持Azure中的所有内容,因此您可能需要使用原始循环来构建自己的Azure:

declare @schemas table (i int identity(1,1), name sysname);
insert into @schemas
    select name from sys.schemas where name like 's[0-9]%';

declare @i int, @name sysname, @cmd nvarchar(max);
select @i = min(i) from @schemas;

while @i is not null
begin

    select @name = name from @schemas where i = @i;

    set @cmd = replace(N'select count(*) from [{0}].[Logs];', '{0}', @name);
    print @cmd;

    --exec(@cmd);
    select @i = min(i) from @schemas where i > @i;
end