-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGetTableJoin.sql
More file actions
46 lines (39 loc) · 1.05 KB
/
GetTableJoin.sql
File metadata and controls
46 lines (39 loc) · 1.05 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
if object_id('dbo.GetTableJoin') is not null
begin
exec ('drop function dbo.GetTableJoin')
end
go
create function dbo.GetTableJoin (@DatabaseName varchar(128), @SchemaName varchar(128), @TableName varchar(128), @FirstAlias varchar(6), @SecondAlias varchar(6))
returns varchar(max)
as
begin
declare @ret varchar(max)
set @ret =
(
select
' and '+case when @FirstAlias is null or len(@FirstAlias) < 1 then ''
else @FirstAlias+'.' end
+'['+g.COLUMN_NAME+'] = '+@SecondAlias+'.['+g.COLUMN_NAME+']'
from dbo.GlobalInformationSchema g
where TABLE_CATALOG = @DatabaseName
and TABLE_SCHEMA = @SchemaName
and TABLE_NAME = @TableName
ORDER BY g.ORDINAL_POSITION
for xml path('')
)
set @ret = substring(@ret,6,len(@ret)-4)
return @ret
end
go
-- Test the function
select dbo.GetTableJoin(db_name()
,'sys'
,'tables'
,'s'
,'t')
select dbo.GetTableJoin(db_name()
,'sys'
,'tables'
,''
,'t')
go