Hello all. I need to extract the column names that form the primary key group on a table in SQL Server. I have a table called Account and it contains ten columns. The primary key consists of two columns - MasterAccountID, AccountID. This primary key is a unique constraint and is clustered (it acts as an index as well as a primary key group). I have tried the following to no avail:
exec sp_pkeys Account -> returns no rows
exec sp_helpindex Account -> throws an error stating that the object 'Account' does not exist
If I run the following SQL statement, I can see all of the PK_* constraints in the database, so I know they are there:
select * from information_schema.table_constraints
where constraInt_type IN ('PRIMARY KEY','FOREIGN KEY')
Again, I need to be able to specify a table name and have it return the columns (don't care if it returns extra fields) that make up the primary key fields for that table. Thanks!
Perhaps something like this:
select
*fromsyscolumnswhere id=object_id('yourTable')and colidin(select colidfromsysindexkeyswhere id=object_id('yourTable'))|||declare
@.TableNamevarchar(255)set
@.TableName='tblPersons'SELECT
CCU.*FROM
INFORMATION_SCHEMA.Table_Constraints TCJOININFORMATION_SCHEMA.Constraint_Column_Usage CCUON CCU.CONSTRAINT_NAME= TC.CONSTRAINT_NAMEWHERE
CONSTRAINT_TYPE
='PRIMARY KEY'AND TC.TABLE_NAME= @.TableName
but this also works: look at the quotes ''
execsp_pkeys'tblPersons'
No comments:
Post a Comment