Find dependencies between tables in sql database - sql-server

I have a Sql database with data. I have been asked to populate a fresh identical database with all the required master data so that the application is able to up and run for a new customer.
First approach
Delete all the data from database, run the application, sure i won't be even able to login. Observe errors, identify tables which need master data(sure User table at least), insert data. Then assume i am going to access a module. But without some master data it'll give me errors. Observe errors, identify tables which need master data, insert data.
But this seems not practical.
Second approach
While keeping the data in database, take one table at a time, using queries or sql server management studio tools, find all dependent tables. Keep the parent table data and delete child table data. Do this for all tables. In second round consider the remaining parent tables. Some table's data are inserted from application. Identify those and delete them. This way i can have relevant master data at the end. But i don't know how to approach this.
All these are my thoughts. Sure there might be many more approaches which are more precise and easier than these.I am confused with what to do. Please guide me. Thanks!

Here's a few queries you could use to figure out which table and column is referencing which table and column...
select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
select * from INFORMATION_SCHEMA.columns
select * from INFORMATION_SCHEMA.tables
select * from sys.foreign_keys
select * from sys.foreign_key_columns
select * from [sys].[objects] where [name] = 'your_tablename'
For more, open Object Explorer (View Menu) and expand:
Databases/System Databases/Master/Views/System Views.
Also, check out any database diagrams there might be in Object Explorer:
Databases/Your_db_name/Database Diagrams.

How big is the database ?
No matter what you have to make proper documentation ?So better start with documentation.
You have to list all table one by one and identity if it is master table.
Remember the diff. between Delete or Truncate.
While doucmenting above query will come in handy.
Save the query and document for future need.
Most importantly,there should not be any error,even if any of the table is empty.

To find foreign key dependecies between tables you can use
SELECT FKT.name 'Parent table', CHT.name 'Child table' FROM sys.foreign_keys FK
JOIN sys.tables CHT ON FK.parent_object_id = CHT.object_id
JOIN sys.tables FKT ON FK.referenced_object_id = FKT.object_id
There is also ways to find dependencies in database views using system views.

Related

How is table populated in SQL Server

My company has a table in a db, which is populated with some store numbers. It's updated daily with data for the past 30 days (running window). The table was set up by someone who's no longer at the company.
My question is, how to find out where the data comes from? I.e. what populates the table and how?
I've tried right-clicking on the table and clicking "View Dependencies" in SSMS, but it doesn't list anything.
I need to find out where the data comes from, since the table has started to show considerably fewer observations than before.
The server is running SQL Server version 13 and I'm using SSMS 18.
Run the query below, it will tell you if your table is used in any function, procedure, trigger or view on the database.
Then you can run the same query again on the found objects off course.
SELECT DISTINCT
o.name AS Object_Name,
o.type_desc,
m.*
FROM sys.sql_modules m
INNER JOIN sys.objects o ON m.object_id = o.object_id
WHERE m.definition Like '%YOUR_TABLE_NAME%'
This will only tell you if this table name is used in any object on your database, not if its used from any application.
But at least it will tell you any function/procedure names that you need to look for in your applications

how to select values from two tables

I have two tables arts and artsdetails.. artsId is the primary key in arts table foreign key in artdetails table. I am selecting values from both table but my query is giving error as
"Invalid object name 'artdetails'"
My query is:
SELECT arts.artsId, artdetails.mainImage
FROM artdetails
INNER JOIN arts ON artdetails.artsId = arts.artsId;
Please help.
You're probably not running the query in the database where these tables live.
If you're using SQL Server Management studio, look in the top left for a drop down containing the database names. It probably says 'master' (as that's the default). Select the one containing the tables you're using and re-run your query.
Failing that, check they're both running in the same schema as Tom suggests.
You can fully quality table names in your query like this:
SELECT a.artsId, ads.mainImage
FROM [DBNAME].[SCHEMA].artdetails ad
INNER JOIN [DBNAME].[SCHEMA].arts a ON ad.artsId = a.artsId;
Also using table abbreviations tidies things up a bit.

How to find out what table's primary keys are using a select query

Is it possible to run SELECT PIRMARY_KEY FROM SomeTable, where PRIMARY_KEY is a keyword that will automatically translate to SomeTable's primary key columns
I am using Oracle database
Try this:
select cc.column_name
from user_cons_columns cc
join user_constraints c on c.constraint_name = cc.constraint_name
where c.table_name = 'MYTABLE'
and c.constraint_type = 'P'
order by cc.position
You can read more about these and other useful data dictionary views in the Oracle Database Reference.
If you are asking "how do I figure out what the primary key is for any given table", then 'desc table_name' will show you all the details you need to know.
This is database specific. The information usually resides in a proprietary system table.
Most of the time, however, the database implementation is nice enough to provide you with a stored procedure to fetch this information. There are API's around that will provide you with database agnostic ways to get this information, but I suspect you are after something accessible directly from SQL. Post your particular database type and I'm sure someone will know.

sql server: looking for table usage through out database

How would I figure out what type of sql code such as procs, functions, views etc. are interacting with my table called TABLE1 through out a given database. Sample code would be very helpful for me.
thanks
select so.name, so.xtype
from sysobjects so (nolock)
inner join syscomments sc (nolock) on sc.id = so.id
where sc.text like '%tablename%'
This code will search all SQL Server objects for a reference to your table. You have to run this query for each database.
If a stored procedure uses your table it will appear in this query. The same is true of functions, views, and triggers.
xtype tells you the type of object.
Here are the possible xtype values:
D = Field names
F = Foreign Key
FN = Function
P = Stored Procedures
PK = Primary Key
S = System Tables
U = User tables
V = Hidden tables
Not enough info in your question, but one thing you can do is use SQL Profiler to profile where INSERTs, UPDATEs, and DELETEs are coming from.
I assume you are talking about how an app is interacting with data and what name (of say a sproc) is doing the insert / update / delete.
Look at SQL Profiler, it comes with your client tools install. Filter it to only show connections to your database (either db name or ID).
If you've been good and created your SPs/views/functions after your table was created, sp_depends will tell you evertyhing referencing the table. Exept for dynamic sql that is.

TSQL: Create a view that accesses multiple databases

I have a special case,
for example in table ta in database A, it stores all the products I buy
table ta(
id,
name,
price
)
in table tb in database B, it contain all the product that people can buy
table tb(
id,
name,
price
....
)
Can I create a view in database A to list all the products that I haven`t bought?
Yes you can - the t-sql syntax is the same as within any other cross database call (within a stored procedure for example).
To reference your tables in the second database you simply need:
[DatabaseName].[Schema].[TableName]
So you would end up with something like
CREATE VIEW [dbo].[YourView]
as
select
a.ID,
a.SomeInfo,
b.SomeOtherInfo
from TableInA a
join DatabaseB.dbo.TableInB b
on -- your join logic goes here
Note that this will only work on the same server - if your databases are on different servers them you will need to create a linked server.
As the other answers indicate, you can use the {LINKED_SERVER.}DATABASE.SCHEMA.OBJECT notation.
You should also be aware that cross-database ownership chaining is disabled by default.
So within a database, granting SELECT on a view allows a user who may not have SELECT on the underlying tables to still SELECT from the view. This may not work across to another database where the user does not have permissions on the underlying table.
Yes, views can reference three part named objects:
create view A.dbo.viewname as
select ... from A.dbo.ta as ta
join B.dbo.tb as tb on ta.id = tb.id
where ...
There will be problems down the road with cross db queries because of backup/restore consistency, referential integrity problems and possibly mirorring failover, but those problems are inherent in having the data split across dbs.

Resources