I try to drop a column in SQL but I am getting this error:
The object 'DF__...'is dependent on column ...
I found a lot of solutions that need to drop the Constraint first, so I ran this and worked:
ALTER TABLE [dbo].[Configuration] DROP CONSTRAINT DF__SiteConfi__Na__2DFCAC08;
ALTER TABLE [dbo].[Configuration] DROP COLUMN NaFlag;
But I need this script to run on any server, so I don't want to mention the Constraint name as it may be different on any other servers. What is the best solution?
You can use some dynamic SQL to drop the default. If it's an isolated script to just drop the column, then it's easier, something like:
DECLARE #sqlDF NVARCHAR(MAX);
SELECT #sqlDF = 'ALTER TABLE {$tableName} DROP CONSTRAINT ' + QUOTENAME(OBJECT_NAME([default_object_id])) + ';'
FROM sys.columns
WHERE [object_id] = OBJECT_ID('{$tableName}') AND [name] in ({$columns}) AND [default_object_id] <> 0;
IF #sqlDF IS NOT NULL
EXEC(#sqlDF);
If you are working with a migrations tool, maybe you're gonna have to refactor this, so it doesn't try to redeclare the #sqlDF variable.
Here's a query to get you started:
with q as
(
select schema_name(t.schema_id) schema_name,
t.name table_name,
c.name column_name,
d.name default_name
from sys.tables t
join sys.columns c
on t.object_id = c.object_id
join sys.default_constraints d
on d.parent_object_id = t.object_id
and d.parent_column_id = c.column_id
)
select concat(
'alter table ',
quotename(schema_name),'.',quotename(table_name),
' drop constraint ', quotename(default_name) ) sql
from q
Related
I want to query the name of all columns of a table. I found how to do this in:
Oracle
MySQL
PostgreSQL
But I also need to know: how can this be done in Microsoft SQL Server (2008 in my case)?
You can obtain this information and much, much more by querying the Information Schema views.
This sample query:
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'Customers'
Can be made over all these DB objects:
CHECK_CONSTRAINTS
COLUMN_DOMAIN_USAGE
COLUMN_PRIVILEGES
COLUMNS
CONSTRAINT_COLUMN_USAGE
CONSTRAINT_TABLE_USAGE
DOMAIN_CONSTRAINTS
DOMAINS
KEY_COLUMN_USAGE
PARAMETERS
REFERENTIAL_CONSTRAINTS
ROUTINES
ROUTINE_COLUMNS
SCHEMATA
TABLE_CONSTRAINTS
TABLE_PRIVILEGES
TABLES
VIEW_COLUMN_USAGE
VIEW_TABLE_USAGE
VIEWS
You can use the stored procedure sp_columns which would return information pertaining to all columns for a given table. More info can be found here http://msdn.microsoft.com/en-us/library/ms176077.aspx
You can also do it by a SQL query. Some thing like this should help:
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('dbo.yourTableName')
Or a variation would be:
SELECT o.Name, c.Name
FROM sys.columns c
JOIN sys.objects o ON o.object_id = c.object_id
WHERE o.type = 'U'
ORDER BY o.Name, c.Name
This gets all columns from all tables, ordered by table name and then on column name.
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'
This is better than getting from sys.columns because it shows DATA_TYPE directly.
You can use sp_help in SQL Server 2008.
sp_help <table_name>;
Keyboard shortcut for the above command: select table name (i.e highlight it) and press ALT+F1.
By using this query you get the answer:
select Column_name
from Information_schema.columns
where Table_name like 'table name'
You can write this query to get column name and all details without using
INFORMATION_SCHEMA in MySql :
SHOW COLUMNS FROM database_Name.table_name;
SELECT name
FROM sys.columns
WHERE object_id = OBJECT_ID('TABLE_NAME')
TABLE_NAME is your table
--This is another variation used to document a large database for conversion (Edited to --remove static columns)
SELECT o.Name as Table_Name
, c.Name as Field_Name
, t.Name as Data_Type
, t.length as Length_Size
, t.prec as Precision_
FROM syscolumns c
INNER JOIN sysobjects o ON o.id = c.id
LEFT JOIN systypes t on t.xtype = c.xtype
WHERE o.type = 'U'
ORDER BY o.Name, c.Name
--In the left join, c.type is replaced by c.xtype to get varchar types
You can try this.This gives all the column names with their respective data types.
desc <TABLE NAME> ;
SELECT column_name, data_type, character_maximum_length, table_name,ordinal_position, is_nullable
FROM information_schema.COLUMNS WHERE table_name LIKE 'YOUR_TABLE_NAME'
ORDER BY ordinal_position
Just run this command
EXEC sp_columns 'Your Table Name'
Summarizing the Answers
I can see many different answers and ways to do this but there is the rub in this and that is the objective.
Yes, the objective. If you want to only know the column names you can use
SELECT * FROM my_table WHERE 1=0
or
SELECT TOP 0 * FROM my_table
But if you want to use those columns somewhere or simply say manipulate them then the quick queries above are not going to be of any use. You need to use
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'Customers'
one more way to know some specific columns where we are in need of some similar columns
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME like N'%[ColumnName]%' and TABLE_NAME = N'[TableName]'
This SO question is missing the following approach :
-- List down all columns of table 'Logging'
select * from sys.all_columns where object_id = OBJECT_ID('Logging')
You can try using :-
USE db_name;
DESCRIBE table_name;
it'll give you column names with the type.
It will check whether the given the table is Base Table.
SELECT
T.TABLE_NAME AS 'TABLE NAME',
C.COLUMN_NAME AS 'COLUMN NAME'
FROM INFORMATION_SCHEMA.TABLES T
INNER JOIN INFORMATION_SCHEMA.COLUMNS C ON T.TABLE_NAME=C.TABLE_NAME
WHERE T.TABLE_TYPE='BASE TABLE'
AND T.TABLE_NAME LIKE 'Your Table Name'
In SQL Server, you can select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS.
Here is the code:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='YourTableName'
you can use this query
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME like N'%[ColumnName]%' and TABLE_NAME = N'[TableName]'
SELECT c.Name
FROM sys.columns c
JOIN sys.objects o ON o.object_id = c.object_id
WHERE o.object_id = OBJECT_ID('TABLE_NAME')
ORDER BY c.Name
One other option which is arguably more intuitive is:
SELECT [name]
FROM sys.columns
WHERE object_id = OBJECT_ID('[yourSchemaType].[yourTableName]')
This gives you all your column names in a single column.
If you care about other metadata, you can change edit the SELECT STATEMENT TO SELECT *.
SELECT TOP (0) [toID]
,[sourceID]
,[name]
,[address]
FROM [ReportDatabase].[Ticket].[To]
Simple and doesnt require any sys tables
Simple and doesn't require sys variables:
SHOW COLUMNS FROM suppliers;
Some SQL Generating SQL:
DROP TABLE IF EXISTS test;
CREATE TABLE test (
col001 INTEGER
, col002 INTEGER
, col003 INTEGER
, col004 INTEGER
, col005 INTEGER
, col006 INTEGER
, col007 INTEGER
, col008 INTEGER
, col009 INTEGER
, col010 INTEGER
)
;
INSERT INTO test(col001) VALUES(1);
INSERT INTO test(col002) VALUES(1);
INSERT INTO test(col005) VALUES(1);
INSERT INTO test(col009) VALUES(1);
INSERT INTO test VALUES (NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
SELECT
CASE ROW_NUMBER() OVER(ORDER BY ordinal_position)
WHEN 1 THEN
'SELECT'+CHAR(10)+' *'+CHAR(10)+'FROM test'
+CHAR(10)+'WHERE '
ELSE
' OR '
END
+ column_name +' IS NOT NULL'
+ CASE ROW_NUMBER() OVER(ORDER BY ordinal_position DESC)
WHEN 1 THEN
CHAR(10)+';'
ELSE
''
END
FROM information_schema.columns
WHERE table_schema='dbo'
AND table_name = 'test'
ORDER BY
ordinal_position;
-- the whole scenario. Works for 10 , will work for 100, too:
-- out -----------------------------------------------
-- out SELECT
-- out *
-- out FROM test
-- out WHERE col001 IS NOT NULL
-- out OR col002 IS NOT NULL
-- out OR col003 IS NOT NULL
-- out OR col004 IS NOT NULL
-- out OR col005 IS NOT NULL
-- out OR col006 IS NOT NULL
-- out OR col007 IS NOT NULL
-- out OR col008 IS NOT NULL
-- out OR col009 IS NOT NULL
-- out OR col010 IS NOT NULL
-- out ;
I have a column LastUpdate in all tables of my database and I want to say "on insert of update LastUpdate = getdate()"
I can do this with a trigger but I find it' hard to write hundreds triggers for each table of the database.
- How do I dynamically create a trigger that affect all tables?
- How do I dynamically create triggers for each table ?
It is not possible to have a trigger that fires when any table is updated.
You could generate the SQL Required dynamically, the following:
SELECT N'
CREATE TRIGGER trg_' + t.Name + '_Update ON ' + ObjectName + '
AFTER UPDATE
AS
BEGIN
UPDATE t
SET LastUpdate = GETDATE()
FROM ' + o.ObjectName + ' AS t
INNER JOIN inserted AS i
ON ' +
STUFF((SELECT ' AND t.' + QUOTENAME(c.Name) + ' = i.' + QUOTENAME(c.Name)
FROM sys.index_columns AS ic
INNER JOIN sys.columns AS c
ON c.object_id = ic.object_id
AND c.column_id = ic.column_id
WHERE ic.object_id = t.object_id
AND ic.index_id = ix.index_id
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 4, '') + ';
END;
GO'
FROM sys.tables AS t
INNER JOIN sys.indexes AS ix
ON ix.object_id = t.object_id
AND ix.is_primary_key = 1
CROSS APPLY (SELECT QUOTENAME(OBJECT_SCHEMA_NAME(t.object_id)) + '.' + QUOTENAME(t.name)) o (ObjectName)
WHERE EXISTS
( SELECT 1
FROM sys.columns AS c
WHERE c.Name = 'LastUpdate'
AND c.object_id = t.object_id
);
Generates SQL for each table with a LastUpdate column along the lines of:
CREATE TRIGGER trg_TableName_Update ON [dbo].[TableName]
AFTER UPDATE
AS
BEGIN
UPDATE t
SET LastUpdate = GETDATE()
FROM [dbo].[TableName] AS t
INNER JOIN inserted AS i
ON t.[PrimaryKey] = i.[PrimaryKey];
END;
GO
The relies on each table having a primary key to get the join from the inserted table back to the table being updated.
You can either copy and paste the results and execute them (I would recommend this way so you can at least check the SQL Generated, or build it into a cursor and execute it using sp_executesql. I would recommend the former, i.e. use this to save a bit of time, but still check each trigger before actually creating it.
I personally think last modified columns are a flawed concept, it always feels to me like storing annoyingly little information, if you really care about data changes then track them properly with an audit table (or temporal tables, or using Change Tracking). Firstly, knowing when something was changed, but not what it was changed from, or who changed it is probably more annoying than not knowing at all, secondly it overwrites all previous changes, what makes the latest change more important than all those that have gone before.
I want these 5 columns as output when a stored procedure, in any database on the server, references a column in a specific database (let's say the database is AA).
Column_name Table_Name Schema_Name Procedure_Name Database_Name
Four of the columns are really easy to get - for the current database that you're in:
SELECT
TableName = t.Name,
SchemaName = s.Name,
ColumnName = c.Name,
DatabaseName = DB_NAME()
FROM
sys.tables t
INNER JOIN
sys.schemas s ON [t].[schema_id] = [s].[schema_id]
INNER JOIN
sys.columns c ON [t].[object_id] = [c].[object_id]
What you cannot get easily is all columns across all tables in all databases. Also: determining in which procedure each column is used is also rather tricky (or next to impossible).
From marc_s answer i generate a query which gives comma separated Procedure_Name depended by that table
SELECT
TableName = t.Name,
SchemaName = s.Name,
ColumnName = c.Name,
DatabaseName = DB_NAME(),
STUFF((SELECT ',' + name
FROM sys.procedures
WHERE object_id in (SELECT distinct id from sys.sysdepends
WHERE depid = (SELECT object_id FROM sys.tables
WHERE name=t.Name)
)
FOR XML PATH('')), 1, 0, '') AS sps
FROM
sys.tables t
INNER JOIN
sys.schemas s ON [t].[schema_id] = [s].[schema_id]
INNER JOIN
sys.columns c ON [t].[object_id] = [c].[object_id]
I have to change the name and the datatype of a column of a table. I have about 150 stored procedures in the database, out of which about 25 refer to the same column. I need a query that can find the name of all the stored procedures which are dependent on this column.
I use this query:
SELECT OBJECT_NAME(M.object_id), M.*
FROM sys.sql_modules M
JOIN sys.procedures P
ON M.object_id = P.object_id
WHERE M.definition LIKE '%blah%'
Obviously you'd have to substitute "blah" for the name of your column.
Try this 1
From Sp
SELECT Name as [Stored Procedure Name]
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%getdate%' order by Name
From Table
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%EmployeeID%'
ORDER BY schema_name, table_name;
Problem:
As you know there is no way to query what fields are referenced by a function or stored procedure.
The closest we can get is an approximation.
We can tell which tables are referenced and what fields might possibly be referenced by those tables.
For example, if you have "CreatedDate" referenced by the "Person" table and you join to the "Order" table (which also has a "CreatedDate" field), it will find a “false-positive” match to "Order.CreatedDate" when you were only looking for "Person.CreatedDate".
Searching the Text of the object's script for field names is unfortunately the best we can do for now.
The good news is, it won’t miss identifying fields that are actually used.
If anything it might pull in more than what were used (due to shared field names or commented out code).
The only exception would be dynamic SQL, as Tables are not linked to Object Scripts if they are embedded in a dynamic string.
Workaround:
CREATE FUNCTION [dbo].[ft_Schema_Column_Script]
(
#ScriptName nVarChar(128) = '%',
#TableName nVarChar(128) = '%',
#ColumnName nVarChar(128) = '%'
)
RETURNS TABLE
AS
RETURN
(
SELECT ##SERVERNAME[ServerName], DB_NAME()[DatabaseName],
SS.name[ScriptSchemaName], SO.name[ScriptName],
SO.type_desc[ScriptType],
TS.name[TableSchemaName], T.name[TableName], C.name[ColumnName],
UT.name[ColumnType], C.max_length[MaxLength],
C.precision[NumericPrecision], C.scale[Scale],
C.is_nullable[Nullable],
C.is_identity[IsIdentity],
C.column_id[Ordinal],
EP.value[Description]
FROM sys.sql_modules as M
JOIN sys.objects as SO--Script Object.
ON M.object_id = SO.object_id
JOIN sys.schemas as SS--Script Schema.
ON SS.schema_id = SO.schema_id
JOIN sys.sql_expression_dependencies D
ON D.referencing_id = SO.object_id
JOIN sys.tables as T
ON T.object_id = D.referenced_id
JOIN sys.schemas as TS--Table Schema.
ON TS.schema_id = T.schema_id
JOIN sys.columns as C
ON C.object_id = T.object_id
LEFT JOIN sys.types AS UT--Left Join because of user-defined/newer types.
ON UT.user_type_id = C.user_type_id
LEFT JOIN sys.extended_properties AS EP
ON EP.major_id = C.object_id
AND EP.minor_id = C.column_id
AND EP.name = 'MS_Description'
WHERE T.name LIKE #TableName ESCAPE '\'
AND C.name LIKE #ColumnName ESCAPE '\'
AND SO.name LIKE #ScriptName ESCAPE '\'
--Use RegEx to exclude false-posotives by from similar ColumnNames.
-- (e.g. Ignore the "ModifiedBy" field when matching on "Modified").
-- Use C.name instead of #ColumnName to further reduce false-positives.
AND M.definition LIKE ( N'%[ ~`!##$\%\^&*()+-=\[\]\\{}|;'''':",./<>?]'
+ C.name
+ N'[ ~`!##$\%\^&*()+-=\[\]\\{}|;'''':",./<>?]%'
) ESCAPE '\'
)
GO
Test:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT * FROM dbo.ft_Schema_Column_Script('ScriptName', DEFAULT, DEFAULT) as C
SELECT * FROM dbo.ft_Schema_Column_Script(DEFAULT, 'TableName', DEFAULT) as C
SELECT * FROM dbo.ft_Schema_Column_Script(DEFAULT, DEFAULT, 'ColumnName') as C
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
Test the example above to see if it's good enough to meet your needs.
Results:
Example output when running this function searching for the Column Name "Created".
It searches Stored Procedures (Sprocs), User-Defined-Functions (UDF's), Triggers, but not Jobs.
The cool thing is:
This not only searches for Columns referenced by Scripts,but also Scripts referenced by Columns (or Tables)!
-- Search in All Objects
SELECT OBJECT_NAME(OBJECT_ID),
definition
FROM sys.sql_modules
WHERE definition LIKE '%' + 'BusinessEntityID' + '%'
Search in Stored Procedures Only:
SELECT DISTINCT OBJECT_NAME(OBJECT_ID),
object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'BusinessEntityID' + '%'
This question already has answers here:
How do you list the primary key of a SQL Server table?
(28 answers)
Closed 3 years ago.
I want to get a particular table's primary key using SQL query for SQL Server database.
In MySQL I am using following query to get table primary key:
SHOW KEYS FROM tablename WHERE Key_name = 'PRIMARY'
What is equivalent of above query for SQL Server ?.
If There is a query that will work for both MySQL and SQL Server then It will be an ideal case.
I also found another one for SQL Server:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = 'TableName' AND TABLE_SCHEMA = 'Schema'
Found another one:
SELECT
KU.table_name as TABLENAME
,column_name as PRIMARYKEYCOLUMN
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
AND KU.table_name='YourTableName'
ORDER BY
KU.TABLE_NAME
,KU.ORDINAL_POSITION
;
I have tested this on SQL Server 2003/2005
Using SQL SERVER 2005, you can try
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
Found at SQL SERVER – 2005 – Find Tables With Primary Key Constraint in Database
From memory, it's either this
SELECT * FROM sys.objects
WHERE type = 'PK'
AND object_id = OBJECT_ID ('tableName')
or this..
SELECT * FROM sys.objects
WHERE type = 'PK'
AND parent_object_id = OBJECT_ID ('tableName')
I think one of them should probably work depending on how the data is stored
but I am afraid I have no access to SQL to actually verify the same.
SELECT COLUMN_NAME FROM {DATABASENAME}.INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME LIKE '{TABLENAME}' AND CONSTRAINT_NAME LIKE 'PK%'
WHERE
{DATABASENAME} = your database from your server AND
{TABLENAME} = your table name from which you want to see the primary key.
NOTE : enter your database name and table name without brackets.
select *
from sysobjects
where xtype='pk' and
parent_obj in (select id from sysobjects where name='tablename')
this will work in sql 2005
The code I'll give you works and retrieves not only keys, but a lot of data from a table in SQL Server. Is tested in SQL Server 2k5/2k8, dunno about 2k. Enjoy!
SELECT DISTINCT
sys.tables.object_id AS TableId,
sys.columns.column_id AS ColumnId,
sys.columns.name AS ColumnName,
sys.types.name AS TypeName,
sys.columns.precision AS NumericPrecision,
sys.columns.scale AS NumericScale,
sys.columns.is_nullable AS IsNullable,
( SELECT
COUNT(column_name)
FROM
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
WHERE
TABLE_NAME = sys.tables.name AND
CONSTRAINT_NAME =
( SELECT
constraint_name
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
TABLE_NAME = sys.tables.name AND
constraint_type = 'PRIMARY KEY' AND
COLUMN_NAME = sys.columns.name
)
) AS IsPrimaryKey,
sys.columns.max_length / 2 AS CharMaxLength /*BUG*/
FROM
sys.columns, sys.types, sys.tables
WHERE
sys.tables.object_id = sys.columns.object_id AND
sys.types.system_type_id = sys.columns.system_type_id AND
sys.types.user_type_id = sys.columns.user_type_id AND
sys.tables.name = 'TABLE'
ORDER BY
IsPrimaryKey
You can use only the primary key part, but I think that the rest might become handy.
Best regards,
David
This should list all the constraints and at the end you can put your filters
/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/
WITH ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME)
AS
(
SELECT CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,
CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,
PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,
PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,
PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,
REFERENCE_TABLE_NAME='' ,
REFERENCE_COL_NAME=''
FROM sys.key_constraints as PKnUKEY
INNER JOIN sys.tables as PKnUTable
ON PKnUTable.object_id = PKnUKEY.parent_object_id
INNER JOIN sys.index_columns as PKnUColIdx
ON PKnUColIdx.object_id = PKnUTable.object_id
AND PKnUColIdx.index_id = PKnUKEY.unique_index_id
INNER JOIN sys.columns as PKnUKEYCol
ON PKnUKEYCol.object_id = PKnUTable.object_id
AND PKnUKEYCol.column_id = PKnUColIdx.column_id
INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
ON oParentColDtl.TABLE_NAME=PKnUTable.name
AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,
CONSTRAINT_TYPE='FK',
PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,
PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,
PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,
REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,
REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30))
FROM sys.foreign_key_columns FKC
INNER JOIN sys.sysobjects oConstraint
ON FKC.constraint_object_id=oConstraint.id
INNER JOIN sys.sysobjects oParent
ON FKC.parent_object_id=oParent.id
INNER JOIN sys.all_columns oParentCol
ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/
AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
INNER JOIN sys.sysobjects oReference
ON FKC.referenced_object_id=oReference.id
INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
ON oParentColDtl.TABLE_NAME=oParent.name
AND oParentColDtl.COLUMN_NAME=oParentCol.name
INNER JOIN sys.all_columns oReferenceCol
ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/
AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
)
select * from ALL_KEYS_IN_TABLE
where
PARENT_TABLE_NAME in ('YOUR_TABLE_NAME')
or REFERENCE_TABLE_NAME in ('YOUR_TABLE_NAME')
ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;
For reference please read thru - http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx
Keep in mind that if you want to get exact primary field you need to put TABLE_NAME and TABLE_SCHEMA into the condition.
this solution should work:
select COLUMN_NAME from information_schema.KEY_COLUMN_USAGE
where CONSTRAINT_NAME='PRIMARY' AND TABLE_NAME='TABLENAME'
AND TABLE_SCHEMA='DATABASENAME'
It is also (Transact-SQL) ... according to BOL.
-- exec sp_serveroption 'SERVER NAME', 'data access', 'true' --execute once
EXEC sp_primarykeys #table_server = N'server_name',
#table_name = N'table_name',
#table_catalog = N'db_name',
#table_schema = N'schema_name'; --frequently 'dbo'