Tuesday 15 August 2017

Get the list User which are Enabled or Disabled in all the databases in SQL Sever

With the help of below sql script we will get the list of enabled or disabled user.
DECLARE @UserName VARCHAR(128)
IF OBJECT_ID('tempdb..##Temp_Table') IS NOT NULL
DROP TABLE ##Temp_Table
CREATE TABLE ##Temp_Table (
ServerName VARCHAR(1000),
DatabaseName VARCHAR(500)
,UserName VARCHAR(500)
,IsEnabled INT
)
DECLARE @SQLStatement VARCHAR(MAX)
SET @SQLStatement='Insert into ##Temp_Table
Select @@ServerName AS ServerName,DB_Name() AS
DatabaseName,name, hasdbaccess
FROM sys.sysusers '
Print @SQLStatement
DECLARE @DatabaseName AS VARCHAR(500)
--DECLARE CURSOR
DECLARE CUR CURSOR
FOR
--Choose the DBs on which you would like to run the script
SELECT NAME
FROM sys.databases
WHERE database_id > 4
--OPEN CURSOR
OPEN CUR
--NEXT NEXT RECORD
FETCH NEXT
FROM CUR
INTO @DatabaseName
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @DBName AS NVARCHAR(500);
SET @DBName = QUOTENAME(N'' + @DatabaseName + '');
--USE Dynamic SQL To Change DB name and run Check If user Enabled or Disabled in Database
EXEC (N'USE ' + @DBName + N'; EXEC('''+@SQLStatement+''');');
FETCH NEXT
FROM CUR
INTO @DatabaseName
END
CLOSE CUR
DEALLOCATE CUR
Select * From ##Temp_Table
See the output.
 

No comments:

Post a Comment

If you have any doubt, please let me know.

Popular Posts