2010-10-26 90 views
0

我已經多DBS具有相同的結構,我想對他們的循環來檢查這個選擇statment循環在SQL Server的所有數據庫查詢

select scan1,scan2,scan3 from customers where .............. 

輸出將是數據庫名稱,如果這個選擇有記錄 像:

db1 
db2 
db3 

等等...

回答

0

感謝所有試圖幫助我,但我找到了查詢,並在這裏它是,如果它可以幫助任何一個。

exec sp_MSforeachdb 
' 
if "?" like "Client%" and isnumeric(substring("?",7,4)) = 1 
BEGIN 
DECLARE @QueryString NVARCHAR(500) 
SET @QueryString = "Select Scan1,Scan2,scan3 from ?.dbo.Customers where Scan1 <> '''' or Scan2 <> '''' or Scan3 <> ''''" 
EXEC sp_executesql @QueryString 

IF @@RowCount > 0 
print "?" 
END 
' 

感謝

+0

是可鑑定與和其它[隱藏功能](http://stackoverflow.com/questions/121243/hidden-features-of-sql-server) – 2010-10-27 10:57:53

0

怎麼是這樣的:

WITH CTE AS 
(
    Select 'DB1' as DatabaseName From DB1.MyTable Where ... 
    UNION 
    Select 'DB2' as DatabaseName From DB2.MyTable Where ... 
    UNION 
    Select 'DB3' as DatabaseName From DB3.MyTable Where ... 
    <Add as many more as you need> 
) 

Select DatabaseName From CTE Where DatabaseName IS NOT NULL