SQL Script To Generate a Database Dictionary **With Linked Fields** - sql

I would like to generate a Data Dictionary for a SQL Server 2008 database that has one row for each field, and the following columns:
table_name
field_name
data_type
link_table (for when the field in question is a foreign key)
link_field (for when the field in question is a foreign key)
I can get the first 3 columns with something like the SQL script below...but I don't know how to get the last two columns of foreign key information. INFORMATION_SCHEMA.TABLE_CONSTRAINTS gets close, but doesn't have the data I'm looking for. Can someone help with this point?
SELECT TABLE_NAME,COLUMN_NAME,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
Secondarily if anyone has any suggestions on additional fields which would be helpful please post.

The following query will duplicate a column if it is involved in more than one relationship.
Select C.TABLE_SCHEMA, C.TABLE_NAME, C.COLUMN_NAME, C.DATA_TYPE
, PKCol.TABLE_SCHEMA, PKCol.TABLE_NAME, PKCol.COLUMN_NAME
From INFORMATION_SCHEMA.COLUMNS As C
Left Join (INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE As FKCol
Join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS As FK
On FK.CONSTRAINT_NAME = FKCol.CONSTRAINT_NAME
Join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE As PKCol
On PKCol.CONSTRAINT_NAME = FK.UNIQUE_CONSTRAINT_NAME)
On FKCol.TABLE_SCHEMA = C.TABLE_SCHEMA
And FKCol.TABLE_NAME = C.TABLE_NAME
ANd FKCol.COLUMN_NAME = C.COLUMN_NAME

Related

Write sql server query to see how many tables are linked a table

Provided there are tables Application, Person, Status, etc...
Status and Person have a link to Application.
Is there a simple sql query that may be written that will give a list of all the tables linked to the Application table (in contrast of using the database diagram).
Application expected results:
Status
Person
Please advise on a feasible solution (if any).
Using SP_depends. There are other ways as well like DMV's.
sp_depends 'TableName'
Assuming you're using MSSQL Server then you can run
EXEC sp_fkeys 'YourTableName'
Otherwise you can use
SELECT *
FROM information_schema.referential_constraints
WHERE table_name = <tablename>
to establish the foreign key relationships
Another way to check each table name that references to other tables would be this:
SELECT DISTINCT OBJECT_NAME(f.parent_object_id) AS TableName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN sys.objects AS o
ON o.OBJECT_ID = fc.referenced_object_id
You can, of course, add more conditions to check for a single table, for example:
WHERE OBJECT_NAME(f.referenced_object_id) = 'Application'
This should give you a result like:
TableName ReferenceTableName
---------- ------------------
Status Application
Person Application

