[RESOLVED] SQL Script Creator
I have created the following SQL code to create a script to change the owner of a MS SQL Server database:
SQL Code:
/*Change Owners of a table:*/
DECLARE @OldOwner CHAR(25)
DECLARE @NewOwner CHAR(25)
SET @OldOwner ='dbo'
SET @NewOwner = 'ADM'
SELECT 'exec sp_changeobjectowner ' + CHAR(39) + RTRIM(LTRIM(@OldOwner)) + '.' + _
Name + CHAR(39) +',' + CHAR(39)+ RTRIM(LTRIM(@NewOwner)) + CHAR(39) Owner_Change_Script
FROM sysobjects
WHERE xtype = 'U' AND UID = 5
ORDER by Name
This code outputs the following:
SQL Code:
exec sp_changeobjectowner 'dbo.CLASSES','ADM'
exec sp_changeobjectowner 'dbo.CAUSES','ADM'
exec sp_changeobjectowner 'dbo.LEVEL','ADM'
exec sp_changeobjectowner 'dbo.ACCIDENTS','ADM'
exec sp_changeobjectowner 'dbo.ACTIONS','ADM'
But I want the Script to insert a 'Go' in between each exec statement like this:
SQL Code:
exec sp_changeobjectowner 'dbo.CLASSES','ADM'
GO
exec sp_changeobjectowner 'dbo.CAUSES','ADM'
GO
exec sp_changeobjectowner 'dbo.LEVEL','ADM'
GO
exec sp_changeobjectowner 'dbo.ACCIDENTS','ADM'
GO
exec sp_changeobjectowner 'dbo.ACTIONS','ADM'
GO
But for the life of me I can't seem to figure it out. Any ideas how I can go about doing this??? The databases I have to convert have hundreds and hundreds of tables and when it throws an error I want to be able to click on the error and be brought to the line that threw the error.
Thanks!
Re: [RESOLVED] SQL Script Creator
I love the challenge of making something SET-based - it's great!
I've done this before so it came quickly ;)
Code:
/*Change Owners of a table:*/
Declare @Dup Table (Dup int)
Insert into @Dup values (1)
Insert into @Dup values (2)
DECLARE @OldOwner CHAR(25)
DECLARE @NewOwner CHAR(25)
SET @OldOwner ='dbo'
SET @NewOwner = 'ADM'
SELECT Case When Dup=2 Then 'Go' Else 'exec sp_changeobjectowner ' + CHAR(39) + RTRIM(LTRIM(@OldOwner)) + '.' +
Name + CHAR(39) +',' + CHAR(39)+ RTRIM(LTRIM(@NewOwner)) + CHAR(39) End Owner_Change_Script
FROM sysobjects
Left Join @Dup on 1=1
WHERE xtype = 'U' --AND UID = 5
ORDER BY Name,Dup
Create a dummy table with two rows. Join to that table with a "forced true".
You end up doubling your rows.
And each row has a unique identifier from the dummy table.
You end up getting:
Code:
Owner_Change_Script
------------------------------------------------
exec sp_changeobjectowner 'dbo.Addr_T','ADM'
Go
exec sp_changeobjectowner 'dbo.AppConnect_T','ADM'
Go
exec sp_changeobjectowner 'dbo.AppElem_T','ADM'
Go
.
.
.
Re: [RESOLVED] SQL Script Creator