Find relationship between any table A and B in Sql Server - sql-server

Suppose we have the following tables, with pretty foreign keys in place.
CREATE TABLE Person
(
Id int not null
--other stuff
)
CREATE TABLE Employee
(
Id int not null,
PersonId int not null,
UserId int null
--other stuff
)
CREATE TABLE User
(
Id int not null,
Name varchar(25) not null,
Password varchar(25) not null
--other stuff
)
CREATE TABLE Roles
(
Id int not null
--other stuff
)
CREATE TABLE UserRoles
(
UserId int not null,
RoleId int not null
--other stuff
)
What are the ways(query, additional software?) to ask
"What is the relationship between table X and Y?"
E.g. I would like to 'ask' :
What is the relationship between tables Person and Roles?
Expected answer :
Person 1:N Employee 1:1 User 1:N UserRoles N:1 Roles
Note that tables Person and Roles do not have a direct relationship. The expected result should list the tables in-between of these two.
Something like this. A diagram representation would do, but it should only have the tables involved in the relationship.
Why I can't use "Database Diagrams" in SSMS.
Creating a relevant diagram with only needed tables takes too much time looking up the references by hand.
I can't use "Add Related tables" because it makes the diagram absolutely unreadable by adding 200+ tables.
The difference from diagramming would be that I only want to input two table names.

I believe this might be what you are looking for:
select t.name as TableWithForeignKey,
c.name as ForeignKeyColumn,
t2.name as DependentOnTable,
c2.name as ReferencedColumn,
N'N:1'
from sys.foreign_key_columns as fk
inner join sys.tables as t
on fk.parent_object_id = t.object_id
inner join sys.columns as c
on fk.parent_object_id = c.object_id
and fk.parent_column_id = c.column_id
inner join sys.columns as c2
on c2.object_id = fk.referenced_object_id
and c2.column_id = fk.referenced_column_id
inner join sys.tables as t2
on t2.object_id = c2.object_id
order by TableWithForeignKey
Note that all relationships in SQL server are 1:N because
neither a 1:1 can be established: How do I create a real one-to-one relationship in SQL Server
nor a N:N relationship can be established: Foreign Key to non-primary key
If you want to setup such relationships then you can merely use the extended properties to write it down for yourself and then "manually" enforce it.

Related

SQLite query with 3 entities in Hibernate 4 (nested join?)

I have the following tables in my database (SQLite):
CREATE TABLE product (
id INTEGER NOT NULL,
name TEXT,
PRIMARY KEY (id)
)
CREATE TABLE feedback(
product INTEGER PRIMARY KEY,
score NUMERIC,
textnote VARCHAR(255),
FOREIGN KEY(product) REFERENCES product(id)
)
CREATE TABLE product_detail (
id INTEGER NOT NULL,
product INTEGER,
description TEXT,
url VARCHAR,
PRIMARY KEY (id),
FOREIGN KEY(product) REFERENCES product (id),
)
So feedback is in a one-to-one relationship with product and product_detail is in a many-to-one relationship with product.
I am trying to write a SQLite query for Hibernate 4 that will give me all the attributes from the 3 tables in one single table. All I came with by far is this:
String hql = "SELECT p.id, p.name, d.id, d.description, d.url " +
"FROM ProductDetail d INNER JOIN d.product AS p";
I'm correctly obtaining the values I want from product and product_detail. How can I add to the query also the information in feedback? I know all products have at least one product detail, but I can't say the same about feedback: most of the products don't have a feedback. I think I should use a LEFT JOIN but I can't figure out how...
Note that as I'm using Hibernate I have all classes relative to the tables in my application (Feedback, ProductDetail and Product).
You must also join feedback:
SELECT
p.id, p.name,
f.score, f.textxnote,
d.id, d.description, d.url
FROM product p
INNER JOIN feedback f ON f.product = p.id
INNER JOIN ProductDetail d ON d.product = p.id
You may change to LEFT the joins if there is a case that a product does not have a row in either of the tables feedback and ProductDetail.

Querying multiple tables two being junction tables

