Tuesday, July 19, 2016

Excute Command in All Database in SQL Server

This tip shows  How to  execute Command in All Database in Server using Stored Procedure .
The below code snippet we can use to create Stored Procedure 
  
  1. Create proc CustomExec(@strs nvarchar(max)  
  2. )  
  3. as begin  
  4.   
  5. DECLARE @ID  varchar(50)  
  6. DECLARE c CURSOR READ_ONLY FAST_FORWARD FOR  
  7.     SELECT name  
  8.     FROM master..sysdatabases where name like 'Test%' 
  9. -- Open the cursor  
  10. OPEN c  
  11.   
  12. FETCH NEXT FROM c INTO @id  
  13. WHILE (@@FETCH_STATUS = 0)  
  14. BEGIN  
  15.    
  16. DECLARE @command varchar(max)  
  17. SELECT @command = 'USE '+ @id +''  
  18. SET @command=@command+'  
  19.   
  20. Go'  
  21.   
  22.  Set @command =@command +@strs  
  23.   
  24. SET @command=@command+'  
  25.    
  26.   GO        
  27.    '  
  28. print @command  
  29.     FETCH NEXT FROM c INTO @id  
  30. END  
  31.   
  32. -- Close and deallocate the cursor  
  33. CLOSE c  
  34. DEALLOCATE c  
  35.   
  36. end  

No comments :

Post a Comment