在多租户单独的架构数据库中查询表的所有版本

时间:2016-01-11 18:56:07

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

在多租户SQL Server数据库中,有多个具有相同名称的表副本,表的每个副本属于不同的模式,是否有任何方法可以在没有{{{}的情况下查询表的所有副本1}}?

类似的东西:

union

我相当肯定答案是否定的,谷歌搜索表明情况属实,但我想知道这样的事情是否可能?我很欣赏这些表可能有不同的列。

1 个答案:

答案 0 :(得分:0)

@tomReddox

看看这是否有帮助。这可以在存储过程中轻松编码,并且每次只需执行exec SP_Name而不是下面的冗长sp_MSforeachtable命令。

-- Create a Schema for demonstration
CREATE SCHEMA [SCH1] AUTHORIZATION [dbo]
GO

-- Create Table in Schema1 (= SCH1 )
create table [SCH1].TEST ( C1 int )
insert into  [SCH1].TEST values ( 1 ) 

-- Create Table in Schema2 ( = dbo )
create table dbo.TEST ( C1 int )
insert into  dbo.TEST values ( 2 ) 
insert into  dbo.TEST values ( 3 ) 

--  Create Results Table in dbo schema this will hold the results
Create Table dbo.Res ( C1 int ) -- Results Table that holds the union of all the *.TEST Tables. Make sure you name it anything other than Test !!


-- Use the sp_MSforeachtable command with the  @whereand  clause to filter only the TEST tables. 
-- This sp searches all schemas in the DB. must use alias for name as o.name
exec sp_MSforeachtable @command1='insert into dbo.RES select *  from ? ' 
     ,  @whereand = ' AND o.name LIKE ''TEST%'' ' 
     ,  @postcommand = ' select  * from dbo.Res '
Go
相关问题