-
Notifications
You must be signed in to change notification settings - Fork 0
/
0002.sqlcode.sql
93 lines (74 loc) · 2.79 KB
/
0002.sqlcode.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
-- We want to re-create the procedure DropCodeSchema.
-- First, everything related to this procedure must be dropped
-- before it is re-created in the end.
drop procedure sqlcode.DropCodeSchema;
create procedure sqlcode.DropCodeSchema(@schemasuffix varchar(50))
as begin
set xact_abort, nocount on
begin try
declare @msg varchar(max)
declare @sql nvarchar(max)
if @@trancount = 0 throw 55001, 'You should run sqlcode.CreateCodeSchema within a transaction', 1;
declare @schemaname nvarchar(max) = concat('code@', @schemasuffix)
declare @schemaid int = (select schema_id from sys.schemas where name = @schemaname);
if @schemaid is null
begin
set @msg = concat('Schema [code@', @schemasuffix, '] not found');
throw 55002, @msg, 1;
end
-- Drop views, functions, procedures
declare @curVFP cursor; -- VFP: views, functions, procedures
set @curVFP = cursor local read_only forward_only for
select
concat('drop ', v.DropType, ' ', quotename(@schemaname), '.', quotename(o.name))
from sys.objects as o
cross apply ( values ( case
when o.type = 'FN' then 'function'
when o.type = 'IF' then 'function'
when o.type = 'TF' then 'function'
when o.type = 'P' then 'procedure'
when o.type = 'PC' then 'procedure'
when o.type = 'V' then 'view'
end )) v(DropType)
where o.schema_id = @schemaid and v.DropType is not null;
open @curVFP
fetch next from @curVFP into @sql;
while (@@fetch_status = 0)
begin
exec sp_executesql @sql;
fetch next from @curVFP into @sql;
end
close @curVFP
deallocate @curVFP
-- Drop types
declare @curT cursor -- T: types
set @curT = cursor local read_only forward_only for
select
concat('drop type ', quotename(@schemaname), '.', quotename(t.name))
from sys.types as t
where t.schema_id = @schemaid;
open @curT
fetch next from @curT into @sql;
while (@@fetch_status = 0)
begin
exec sp_executesql @sql;
fetch next from @curT into @sql;
end
close @curT
deallocate @curT
-- Finally drop the schema itself
set @sql = concat('drop schema ', quotename(@schemaname))
exec sp_executesql @sql;
end try
begin catch
if @@trancount > 0 rollback;
;throw
end catch
end
go
create certificate [cert/sqlcode2] encryption by password = 'SqlCodePw1%' with subject = '"sqlcode2"';
add signature to sqlcode.DropCodeSchema by certificate [cert/sqlcode2] with password = 'SqlCodePw1%'
create user [certuser/sqlcode2] from certificate [cert/sqlcode2] ;
alter role db_owner add member [certuser/sqlcode2];
alter certificate [cert/sqlcode2] remove private key;
grant execute on sqlcode.DropCodeSchema to [sqlcode-deploy-role];