Skip to content

Script to list out all the SQL Server logins

Script to list out all the SQL Server logins along with its properties. The output of this script will be a create login script which can be run on the target machine where all these logins are to be migrated. You will see their are two selct queries in this script. First select query is to pull out all the SQL authenticated logins and second script will pull out all the Windows authenticated logins.

SELECT 'CREATE LOGIN ' + QUOTENAME(name) + ' WITH PASSWORD=' + sys.fn_varbintohexstr(password_hash) + ' HASHED, SID=' + sys.fn_varbintohexstr(sid) + ', ' + 'DEFAULT_DATABASE='+ QUOTENAME(COALESCE(default_database_name, 'master')) + ', DEFAULT_LANGUAGE=' + QUOTENAME(COALESCE(default_language_name, 'us_english')) + ', CHECK_EXPIRATION=' + CASE is_expiration_checked WHEN 1 THEN 'ON' ELSE 'OFF' END + ', CHECK_POLICY=' + CASE is_policy_checked WHEN 1 THEN 'ON' ELSE 'OFF' END as 'SQL Server Logins' FROM sys.sql_logins WHERE name not like 'sa' UNION ALL SELECT 'CREATE LOGIN ' + QUOTENAME(name) + ' FROM WINDOWS WITH ' + 'DEFAULT_DATABASE='+ QUOTENAME(COALESCE(default_database_name, 'master')) + ', DEFAULT_LANGUAGE=' + QUOTENAME(COALESCE(default_language_name, 'us_english')) as 'SQL Server Logins' FROM sys.server_principals WHERE type IN ('U','G')