I am trying to write a sql query that queries records from multiple tables which involved junction tables. The Userprofile table has relationship with Role and team table and one to one relationship with TimeZone table.
I am trying to achieve a query that will pull records from UserProfile table as well relevant records from Role , team and timezone table. I have tried to write a query and it is getting overly complex. Could somebody verify my query and tell me the right way to do it
The tables are as follows
UserProfile table
[EmployeeID]
[Forename]
[Surname]
[PreferredName]
[DefaultLanguageCode]
[DefaultCountryCode]
[TimeZoneID]
[Domain]
[NetworkID]
Team table
[TeamID]
[CountryCode]
[TeamName]
[TeamDescription]
UserTeamLinkTable
[UserProfileTeamLinkID]
[TeamID]
[UserProfileID]
[isDefault]
[isActive]
UserRole Table
[RoleID]
[RoleDescription]
[isActive]
UserRoleLink Table
[UserProfileRoleLinkID]
[RoleID]
[UserProfileID]
[isActive]
TimeZone table
[TimeZoneID]
[TimeZoneCode]
[TimeZone]
[TimeZoneName]
Query
select
userprofile.[UserProfileID]
,userprofile.[EmployeeID]
,userprofile.[Forename]
,userprofile.[Surname]
,userprofile.[PreferredName]
,userprofile.[DefaultCountryCode]
,userprofile.[DefaultLanguageCode]
,userprofile.[TimeZoneID]
,userprofile.TeamID
,userprofile.TeamName
,userprofile.[Domain]
,userprofile.[NetworkID]
,userprofile.[EmailAddress]
,userprofile.[CreatedDate]
,userprofile.[CreatedBy]
,userprofile.[ModifiedDate]
,userprofile.[ModifiedBy]
from TimeZone tz inner join
(
select
up.[UserProfileID]
,up.[EmployeeID]
,up.[Forename]
,up.[Surname]
,up.[PreferredName]
,up.[DefaultCountryCode]
,up.[DefaultLanguageCode]
,up.[TimeZoneID]
,te.TeamID
,te.TeamName
,up.[Domain]
,up.[NetworkID]
,up.[EmailAddress]
,up.[CreatedDate]
,up.[CreatedBy]
,up.[ModifiedDate]
,up.[ModifiedBy]
from [dbo].[UserProfileTeamLink] upt
inner join UserProfile up on up.UserProfileID = upt.UserProfileID
inner join Team te on te.TeamID = upt.TeamID ) userprofile on tz.TimeZoneID = userprofile.TimeZoneID
It is hard to say without knowing what the data looks like or what the desired output looks like. You could join all of the tables without using sub queries if you are expecting multiple rows per user because of those many to many relationships.
select
up.[UserProfileID]
,up.[EmployeeID]
,up.[Forename]
,up.[Surname]
,up.[PreferredName]
,up.[DefaultCountryCode]
,up.[DefaultLanguageCode]
,up.[TimeZoneID]
,tz.TimeZone
,te.TeamID
,te.TeamName
,up.[Domain]
,up.[NetworkID]
,up.[EmailAddress]
,up.[CreatedDate]
,up.[CreatedBy]
,up.[ModifiedDate]
,up.[ModifiedBy]
,ur.RoleDescription
from UserProfile up
inner join TimeZone tz
on tz.TimeZoneID = up.TimeZoneID
inner join UserProfileTeamLink upt
on upt.UserProfileID = upt.UserProfileID
--and upt.isDefault = 1 /* default team only? */
--and upt.isActive = 1 /* active team only? */
inner join Team te
on te.TeamID = upt.TeamID
inner join UserProfileRoleLink upr /* left join if users might not have a role*/
on up.UserProfileID = upr.UserProfileId
--and upr.isActive = 1 /* active role only? */
inner join UserRole ur /* left join if users might not have a role*/
on upr.RoleId = ur.RoleId

I want to select from two tables (a,b) which are related to each other through third table(c), but table a has a composite primary key

