views:

146

answers:

3

I have a stored procedure that creates a database (ex: sp_createDB). In the similar fashion I have to create a 100's of databases using that one. So that I have to put it in a loop. But I don't know how to do it sqlserver. How can I do this in sqlserver.

Help me in this regard.

Thanks

+2  A: 

You can use ...

exec sprocName
GO 100

See more here. In general, it's ...

GO [COUNT]

See, MSDN.

JP Alioto
Wouldn't a while loop be nicer?
Tetraneutron
Hi JP, look at my answer below - http://stackoverflow.com/questions/1108017/how-to-execute-a-stored-procedure-continuosly/1108040#1108040 - for a loophole if you use the "GO [COUNT]" method.
Kirtan
@Tetraneutron: In this case I would actually disagree, although I have not used this method, ever, it's clearly quite elegant due to simplicity. Could confuse coders not familiar with the syntax though.
John Sansom
this could be a good option if the code within the procedure can determine the name of the database
KM
+3  A: 

JP's answer is correct technically (GO [COUNT] can be used to repeat a batch of statements COUNT times), but there's a logical mistake. Your stored procedure will need different parameters everytime it executes (as it has to create unique DBs, right?), so you'll have to loop around using WHILE like this -

DECLARE @Counter INT
SET @Counter = 1

DECLARE @DBName VARCHAR(20)

WHILE (@Counter <= 100)
BEGIN
    PRINT @Counter
    @DBName = 'DB' + CAST(@Counter AS VARCHAR)
    EXEC dbo.CreateDB @DBName
END
GO
Kirtan
the OP doesn't give many details, but it may be possible for the procedure to determine the name of the database, so a parameter might not be necessary.
KM
If that is so, then he can definitely use JP's approach. But ideally this is the case, so I have added the loop, and a parameter to the stored procedure.
Kirtan
+1  A: 

A while loop would be fine to call it N times as others have suggested, but...

DO NOT NAME YOUR PROCEDURES SP_ ...
DO NOT NAME YOUR PROCEDURES SP_ ...
DO NOT NAME YOUR PROCEDURES SP_ ...

Within Sql Server, "sp_ ..." is reserved for system stored procedures, and could confuse people familiar with that convention! It could cause issues if Sql Server ever implements their own "sp_createDB" Procedure. Also, stored procedures will run fractionally slower if they start with a prefix of sp_ . This is because SQL Server will look for a system stored proc first. As a result, it NOT recommend to start stored procs with a prefix of sp_

KM