-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGetColumnList.sql
More file actions
70 lines (61 loc) · 1.61 KB
/
GetColumnList.sql
File metadata and controls
70 lines (61 loc) · 1.61 KB
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
if object_id('dbo.GetColumnList') is not null
begin
exec ('drop function dbo.GetColumnList')
end
go
create function dbo.GetColumnList (@DatabaseName varchar(128), @SchemaName varchar(128), @TableName varchar(128), @ColumnsToIgnore xml, @ColumnList xml, @Alias varchar(6))
returns varchar(max)
as
begin
declare @ret varchar(max)
set @ret = (
select
','
+case when len(isnull(@Alias,'')) < 1 then '' else @Alias+'.' end
+'['+g.COLUMN_NAME+']'
from dbo.GlobalInformationSchema g
where TABLE_CATALOG = @DatabaseName
and TABLE_SCHEMA = @SchemaName
and TABLE_NAME = @TableName
and not exists
(
select 1
from @ColumnsToIgnore.nodes('columns/column') c(i)
where c.i.value('@name','varchar(30)') = g.COLUMN_NAME
)
and exists
(
select 1
from @ColumnList.nodes('columns/column') c(i)
where c.i.value('@name','varchar(30)') = g.COLUMN_NAME
union all
select 1
from sysobjects
where case when @ColumnList is null then 1 else 0 end=1
)
ORDER BY g.ORDINAL_POSITION
FOR XML PATH('')
)
set @ret = substring(@ret,2,(len(@ret)-1))
return @ret
end
go
-- Test the function
select dbo.GetColumnList(db_name()
,'sys'
,'columns'
,N'<columns>
<column name="object_id" />
<column name="column_id" />
</columns>'
,null
,'')
select dbo.GetColumnList(db_name()
,'sys'
,'tables'
,N'<columns>
<column name="object_id" />
<column name="schema_id" />
</columns>'
,null'
,'a')