I am making a utility for our program and i need to have the primary keys of a table separate from the other fields in a table. Now I have found and tweaked a bit of sql to get the primary keys...SELECT PKT.name, PKT.TName, COL.DATA_TYPE, COL.CHARACTER_MAXIMUM_LENGTHFROM (SELECT SC.name, SO.name AS TName FROM sys.sysobjects AS SO INNER JOIN sys.sysobjects AS SPK ON SO.id = SPK.parent_obj INNER JOIN sys.sysindexes AS SI ON SO.id = SI.id AND SPK.name = SI.name INNER JOIN sys.sysindexkeys AS SIK ON SO.id = SIK.id AND SI.indid = SIK.indid INNER JOIN sys.syscolumns AS SC ON SO.id = SC.id AND SIK.colid = SC.colid WHERE (SO.name = 'Doc') AND (SO.xtype = 'U') AND (SPK.xtype = 'PK')) AS PKT INNER JOIN INFORMATION_SCHEMA.COLUMNS AS COL ON PKT.TName = COL.TABLE_NAME AND PKT.name = COL.COLUMN_NAME
This works beautifully to get my prmiary keys of whatever table I need, what i want now is to get the other fields of the table and their datatypes and max lengths. I thought I could join it back on the information_schema.columns table and 'remove' the primary key columns that I already know about. SELECT COL2.TABLE_NAME, COL2.COLUMN_NAME, COL2.DATA_TYPE, COL2.CHARACTER_MAXIMUM_LENGTHFROM INFORMATION_SCHEMA.COLUMNS AS COL2 LEFT OUTER JOIN (SELECT PKT.name, PKT.TName, COL.DATA_TYPE, COL.CHARACTER_MAXIMUM_LENGTH FROM (SELECT SC.name, SO.name AS TName FROM sys.sysobjects AS SO INNER JOIN sys.sysobjects AS SPK ON SO.id = SPK.parent_obj INNER JOIN sys.sysindexes AS SI ON SO.id = SI.id AND SPK.name = SI.name INNER JOIN sys.sysindexkeys AS SIK ON SO.id = SIK.id AND SI.indid = SIK.indid INNER JOIN sys.syscolumns AS SC ON SO.id = SC.id AND SIK.colid = SC.colid WHERE (SO.name = 'Doc') AND (SO.xtype = 'U') AND (SPK.xtype = 'PK')) AS PKT INNER JOIN INFORMATION_SCHEMA.COLUMNS AS COL ON PKT.TName = COL.TABLE_NAME AND PKT.name = COL.COLUMN_NAME) AS PrimeKeys ON PrimeKeys.name <> COL2.COLUMN_NAMEWHERE (COL2.TABLE_NAME = PrimeKeys.TName)
But this produces results that are definitely not correct. I have tried right and left joins and they produce the same results for this table, and inner join produces results very off.