Get info (especial pk) of all column in a table - sql-server

I try to get info of all column in a table
Example info about type, name column, especially info about primary key but it missing
I use
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='tablename'
It's not contain info about primary key. How to get that thanks

How about something like
SELECT *
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = 'TableName'
Also maybe try
SELECT i.name AS IndexName,
OBJECT_NAME(ic.OBJECT_ID) AS TableName,
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName,
c.*
FROM sys.indexes AS i INNER JOIN
sys.index_columns AS ic ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id INNER JOIN
sys.columns c ON ic.object_id = c.object_id
AND ic.column_id = c.column_id
WHERE i.is_primary_key = 1

try with sp_help [tablename] it will give you primary key details
sp_help [tablename]
sp_help
Or if you need only details about primary key column try with Mr.Astander answer
SELECT *
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = 'TableName'

You could retrieve primary key information and join it to INFORMATION_SCHEMA.COLUMNS and get primary key information with other columns. Please see the below query.
SELECT c.*,
CASE WHEN keys.COLUMN_NAME IS NULL
THEN 0
ELSE 1
END AS is_primary
FROM
INFORMATION_SCHEMA.COLUMNS c
LEFT OUTER JOIN (
SELECT col.COLUMN_NAME,col.TABLE_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tab
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
ON Col.Constraint_Name = tab.Constraint_Name
AND Col.Table_Name = tab.Table_Name
WHERE Constraint_Type = 'PRIMARY KEY') keys
ON c.COLUMN_NAME=keys.COLUMN_NAME AND c.TABLE_NAME=keys.TABLE_NAME
ORDER BY c.TABLE_NAME

Try:
SELECT TC.TABLE_NAME, CU.CONSTRAINT_NAME, C.DATA_TYPE
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CU
ON TC.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.COLUMNS C
ON CU.TABLE_NAME = C.TABLE_NAME AND CU.TABLE_SCHEMA = C.TABLE_SCHEMA AND C.COLUMN_NAME = CU.COLUMN_NAME
WHERE TC.TABLE_NAME = 'tablename' AND CONSTRAINT_TYPE = 'PRIMARY KEY'

Related

Get all tables which has primary key with data type uniqueidentifier in SQL Server

I need to write a query that will return all tables name which has Primary key column with data type uniqueidentifier.
Can anyone please help me.
Using sql server object catalog views:
select
IndexName = i.name
, SchemaName = schema_Name(t.schema_id)
, TableName = t.Name
, ColumnName = c.Name
, TypeName = type_name(c.user_type_id)
from sys.tables t
inner join sys.indexes as i on
t.object_id = i.object_id
and i.is_primary_key = 1
inner join sys.index_columns as ic on
i.object_id = ic.object_id
and i.index_id = ic.index_id
inner join sys.columns as c on
c.column_id = ic.column_id
and c.object_id = ic.object_id
and type_name(c.user_type_id) = 'uniqueidentifier'
rextester link: http://rextester.com/SAL18997
SELECT Col.Column_Name , tab.TABLE_NAME ,DATA_TYPE
from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab join
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col on col.CONSTRAINT_NAME = Tab.CONSTRAINT_NAME
join INFORMATION_SCHEMA.COLUMNS columns on columns.COLUMN_NAME = Col.COLUMN_NAME and col.TABLE_NAME =columns.TABLE_NAME
WHERE
Col.Constraint_Name = Tab.Constraint_Name
AND Col.Table_Name = Tab.Table_Name
AND Constraint_Type = 'PRIMARY KEY'
AND columns.DATA_TYPE = 'uniqueidentifier'

Information schema and Primary Keys

