SolutionsTI
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 :
Here is the error I get:
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
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
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.
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Works like a charm.
Thank you for the quick solution!
Thank you for the quick solution!
Can you mark the solution? Thanks.
Open in new window