2010-10-18 106 views
1

我有方案,我想將其轉換爲查詢。 我的情景: 我有很多具有相同結構的客戶端「Clientxxxx」我想讓所有這些dbs的循環獲取來自一個表的數據存在於所有這些dbs中,這些dbs被稱爲「EventLog」這些事件日誌記錄在此表中,在所謂的「門戶」多個數據庫之間的複雜SQL Server查詢

另一個分貝我想每一個客戶在其他DBS「Clientxxxx」,「門戶網站」分貝與他的事件日誌時,從「事件日誌」表

db:Client1   db:Client2   db:Client3 
table:"EventLog" table:"EventLog"  table:"EventLog" 

each client has his db and his data in Portal db 

db:portal 
table:Clients 

query: 
Client1 data 
his event logs 
client2 data 
his event logs 
and so on 
........ 
........ 
........ 
........ 

我需要一些幫助,請。

感謝

+0

出於興趣,我可以詢問設計決策背後的原因,爲每個客戶分配他們自己的單獨數據庫嗎? – 2010-10-19 08:06:14

回答

0

通常情況下,我使用動態SQL方法,用遊標遍歷所有的數據庫,插入到統一表變量,然後選擇變量的了:

declare @return (dbname varchar(100), 
       <<dataset spec for EventLog>>) 

declare @db varchar(100) 
declare @sql varchar(max) 

declare recscan cursor for 
select name from sys.databases 
where database_id not in (1,2,3,4) --excludes system databases 

open recscan 
fetch next from recscan into @db 

while @@fetch_status = 0 
begin 
    set @sql = 'select '''[email protected]+''',* from '[email protected]+'..eventlog' 

    insert into @return 
    exec(@sql) 

    fetch next from recscan into @db 
end 

close recscan 
deallocate recscan 

select * from @return 

注意,我創建額外的字段,並將數據庫名稱作爲顯式字符串值在動態查詢中,以便我可以分解數據的來源。我還爲表對象使用了3部分命名,但是您可以將動態構建的USE語句插入到SQL變量中。

1

我會做到以下幾點:

Portal分貝在它創建一個視圖具有此:

vw_AggregateClients:

SELECT 'Client1' as clientName, * from Client1.dbo.EventLog 
UNION 
SELECT 'Client2', * from Client2.dbo.EventLog 
UNION 
SELECT 'Client3', * from Client3.dbo.EventLog 

,然後查詢它像此:

SELECT * from vw_AggregateClients as ac 
INNER JOIN Clients as c 
ON ac.clientName = c.ClientName 

如果您的客戶端數據庫數量很大,或者您不知道有多少客戶端數據庫,那麼您可能必須使用dynamic sql。如果你走這條路線,那麼我會鏈接到一篇好文章。

+1

@ + 1:同意,使用視圖的解決方案實現也是我的建議,也就是說,如果當然提供重新設計您的應用程序平臺和數據庫體系結構不是一種選擇:-) – 2010-10-19 08:04:42