查找正在使用的外键

时间:2009-04-06 09:53:59

标签: sql sql-server sql-server-2008

通过引用用户表,我有大约50个创建者和更改者的表。当我想删除用户时,我想创建一个这个用户有数据表的列表,这样就可以删除/编辑属于所述用户的所有内容。有没有办法在SQL中执行此操作?

6 个答案:

答案 0 :(得分:3)

您可以使用级联删除。

答案 1 :(得分:3)

不完全确定你要去的地方..

如果您想要引用表的外键列表,请尝试此问题 How can I list all foreign keys referencing a given table in SQL Server?

答案 2 :(得分:2)

答案 3 :(得分:2)

SQL 2005+提供了许多系统视图,如sys.tables和sys.foreign_key_columns,它们可以为您提供帮助。

SELECT
  pt.name AS ParentTable,
  pc.name AS ParentColumn,
  rt.name AS ReferencedTable,
  rc.name AS ReferencedColumn
FROM sys.foreign_key_columns fkc
  INNER JOIN sys.tables pt ON pt.object_id = fkc.parent_object_id
  INNER JOIN sys.columns pc ON pc.column_id = fkc.parent_column_id AND
                               pc.object_id = fkc.parent_object_id
  INNER JOIN sys.tables rt ON rt.object_id = fkc.referenced_object_id
  INNER JOIN sys.columns rc ON rc.column_id = fkc.referenced_column_id AND
                               rc.object_id = fkc.referenced_object_id

答案 4 :(得分:1)

这将列出您的ID所在的所有表:

DECLARE @Query        varchar(1000)
DECLARE @MaxRow       int
DECLARE @CurrentRow   int
DECLARE @CurrentTable varchar(500)
DECLARE @UserID       int

SET @UserID=???

CREATE TABLE #Rows
(
     RowID                int not null primary key identity(1,1)
    ,TableWithForeignKey  varchar(500)
)


CREATE TABLE #Temp
(
    RowValue  int
)

INSERT INTO #Rows
    (TableWithForeignKey )
    select
        t.name as TableWithForeignKey  --, fk.constraint_column_id as FK_PartNo , c.name as ForeignKeyColumn 
        from sys.foreign_key_columns as fk
            inner join sys.tables    as t on fk.parent_object_id = t.object_id
            inner join sys.columns   as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
        where fk.referenced_object_id = (select object_id from sys.tables where name = '????????')
        --order by TableWithForeignKey, FK_PartNo
SELECT @MaxRow=@@ROWCOUNT
SET @CurrentRow=0
SELECT * FROM #Rows
WHILE @CurrentRow<@MaxRow
BEGIN
    SET @CurrentRow=@CurrentRow+1
    SELECT @CurrentTable=TableWithForeignKey FROM #Rows WHERE RowID=@CurrentRow
    --SET @Query='DELETE FROM '+@CurrentTable+' WHERE UserID='+CONVERT(varchar(20),@UserID)
    SET @Query='SELECT COUNT(*) FROM '+@CurrentTable+' WHERE YourIDhere='+CONVERT(varchar(20),@UserID)
    PRINT @Query
    INSERT INTO #Temp
    EXECUTE (@Query)

    IF NOT EXISTS (SELECT RowValue FROM #Temp WHERE RowValue>0)
    BEGIN
        PRINT 'no matches found'
        DELETE #Rows WHERE RowID=@CurrentRow
    END
    ELSE
    BEGIN
        PRINT 'matches found!!'
    END

    DELETE #Temp
END
--list all tables where the ID exists
SELECT * FROM #Rows

答案 5 :(得分:0)

已经发布了一些查找通过外键关系引用User表的表的方法,这是另一种方法:http://www.sqlservercurry.com/2009/03/simple-stored-procedure-to-find-foreign.html

获得表列表后,您将不得不编写SQL以确定哪些表具有特定用户的记录。没有办法解决这个问题。由于查询看起来都一样,您可以将表格列表粘贴到Excel中,使用公式构建查询,然后将查询粘贴回SSMS。