-
Notifications
You must be signed in to change notification settings - Fork 0
/
drop_if_exists.sql
85 lines (73 loc) · 1.79 KB
/
drop_if_exists.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
if object_id('dbo.drop_if_exists') is not null
drop procedure dbo.drop_if_exists
GO
-- Drops the named object if it exists
create procedure dbo.drop_if_exists
@name nvarchar(max)
as
set nocount on
if @name is null
begin
raiserror('@name is required', 11, 1)
return
end
declare
@server sysname = parsename(@name, 4),
@database sysname = parsename(@name, 3),
@schema sysname = parsename(@name, 2),
@object sysname = parsename(@name, 1)
if @server is not null
begin
raiserror('Remote servers are not supported.', 11, 1)
return
end
declare
@type char(2),
@parent_name nvarchar(max),
@object_id int = object_id(@name)
declare @stmt nvarchar(max) = '
select
@type = type,
@parent_name = quotename(object_schema_name(parent_object_id)) + ''.'' + quotename(object_name(parent_object_id))
from ' + isnull(quotename(@database), '') + '.sys.objects
where object_id = @object_id'
exec sp_executesql
@stmt = @stmt,
@params = N'
@type char(2) out,
@parent_name nvarchar(max) out,
@object_id int',
@type = @type out,
@parent_name = @parent_name out,
@object_id = @object_id
declare @rowcount int = @@rowcount
if @rowcount = 0
begin
raiserror('Info: ''%s'' does not exist', 1, 1, @name)
return
end
declare @type_name varchar(10)
set @type_name = case
when @type in ('c', 'd', 'f', 'pk', 'uq')
then 'constraint'
when @type in ('fn', 'if', 'tf')
then 'function'
else case @type
when 'p'
then 'procedure'
when 'tr'
then 'trigger'
when 'u'
then 'table'
when 'v'
then 'view'
else null
end
end
set @stmt = isnull('use ' + quotename(@database) + '
', '') + case @type_name
when 'constraint' then 'alter table ' + @parent_name + ' drop constraint ' + quotename(@object)
else 'drop ' + @type_name + ' ' + quotename(@schema) + '.' + quotename(@object)
end
exec sp_executesql @stmt
GO