Hi guys,
I am trying to create loop to drop and create users in user_databases which start from database_id = 5
The query that I'm trying to achieve like this
Because I don't wanna generate 5-6 blocks query like that, so I'm creating the loop like this code
for some reason the Drop user works only database_id = 5 not for the 6,7,8,etc. but the SELECT @DB_Name is working. I suspect the use @DB_NAME is not working properly.
Any idea how to fix my codes?
Thanks heaps guys,
I am trying to create loop to drop and create users in user_databases which start from database_id = 5
The query that I'm trying to achieve like this
Code:
USE database_name
IF EXISTS (SELECT * FROM sys.database_principals WHERE name = 'AU\username')
BEGIN
DROP USER [AU\username];
END
CREATE USER [AU\username] FOR LOGIN [AU\username];
Because I don't wanna generate 5-6 blocks query like that, so I'm creating the loop like this code
Code:
DECLARE @DB_Id Int,
@DB_Max Int,
@DB_Name varchar(100),
@SQL_SCRIPT nvarchar(200)
SET @DB_Id = 5
SELECT @DB_Max = max(database_id) FROM sys.databases
WHILE @DB_Id <= @DB_Max
BEGIN
SELECT @DB_Name = name from sys.databases WHERE database_id = @DB_Id
SELECT @DB_Name
SET @SQL_SCRIPT = 'USE ' + @DB_Name
SELECT @SQL_SCRIPT
EXEC sp_executesql @SQL_SCRIPT
IF EXISTS (SELECT * FROM sys.database_principals WHERE name = 'AU\username')
BEGIN
DROP USER [AU\username];
END
CREATE USER [AU\username] FOR LOGIN [AU\username];
SET @DB_Id = @DB_Id + 1
END
for some reason the Drop user works only database_id = 5 not for the 6,7,8,etc. but the SELECT @DB_Name is working. I suspect the use @DB_NAME is not working properly.
Any idea how to fix my codes?
Thanks heaps guys,