How do I just print out a 'primary key' for the column with the primary key?
I get 'primary key' for all the columns if the table has a primary key, instead of the one column with the primary key and the other columns as blank in keyType.
SELECT c.TABLE_NAME,
c.COLUMN_NAME,
c.DATA_TYPE,
c.Column_default,
c.character_maximum_length,
c.numeric_precision,
c.is_nullable,
CASE
WHEN u.CONSTRAINT_TYPE = 'PRIMARY KEY' THEN 'primary key'
ELSE ''
END AS KeyType
FROM INFORMATION_SCHEMA.COLUMNS as c
LEFT JOIN information_schema.table_constraints as u ON c.table_name = u.table_name
ORDER BY table_name
SELECT c.TABLE_NAME, c.COLUMN_NAME,c.DATA_TYPE, c.Column_default, c.character_maximum_length, c.numeric_precision, c.is_nullable
,CASE WHEN pk.COLUMN_NAME IS NOT NULL THEN 'PRIMARY KEY' ELSE '' END AS KeyType
FROM INFORMATION_SCHEMA.COLUMNS c
LEFT JOIN (
SELECT ku.TABLE_CATALOG,ku.TABLE_SCHEMA,ku.TABLE_NAME,ku.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS ku
ON tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND tc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME
) pk
ON c.TABLE_CATALOG = pk.TABLE_CATALOG
AND c.TABLE_SCHEMA = pk.TABLE_SCHEMA
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.COLUMN_NAME = pk.COLUMN_NAME
ORDER BY c.TABLE_SCHEMA,c.TABLE_NAME, c.ORDINAL_POSITION
As an addition, consider looking at:
sp_helptext N'sp_help'
Sometimes learning from the MS team is a great thing. :-)
a very small add to the first answer. It's possible to view in same time the MS_Description (or other extend properties)
SELECT c.TABLE_NAME, c.COLUMN_NAME,c.DATA_TYPE, c.Column_default, c.character_maximum_length, c.numeric_precision, c.is_nullable
,CASE WHEN pk.COLUMN_NAME IS NOT NULL THEN 'PRIMARY KEY' ELSE '' END AS KeyType, c.ORDINAL_POSITION
,convert(varchar(8000), ex.value) as coln
FROM INFORMATION_SCHEMA.COLUMNS c
LEFT JOIN (
SELECT ku.TABLE_CATALOG,ku.TABLE_SCHEMA,ku.TABLE_NAME,ku.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS ku
ON tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND tc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME
) pk
ON c.TABLE_CATALOG = pk.TABLE_CATALOG
AND c.TABLE_SCHEMA = pk.TABLE_SCHEMA
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.COLUMN_NAME = pk.COLUMN_NAME
outer apply ::fn_listextendedproperty('MS_Description', 'schema', 'dbo', 'table', c.TABLE_NAME, 'column', c.COLUMN_NAME) ex
ORDER BY c.TABLE_SCHEMA,c.TABLE_NAME, c.ORDINAL_POSITION
I've found this code below to be the simplest method to find the primary key for a table. It only requires a left outer join between the information_schema.columns table and the information_schema.key_column_usage table.
Select
col.column_name,
col.data_type,
col.ordinal_position,
col.is_nullable,
case when ky.COLUMN_NAME is null then 0 else 1 end as primary_key_flag
from <your-catalog>.Information_Schema.columns col
left outer join <your-catalog>.INFORMATION_SCHEMA.KEY_COLUMN_USAGE ky
on ky.COLUMN_NAME = col.COLUMN_NAME and ky.TABLE_NAME = col.TABLE_NAME
and ky.TABLE_CATALOG = col.TABLE_CATALOG and ky.table_name = col.table_name
where
col.TABLE_NAME = '<your-table-name>'
and col.table_catalog = '<your-catalog>';
Note: This code was built using SQL Server 2017 Express (14.0.1000) and after I created the primary key, I was able to see those values in the KEY_COLUMN_USAGE table. I also saw a record in the CONSTRAINT_TABLE_USAGE which identified the constraint_name, but I didn't find that to be a requirement in order to get the join into which revealed the primary key.
Final note: I'm just getting back into SQL server on a personal project after nearly a decade away from the DB (using MySQL), and so I'm nowhere near an expert on the subject.

Get a List of all Primary Keys in a Database

