Regarding Dynamic join -- Need help
suppose i have three tables called
Department
-------------
DeptID DeptName
------ ---------
1 Accounts
2 Sales
3 Purchase
Location
----------
LocID LocName
------ --------
1 China
2 UK
3 USA
4 Ge开发者_StackOverflowrmany
Employee
----------
EmpID Name Salary LocID DeptID
----- ----- ------ ----- -------
1 jhon 15000 1 2
2 Sina 12500 3 1
3 Keith 17420 2 3
EMPID is PK of employee table and also employee table joined with location and department by locid and deptid.
in simple sql we can join very easily and show the data like
empid name salary locname deptname.
but in my case i do not want to hard code the join by tablename.columnname.
rather i want query the system tabele and get the relationship and build the join dynamically. i am not very good in sql. so please someone help with sample as a result i can construct the join dynamically.............please help.
You can get the primary key columns of a table like this:
select *
from sys.identity_columns c
where c.object_id = object_id('TableName')
Then you can get the foreign key columns of a table like this:
select *
from sys.foreign_key_columns fkc
inner join sys.columns c on c.object_id = fkc.parent_object_id and c.column_id = fkc.parent_column_id
where fkc.parent_object_id = object_id('TableName')
In this way you can generate the SQL for a join between the tables. This would involve a lot of string manipulation in SQL, which is not very pleasant.
Overall, I would suggest not using dynamic SQL if possible. Is there a strong reason the SQL needs to be dynamic?
精彩评论