generated from MaxGripe/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sa.sql
60 lines (48 loc) · 1.19 KB
/
sa.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Find jobs not owned by 'sa'
*/
SELECT j.name, suser_sname(j.owner_sid) AS 'job_owner'
FROM msdb.dbo.sysjobs j
WHERE j.owner_sid <> 0x01 order by 1;
/*
Find databases not owned by 'sa'
*/
SELECT d.name, suser_sname(d.owner_sid) AS 'database_owner'
FROM master.sys.databases d
WHERE suser_sname(d.owner_sid) <> 'sa' order by 1;
/*
Auto-fix job_owner -> sa
*/
DECLARE @job_name NVARCHAR(128);
DECLARE job_cursor CURSOR FOR
SELECT j.name
FROM msdb.dbo.sysjobs j
WHERE j.owner_sid <> 0x01;
OPEN job_cursor;
FETCH NEXT FROM job_cursor INTO @job_name;
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC msdb.dbo.sp_update_job
@job_name = @job_name,
@owner_login_name = 'sa';
FETCH NEXT FROM job_cursor INTO @job_name;
END;
CLOSE job_cursor;
DEALLOCATE job_cursor;
/*
Auto-fix database_owner -> sa
*/
DECLARE @database_name NVARCHAR(128);
DECLARE db_cursor CURSOR FOR
SELECT d.name
FROM master.sys.databases d
WHERE suser_sname(d.owner_sid) <> 'sa';
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @database_name;
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC('ALTER AUTHORIZATION ON DATABASE:: [' + @database_name + '] TO sa');
FETCH NEXT FROM db_cursor INTO @database_name;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;