SQL过程中的动态更改模式

SQL过程中的动态更改模式,sql,sql-server,azure-sql-database,Sql,Sql Server,Azure Sql Database,我有一个具有多个模式的数据库。在每个模式中,我都得到一个名为[Logs]的表,因此我的数据库表如下所示: [s1].[Logs] [s2].[Logs] [s3].[Logs] ... [sN].[Logs] 每天我都想运行存储过程,它将对上面的每个表执行相同的操作。有没有办法将架构名称传递到存储过程中?我正在Azure上使用SQL。不,它不是-除非SP使用动态SQL来执行您在SP中构建的某些SQL字符串 这是通过sp_executesql存储过程实现的 有更多信息。Microsoft有一些

我有一个具有多个模式的数据库。在每个模式中,我都得到一个名为[Logs]的表,因此我的数据库表如下所示:

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

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

不,它不是-除非SP使用动态SQL来执行您在SP中构建的某些SQL字符串

这是通过sp_executesql存储过程实现的


有更多信息。

Microsoft有一些未记录的过程,可以对表(
sp_msforeachtable
)和数据库(
sp_msforeachdb
)执行“foreach”操作。这两者都依赖于另一个名为
spmsforeachworker
的未记录过程,您可以利用该过程创建foreachschema类型的例程。有一篇文章(reg required)演示了这种方法

这就是说,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
可能对你有用。