Display ALL the columns from table that doesn`t contain the Primary Keys

I`ve got this query to do.
Display ALL the columns from table named 'somehow' that are not primary keys.
This is how I am trying to obtain the column headers that differ from the Primary Key ID Column :
SELECT cols.column_name
FROM information_schema.table_constraints t
JOIN information_schema.key_column_usage k
USING(constraint_name,table_schema,table_name)
WHERE t.constraint_type <> 'PRIMARY KEY'
AND t.table_schema='mydb'
AND t.table_name='somehow'
Something is not right since I get an SQL Error. What am I doing wrong?
Update :
SELECT k.column_name
FROM information_schema.table_constraints t
JOIN information_schema.key_column_usage k
USING(constraint_name,table_schema,table_name)
WHERE t.constraint_type <> 'PRIMARY'
AND t.table_schema='mydb'
AND t.table_name='somehow'
This shows exactly what I don`t want to get as a result (The Primary Key ) I need everything else to be shown :(
All table columns can be found in MySQL's system table columns. Its column_key field contains 'PRI' in case a column is part of the primary key. Hence:
select column_name
from information_schema.columns
where table_schema = 'mydb'
and table_name = 'somehow'
and column_key <> 'PRI';

How to trace the foreign keys?

I have 3 different sql environments which are similar but not same. I have a column "CLMID" used in different tables. Most of them are linked with the foreign key mapping. But some tables are corrupted so do not have the foreign key mapping done right. I now need to update a data into this column in all tables. So I need a query which will find for me the list of tables that are having proper mapping, so that if I update the parent they update the child by them self. I also need to find the constraint the other way where, only if I update the child I can update the parent table.
Please note that I need to get this list without doing any update or insert operations as Its a critical database. Please help me with the query. Thank you.
Every SQL product has some way to query the database for schema data, including keys. Learning to use the Information_Schema is best IMHO because it is a standard across most platforms (as I recall Oracle does not implement it).
SQL Server probably has some easier queries with its own catalogs, but the following somewhat hairy query gives you exactly what you want and is the most cross-platform you can get.
SELECT
FK.TABLE_NAME as child_table,
CU.COLUMN_NAME as child_column,
PK.TABLE_NAME as parent_table,
PT.COLUMN_NAME as parent_column,
C.CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN
(
SELECT
i1.TABLE_NAME, i2.COLUMN_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT
ON PT.TABLE_NAME = PK.TABLE_NAME
ORDER BY
1,2,3,4
try this
show create table table-name
Upon seeing this, you can see the foreign keys the columns have. This doesnt change any of the table data
Check out sys.foreign_keys for some SQL Server-specific action. Specifically, it seems that you're interested in the delete_referential_action_desc and update_referential_action_desc columns. As far as I know, there's no way to update a child table and have the update automatically propagate to the parent. I'm willing to be corrected, though.

Dynamically determining table name given field name in SQL server

Strange situation: I am trying to remove some hard coding from my code. There is a situation where I have a field, lets say "CityID", and using this information, I want to find out which table contains a primary key called CityID.
Logically, you'd say that it's probably a table called "City" but it's not... that table is called "Cities". There are some other inconsistencies in database naming hence I can never be sure if removing the string "ID" and finding out the plural will be sufficient.
Note: Once I figure out that CityID refers to a table called Cities, I will perform a join to replace CityID with city name on the fly. I will appreciate if someonw can also tell me how to find out the first varchar field in a table given its name.
SELECT name FROM sysobjects
WHERE id IN ( SELECT id FROM syscolumns WHERE name = 'THE_COLUMN_NAME' )
To get column information from the specified table:
SELECT column_name, data_type, character_maximum_length
FROM information_schema.columns
WHERE table_name = 'myTable'
select table_name from information_schema.columns where column_name='CityID'
You can use the INFORMATION_SCHEMA tables to read metadata about the database.
SELECT
TABLE_NAME
FROM
[db].[INFORMATION_SCHEMA].[COLUMNS]
WHERE
COLUMN_NAME='CityID';
For a primer in what's in the INFORMAITON_SCHEMA, see INFORMATION_SCHEMA, a map to your database
The information you seek is all available in the information schema views. Note that you will find many sources telling you how to directly query the underlying system tables that these are views onto - and I must admit that I do the same when it's just to find something out quickly - but the recommended way for applications is to go through these views.
For example, to find your CityID column:
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'CityID'
To find the first varchar field in a table:
SELECT TOP 1 * FROM INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_NAME = 'TableName'
AND DATA_TYPE = 'varchar' -- This is off the top of my head!
ORDER BY ORDINAL_POSITION
As I understand from your question, you want to find tables which contain CITYID column in primary key
You can use SQL Server system views like sysindexes and sysindexkeys as shown in SQL tutorial to query database table primary keys including composite primary keys which are formed
SELECT
TBL.name as TableName
FROM sysobjects as PK
INNER JOIN sys.objects as TBL
on TBL.object_id = PK.parent_obj
INNER JOIN sysindexes as IND
on IND.name = PK.name AND
IND.id = TBL.object_id
INNER JOIN SysIndexKeys as KEYS
on KEYS.id = IND.id AND
KEYS.indid = IND.indid
INNER JOIN syscolumns as COL
on COL.id = KEYS.id AND
COL.colid = KEYS.colid
WHERE
PK.xtype = 'PK' AND
COL.name = 'CityID'

Finding all Nullable Columns in SQL 2000 Database

How to find out column with NULL values allowed in the insert in whole database ?
I don't have sql at hand, but the query goes something like this
SELECT * FROM information_schema.columns WHERE is_nullable = 'YES'
In general, search for this stardard view, for all the metadata info about your schema and structure of the database; there are many others (information_schema.tables, information_schema.constraints, etc)
Those who only want to see columns from base tables (not views) should join with INFORMATION_SCHEMA.TABLES. I also like to exclude the system table sysdiagrams.
Query
SELECT
c.TABLE_NAME,
COLUMN_NAME,
DATA_TYPE
FROM
INFORMATION_SCHEMA.COLUMNS AS c
JOIN INFORMATION_SCHEMA.TABLES AS t ON t.TABLE_NAME = c.TABLE_NAME
WHERE
is_nullable = 'YES' AND
TABLE_TYPE = 'BASE TABLE' AND
c.TABLE_NAME != 'sysdiagrams'
ORDER BY
c.TABLE_NAME,
COLUMN_NAME
If you have duplicate table names across schemas or table catalogs, you should involve those fields in the join as well, as shown in the answers here:
Differentiating tables and views in INFORMATION_SCHEMA.COLUMNS.