I want to select from two tables (customers,machins) which are related to each other through third table(orders), but table a has a composite primary key
Table customers has primary key as
id
Table machins has a composite primary key with these two columns:
machinId
machineModel
And these two are related to table orders
Id(fk)
machine(fk)
machintype
I want to select from customers and machins all machines that a person has bought (orders)
My select command is
Select c.name, c.land, m.namemachin
from orders o
inner join customers c on c.id = o.id
inner join machins m on o.machine = m.Id
where c.name = 'karl' and m.machine = o.machintype
But it doesn't work
Can you please help me?
If you have a composite primary key in table machins then both of that column should be available in table orders for a proper relation. Then only you can do a proper join this tables for a select query.
As per the discussion m.machineModel = o.machintype
So please try this query
Select c.name, c.land, m.namemachin
from orders o
inner join customers c on c.id = o.id
inner join machins m on m.machinId = o.machine
and m.machineModel = o.machintype
where c.name = 'karl'
If your fetching is something related to string concatenation i.e to obtain all machines as string. I think you can use STUFF and FOR XML PATH.
Or else go through th below link it might help
http://www.w3resource.com/sql/joins/using-a-where-cluase-to-join-two-tables-related-by-a-composite-primary-key-or-foriegn-key-pair.php

how to know if a row has a foreign key on other table

hi guys i've been searching and trying with no luck for a solution regarding my two tables in an ms sql 2008 r2 my tables are below:
table 1
pk personid varchar - i manually insert here from GUID
fname varchar
mname varchar
lname varchar
qualifier varchar
table 2
pk id - increment by 1
fk personid varchar
salary int
deductions int
salary_month int
salary_year int
now my aim here is to know which entries have a foreign key on the other table if not i want to delete it
i really need some help i have been trying it for a couple of weeks
Maybe, you want this?
SELECT *
FROM table1 t1
WHERE NOT EXISTS (SELECT * FROM table2 t2 WHERE t2.personid=t1.personid)
Here is a query that will give you a list of all foreign keys that exist in your database.
select FK.name as [Foreign_Key_Name], T.name as [Referenced_Table], T2.name as [Parent_Table]
from sys.foreign_key_columns FKC
inner join sys.tables T on FKC.referenced_object_id = T.object_id
inner join sys.tables T2 on FKC.parent_object_id = T2.object_id
inner join sys.foreign_keys FK on FKC.constraint_object_id = FK.object_id
If you have some columns that are used like foreign keys but there is no actual FK object inside your database then you can try something like this
select *
from table1 T1
inner join table2 T2 on T1.ColumnX = T2.ColumnY
If query returns a lot of rows than those two columns are probably in a FK relationship.

Find all foreign key of a table that prevent insert into it in SQL Server

I have a database with about 200 tables with many foreign keys constraints. There is no data in the database and I need to insert rows into a specified table X.
Because of the many foreign keys I don't know the order of how to insert in other tables so that I can insert into table X. Some of foreign key constraint are hierarchical.
How can I find out the order of inserting so that I can successfully insert data into table X? Is there any SQL query that help me?
Edited
I want result in a table with column "TableName" ,"ParentTableDependece" that show tree view and can get select from it
Using this snippet, you can find all other tables and the foreign keys involved that reference your own table X:
;WITH ReferencingFK AS
(
SELECT
fk.Name AS 'FKName',
OBJECT_NAME(fk.parent_object_id) 'ParentTable',
cpa.name 'ParentColumnName',
OBJECT_NAME(fk.referenced_object_id) 'ReferencedTable',
cref.name 'ReferencedColumnName'
FROM
sys.foreign_keys fk
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns cpa ON fkc.parent_object_id = cpa.object_id AND fkc.parent_column_id = cpa.column_id
INNER JOIN
sys.columns cref ON fkc.referenced_object_id = cref.object_id AND fkc.referenced_column_id = cref.column_id
)
SELECT
FKName,
ParentTable,
ParentColumnName,
ReferencedTable,
ReferencedColumnName
FROM
ReferencingFK
WHERE
ReferencedTable = 'X' -- <=== put your table name here!
ORDER BY
ParentTable, ReferencedTable, FKName
Once you have all the tables that reference X, you might also need to repeat this for other tables (if they in turn depend on foreign key references)
Why not this?
EXEC sp_msdependencies #objname = 'X'
Raj
You can try:
EXEC sp_help 'TableName'
This will give you the whole details of the table i.e you can get the relations, indexes and other information related with the object you pass with it.

Resources