How to use SQL server foreach loop in SQL scripts?

1.1K    Asked by shivaniChavan in Salesforce , Asked on Aug 23, 2021

In Powershell I use foreach to run a function through a list of targets.

I was wondering that if there is anything similar to foreach in SQL, so I can run the same query through multiple DBs I chose and save the results to one CSV file?


Answered by Radhika Patel

You can use SQL server foreach loop in T-SQL against a set of data in T-SQL.SQL server foreach loop is set to keep looping as long as there is at least a row of data in @Enumerator.


PowerShell is still viable and potentially a lot easier, especially when you leverage dbatools.

You can use Get-DbaDatabase to not only get the databases but also easily filter out problematic ones you probably don't want to execute against (system dbs, offline dbs, etc):

Get-DbaDatabase -Status 'Normal' -ExcludeSystem -OnlyAccessible

And then run Invoke-DbaQuery to run your command against each of the databases returned.



Your Answer

Interviews

Parent Categories