I want to add users to the same role in more than one database. However the role may or may not be present in each database. How can I check if the role exists in each database and if it does, add users to that role?
e.g. IF role exists BEGIN Add user in role END
To find all the role assignments to users in SQL Server database, you can use the following query. SELECT r.name role_principal_name, m.name AS member_principal_name FROM sys. database_role_members rm JOIN sys. database_principals r ON rm.
The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.
try:
IF DATABASE_PRINCIPAL_ID('role') IS NULL
BEGIN
-- add user here
CREATE ROLE role AUTHORIZATION MyUser;
END
IF EXISTS
(
SELECT 1
FROM sys.database_principals
WHERE type_desc = 'DATABASE_ROLE'
AND name = 'name'
)
BEGIN
-- add user;
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With