Link to home
Start Free TrialLog in
Avatar of SolutionsTI
SolutionsTIFlag for Canada

asked on

How to drop a user or schema using dynamic SQL?

Hi folks,

I am actually migrating MSSQL 2000 databases to MSSQL 2008 with an automatic script that I created for the migration. I have one script that backups all the databases on the MSSQL 2000 server, and another script that restores all the databases backups to the new MSSQL 2008 server.

Everything works fine except the following portion of code :
SET @strSqlStatement = ''
SET @strSqlStatement = 'USE ' + @databaseName
PRINT @strSqlStatement
EXEC sp_executesql @strSqlStatement
	
SET @strSqlStatement = ''
SET @strSqlStatement = 'DROP SCHEMA ' + @userName
EXEC sp_executesql @strSqlStatement
	
SET @strSqlStatement = ''
SET @strSqlStatement = 'DROP USER ' + @userName
EXEC sp_executesql @strSqlStatement

Open in new window


Here is the error I get:
Msg 15151, Level 16, State 1, Line 1
Cannot drop the schema 'usrMarketing', because it does not exist or you do not have permission.
Msg 15151, Level 16, State 1, Line 1
Cannot drop the user 'usrMarketing', because it does not exist or you do not have permission.

Open in new window


It looks like the USE statement is not doing anything, because if I run the above portion of code in the SQL Server Management Studio client tool with the database dbMarketing selected from the "Available databases" list, the two DROP statements works like a charm.

What I would like to do is to DROP the schema and the orphan user dynamically. I use a cursor that loops through all the databases to RESTORE, fetching the name of the database and the user in the @databaseName and @userName variables.

Any thoughts?

Thanks you
Avatar of Daniel_PL
Daniel_PL
Flag of Poland image

Try this approach:





SET @strSqlStatement = 'DROP SCHEMA ' + @databaseName + '.' + @userName

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Daniel_PL
Daniel_PL
Flag of Poland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SolutionsTI

ASKER

Works like a charm.

Thank you for the quick solution!
Can you mark the solution? Thanks.