Is this the best way to - Get a List of all Primary Keys in a Database - or is there something better?
SELECT
KCU.TABLE_NAME AS Table_Name,
KCU.CONSTRAINT_NAME AS Constraint_Name,
KCU.COLUMN_NAME AS COLUMN_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
ON KCU.CONSTRAINT_SCHEMA = TC.CONSTRAINT_SCHEMA
AND KCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
AND KCU.TABLE_SCHEMA = TC.TABLE_SCHEMA
AND KCU.TABLE_NAME = TC.TABLE_NAME
WHERE
TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY
KCU.TABLE_SCHEMA, KCU.TABLE_NAME, KCU.CONSTRAINT_NAME
USE databasename;
GO
SELECT i.name AS IndexName, OBJECT_NAME(ic.OBJECT_ID) AS TableName,
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
This query will extract the all primary key constraints from the database...
u just need to execute this query and type the database name in first line
The following syntax give you all constraints in database in use.
select * from sys.key_constraints;
If you want the data type information as well:
SELECT
so.name 'Table Name',
c.name 'Column Name',
t.Name 'Data type',
c.max_length 'Max Length',
c.precision ,
c.scale ,
c.is_nullable,
ISNULL(i.is_primary_key, 0) 'Primary Key'
FROM
sys.columns c
INNER JOIN
sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN
sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN
sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
INNER JOIN
sysobjects so ON c.object_id = so.id
WHERE
i.is_primary_key = 1 and
so.xtype = 'U'
Order By 'Table Name', 'Column Name'
look on link
EXEC sp_pkeys '<tablename>'
EXEC sp_helpconstraint '<tablename>'
sp_pkeys will return a row for each
column that participates in the
primary key for . The
columns you are likely most interested
in are COLUMN_NAME and PK_NAME.
sp_helpconstraint will list all
constraints for , including
foreign keys that reference the table.
In the first recordset, there will
only be a column called Object Name
(kind of useless, since that's what
you passed in). In the second
resultset, there will be the following
columns: constraint_type,
constraint_name, and constraint_keys.
If you are doing this from java you can also use the getPrimaryKeys method in the databasemetadata object. Perhaps other languages have similar ways to do it.

Get the unique constraint columns list (in TSQL)?

I can get a list of unique constraints fairly easily with the following query:
select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='UNIQUE'
But how do I get a list of the columns that each unique constraint applies to?
Ed is correct, the columns are exposed on the constraint column usage view, here is the SQL for it.
select TC.Constraint_Name, CC.Column_Name from information_schema.table_constraints TC
inner join information_schema.constraint_column_usage CC on TC.Constraint_Name = CC.Constraint_Name
where TC.constraint_type = 'Unique'
order by TC.Constraint_Name
See INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
SELECT *
FROM sys.indexes i
JOIN sys.index_columns ic
ON i.index_id = ic.index_id
AND i.object_id = ic.object_id
WHERE i.is_unique_constraint = 1;
Necromancing.
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE is incredibly slow.
Use sys.indexes, join the table, schema, object, and as an added bonus, you get not only unique constraints, but also unique indices, including filter.
-- CREATE TABLE dbo.T_User( USR_ID int NOT NULL, USR_User nvarchar(256) NULL, USR_Status int NOT NULL );
-- ALTER TABLE dbo.T_User ADD CONSTRAINT UC_T_User_USR_User UNIQUE(USR_User)
-- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo.T_User') AND name = N'IX_T_User_USR_User')
-- CREATE UNIQUE INDEX IX_T_User_USR_User ON dbo.T_User(USR_User)
-- WHERE (USR_User IS NOT NULL AND USR_Status=(1))
SELECT
sch.name
,st.name
,i.name
,i.has_filter
,i.filter_definition
,i.is_unique
,i.is_primary_key
,i.is_unique_constraint
,CASE WHEN i.is_unique_constraint = 1
THEN N'ALTER TABLE ' + QUOTENAME(sch.name) + N'.' + QUOTENAME(st.name) + N' DROP CONSTRAINT ' + QUOTENAME(i.name) + N'; '
ELSE N'DROP INDEX ' + QUOTENAME(i.name) + N' ON ' + QUOTENAME(sch.name) + '.' + QUOTENAME(st.name) + '; '
END AS sql
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.index_id = ic.index_id
AND i.object_id = ic.object_id
INNER JOIN sys.tables AS st
ON st.object_id = i.object_id
INNER JOIN sys.objects AS syso
ON syso.object_id = st.object_id
AND syso.is_ms_shipped = 0
INNER JOIN sys.schemas AS sch
ON sch.schema_id = st.schema_id
WHERE (1=1)
AND NOT EXISTS
(
SELECT *
FROM sys.extended_properties AS xp
WHERE xp.minor_id = 0
AND xp.major_id = st.object_id
AND xp.name = 'microsoft_database_tools_support'
)
-- AND sch.name = 'dbo'
-- AND st.name = 'T_Benutzer'
AND
(
i.is_unique_constraint = 1
OR
(i.is_unique = 1 AND i.is_primary_key = 0)
)
;
Just for reference of mySQL users,
Same thing can be achieved with below queries:
To find any unique constraint on a table
select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='UNIQUE' and table_name='db_my_table'
To find unique column list with all column
select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_NAME='cons_name' and TABLE_NAME='db_my_table'
to find unique column list with required view
select CONSTRAINT_NAME,COLUMN_NAME,TABLE_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_NAME='cons_name' and TABLE_NAME='db_my_table'
Here is a better solution, which lists the constraint columns in a proper sort order, with added ASC/DESC flag. It also allows filtering by catalog, schema or table name.
SELECT sh.name AS schema_name,
i.name AS constraint_name,
t.name AS table_name,
c.name AS column_name,
ic.key_ordinal AS column_position,
ic.is_descending_key AS is_desc
FROM sys.indexes i
INNER JOIN sys.index_columns ic
ON i.index_id = ic.index_id AND i.object_id = ic.object_id
INNER JOIN sys.tables AS t
ON t.object_id = i.object_id
INNER JOIN sys.columns c
ON t.object_id = c.object_id AND ic.column_id = c.column_id
INNER JOIN sys.objects AS syso
ON syso.object_id = t.object_id AND syso.is_ms_shipped = 0
INNER JOIN sys.schemas AS sh
ON sh.schema_id = t.schema_id
INNER JOIN information_schema.schemata sch
ON sch.schema_name = sh.name
WHERE i.is_unique_constraint = 1
-- AND sch.catalog_name = 'EmployeesQX'
-- AND sh.name = 'dbo'
ORDER BY sh.name, i.name, ic.key_ordinal;

