Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

T-SQL Looping? 1

Status
Not open for further replies.

soy4soy

IS-IT--Management
May 22, 2000
100
US
I have a query:

SELECT NAME FROM SYSDATABASES
where name like 'PSCPROD_%'
ORDER BY NAME

For each line/record of what this query returns, I would like to perform a DUMP DATABASE operation.

How can this be accomplished? I can do it in Perl with no problem, but I would prefer to use either T-SQL, Visual Basic, or Javascript so that I may use the SQLAgent to execute the script automatically.
 
It's a good idea to keep administration stuff inside the database so TSQL is probably the way to go.

Try using a cursor to spin through the result set & dump.

 
check out the stored procedure sp_msforeachdb.

I haven't used it but it should work the same as the sp_foreachtable procedure here is some sample code I use with that.

sp_msforeachtable "declare @cnt int
select @cnt=count(*) from ?
If @cnt > 0
begin
print '?'
select @cnt
end"

it lists out all of the tables in a database that have records in them. Note: the question mark is replaced by the name of the table / database in each iteration of the code.

 
Like bitbrain said, you can use cursor... here's the syntax:

DECLARE @name VARCHAR(50)
DECLARE @stmt NVARCHAR(100)
DECLARE dbnames CURSOR FOR
SELECT name FROM sysdatabases
WHERE name like 'PCSPROD_%'
OPEN dbnames
FETCH NEXT FROM dbnames INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @stmt = 'DROP DATABASE ' + @name
EXECUTE sp_executesql @stmt
FETCH NEXT FROM dbnames INTO @name
END
CLOSE dbnames
DEALLOCATE dbnames Andel
andelbarroga@hotmail.com
 
Thanks to all of you for your help! The syntax really helped out Andel!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top