开发者

Loop on all database query in sql server

开发者 https://www.devze.com 2023-01-22 06:36 出处:网络
I have multi dbs with same structure I want to loop on them to check this select statment select scan1,s开发者_StackOverflow中文版can2,scan3 from customers where ..............

I have multi dbs with same structure I want to loop on them to check this select statment

select scan1,s开发者_StackOverflow中文版can2,scan3 from customers where ..............

the output would be database name if this select has records like that:

db1
db2
db3

and so on ...


How about something like this:

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


thanks for all trying to help me but i found the query and here it is if it can help any one.

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
'

thanks

0

精彩评论

暂无评论...
验证码 换一张
取 消