How do I determine if a column is in the primary key of its table? (SQL Server)

I am currently using...
select Table_Name, Column_name, data_type, is_Nullable
from information_Schema.Columns
...to determine information about columns in a given database for the purposes of generating a DataAccess Layer.
From where can I retrieve information about if these columns are participants in the primary key of their table?
Here is one way (replace 'keycol' with the column name you are searching
for):
SELECT K.TABLE_NAME ,
K.COLUMN_NAME ,
K.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME
AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND K.COLUMN_NAME = 'keycol';
Similarly, the following will give you information about all the tables and their keys, instead of information about specific columns. This way, you make sure you have all the columns of interest and know what they participate in. In order to see all keys (primary, foreign, unique), comment the WHERE clause.
SELECT K.TABLE_NAME, C.CONSTRAINT_TYPE, K.COLUMN_NAME, K.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K
ON C.TABLE_NAME = K.TABLE_NAME
AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY K.TABLE_NAME, C.CONSTRAINT_TYPE, K.CONSTRAINT_NAME
For your need, full outer join with INFORMATION_SCHEMA.COLUMNS and INFORMATION_SCHEMA.KEY_COLUMN_USAGE. At the select statement, add CONSTRAINT_NAME column from INFORMATION_SCHEMA.KEY_COLUMN_USAGE that will give you null or keyname.
select C.Table_Name, C.Column_name, data_type, is_Nullable, U.CONSTRAINT_NAME
from information_Schema.Columns C FULL OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U ON C.COLUMN_NAME = U.COLUMN_NAME
WHERE C.TABLE_NAME=#TABLENAME
this query return column with is primary key.
SELECT col.COLUMN_NAME ,
col.DATA_TYPE ,
col.CHARACTER_MAXIMUM_LENGTH ln ,
CAST(ISNULL(j.is_primary, 0) AS BIT) is_primary
FROM INFORMATION_SCHEMA.COLUMNS col
LEFT JOIN ( SELECT K.TABLE_NAME ,
K.COLUMN_NAME ,
CASE WHEN K.CONSTRAINT_NAME IS NULL THEN 0
WHEN K.CONSTRAINT_NAME IS NOT NULL THEN 1
END is_primary
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME
AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND C.TABLE_NAME = 'tablename'
) j ON col.COLUMN_NAME = j.COLUMN_NAME
WHERE col.TABLE_NAME = 'tablename'

Resources