Hope this is in the right thread, sorry if not!
I have run into a problem, i need to find out that column(s) in a table that makes the primary key.
I thought that this code did the trick.
***
DECLARE @.c varchar(4000), @.t varchar(128)
SET @.c = ''
SET @.t='contact_pmc_contact_relations'
Select @.c = @.c + c.name + ',' FROM syscolumns c INNER JOIN sysobjects o ON o.id = c.id inner join sysindexkeys k on o.id = k.id WHERE o.name = @.t and k.colid = c.colid ORDER BY c.colid
SELECT Substring(@.c, 1, Datalength(@.c) - 1)
***
This works in most of my cases. But i have encounterd tabels where this code doesn't work.
Here is a dump from one of the tabels where it doesn't work.
SELECT *
FROM sysindexkeys
WHERE (id = 933578364) <--id of the table
***
id indid colid keyno
933578364 1 1 1
933578364 1 2 2
933578364 2 1 1
933578364 3 2 1
933578364 4 3 1
933578364 5 4 1
933578364 6 5 1
933578364 7 6 1
933578364 8 7 1
Not sure if that dump made any sense, but i hope it did.
If i look at the table in SQL Enterprise manager there is no relations, no indexes only my primarykey made up with 2 columns (column id 1 and 2).
So, anyone know how i could solve this problem?
Regards
/Anders
to get the pk one of the best and recommended method will be
select *from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_type='PRIMARY KEY'
Madhu
|||
SQL Server 2000 ou 2005 ?
|||Currently we'r using sql server 2000, but if there is a way that works on both 2000 and 2005 it would be really great!|||
Madhu K Nair wrote:
to get the pk one of the best and recommended method will be
select *from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_type='PRIMARY KEY'
Madhu
Either im missunderstanding or that doesn't work. I want to get the columns that compose the primarykey. Not the primary key itself.
|||i got the issue. Since there is no direct method (Single select statement), I will give u a workaround. If u check sp_helpconstraint , it give u the details. U can use sp_helptext to find the sourcecode behind this SP and do the required modification adn create u r own SP.
Madhu
|||
select * from INFORMATION_SCHEMA.[CONSTRAINT_COLUMN_USAGE]
where constraint_type='PRIMARY KEY'
Jens K. Suessmeyer
http://www.sqlserver2005.de
|||
Is this you are looking for?
Code Snippet
SELECT CCU.TABLE_NAME
, CCU.COLUMN_NAME
, ORDINAL_POSITION
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
JOIN INFORMATION_SCHEMA.[KEY_COLUMN_USAGE] CCU
ON TC.TABLE_NAME = CCU.TABLE_NAME
AND TC.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY CCU.TABLE_NAME, ORDINAL_POSITION
Just expanding to what others meant to answer to your question.
No comments:
Post a Comment