只有主键表

时间:2017-12-02 21:14:22

标签: sql sql-server-2008

我想找到只有我指定列的主键的表。我想要的是:

SELECT   
    OBJECT_NAME(ic.OBJECT_ID) AS TableName, 
    1 AS InsertPrimaryGuidOnly,
    0 AS InsertCustomerOnly, 
    0 AS InsertApplicationOnly, 
    0 AS InsertNoKeyOnly  
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  
    AND COL_NAME(ic.OBJECT_ID, ic.column_id) =  'CREDITCHECKGUID'    
    AND OBJECT_NAME(ic.OBJECT_ID) NOT IN ('Customer', 'Application')  

我正在获取表列表,但它还列出了具有列作为主键和外键的表。我想要的只是主键表。如果主要密钥也是外键,我不想列出该表。请帮忙。

1 个答案:

答案 0 :(得分:0)

在查询中放置此where子句;

AND ic.OBJECT_ID NOT IN (select parent_object_id from sys.foreign_keys fk)

完整查询;

SELECT   
    ic.OBJECT_ID,
    OBJECT_NAME(ic.OBJECT_ID) AS TableName, 
    1 AS InsertPrimaryGuidOnly,
    0 AS InsertCustomerOnly, 
    0 AS InsertApplicationOnly, 
    0 AS InsertNoKeyOnly  
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  
    AND COL_NAME(ic.OBJECT_ID, ic.column_id) =  'CREDITCHECKGUID'
    AND OBJECT_NAME(ic.OBJECT_ID) NOT IN ('Customer', 'Application')
    AND ic.OBJECT_ID NOT IN (select parent_object_id from sys.foreign_keys fk)