如何列出引用SQL Server中给定表的所有外键?

How can I list all foreign keys referencing a given table in SQL Server?

我需要删除SQL Server数据库中高度引用的表。如何获取删除表所需的所有外键约束的列表?

(SQL比在Management Studio的GUI中单击更可取。)


没有人知道为什么,但不建议我使用到一个sp_fkeys查询给定的表的外键。

1
EXEC sp_fkeys 'TableName'

所以,你可以指定的架构:

1
EXEC sp_fkeys @pktable_name = 'TableName', @pktable_owner = 'dbo'

没有指定的模式,下面的文档状态:

If pktable_owner is not specified, the default table visibility rules
of the underlying DBMS apply.

In SQL Server, if the current user owns a table with the specified
name, that table's columns are returned. If pktable_owner is not
specified and the current user does not own a table with the specified
pktable_name, the procedure looks for a table with the specified
pktable_name owned by the database owner. If one exists, that table's
columns are returned.


我使用的图解特征数据库中的SQL服务器管理工作室,但排除了这是因为你先为我工作在SQL Server 2008(没有2005年)。

被指表和列名称的列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 = 'TableOthersForeignKeyInto')
ORDER BY
    TableWithForeignKey, FK_PartNo

让外国的关键约束名称

1
2
3
4
5
SELECT DISTINCT name FROM sys.objects WHERE object_id IN
(   SELECT fk.constraint_object_id FROM sys.foreign_key_columns AS fk
    WHERE fk.referenced_object_id =
        (SELECT object_id FROM sys.tables WHERE name = 'TableOthersForeignKeyInto')
)


这给你:

  • 它本身的FK
  • FK的图式,这是属于
  • "引用表或表有一个FK。
  • "引用柱或柱内引用表,点到FK
  • "引用的表或表,有一个关键的柱是指向到你.
  • "参考柱或柱这是一个关键FK是指向到你

下面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
SELECT  obj.name AS FK_NAME,
    sch.name AS [schema_name],
    tab1.name AS [TABLE],
    col1.name AS [COLUMN],
    tab2.name AS [referenced_table],
    col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
    ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
    ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
    ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
    ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
    ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
    ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id


试试这个:

1
sp_help 'TableName'


你应该注意引用其他对象。

如果所引用的表在表的其他比它可能是由其他对象,如在参考视图,存储过程,函数和更多。

我真的很好的GUI工具,如"视图"对话框或在依赖关系分析的免费工具,因为这样apexsql搜索寻找其他对象的依赖关系可以是错误之,如果你想做一个SQL只。

如果SQL是唯一的选择,你可以做这样的尝试。

1
2
3
4
SELECT O.name AS [Object_Name], C.text AS [Object_Definition]
FROM sys.syscomments C
INNER JOIN sys.all_objects O ON C.id = O.object_id
WHERE C.text LIKE '%table_name%'

在得到原问题列表中所有外键引用的表,这样一个高度表可以被删除。

这个查询返回所有的小"拖放拖放命令外国密钥需要一个特定的表的所有外键:

1
2
3
4
5
6
7
8
SELECT
   'ALTER TABLE ['+sch.name+'].['+referencingTable.Name+'] DROP CONSTRAINT ['+foreignKey.name+']' '[DropCommand]'
FROM sys.foreign_key_columns fk
    JOIN sys.tables referencingTable ON fk.parent_object_id = referencingTable.object_id
    JOIN sys.schemas sch ON referencingTable.schema_id = sch.schema_id
    JOIN sys.objects foreignKey ON foreignKey.object_id = fk.constraint_object_id
    JOIN sys.tables referencedTable ON fk.referenced_object_id = referencedTable.object_id
WHERE referencedTable.name = 'MyTableName'

输出的例子:

1
2
3
[DropCommand]
ALTER TABLE [dbo].[OtherTable1] DROP CONSTRAINT [FK_OtherTable1_MyTable]
ALTER TABLE [dbo].[OtherTable2] DROP CONSTRAINT [FK_OtherTable2_MyTable]

omit的WHERE子句的命令去删除所有当前数据库中的外键。


这是我将使用的SQL代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
SELECT
   f.name AS 'Name of Foreign Key',
   OBJECT_NAME(f.parent_object_id) AS 'Table name',
   COL_NAME(fc.parent_object_id,fc.parent_column_id) AS 'Fieldname',
   OBJECT_NAME(t.object_id) AS 'References Table name',
   COL_NAME(t.object_id,fc.referenced_column_id) AS 'References fieldname',

   'ALTER TABLE [' + OBJECT_NAME(f.parent_object_id) + ']  DROP CONSTRAINT [' + f.name + ']' AS 'Delete foreign key',

   'ALTER TABLE [' + OBJECT_NAME(f.parent_object_id) + ']  WITH NOCHECK ADD CONSTRAINT [' +
        f.name + '] FOREIGN KEY([' + COL_NAME(fc.parent_object_id,fc.parent_column_id) + ']) REFERENCES ' +
        '[' + OBJECT_NAME(t.object_id) + '] ([' +
        COL_NAME(t.object_id,fc.referenced_column_id) + '])' AS 'Create foreign key'
    -- , delete_referential_action_desc AS 'UsesCascadeDelete'
FROM sys.foreign_keys AS f,
     sys.foreign_key_columns AS fc,
     sys.tables t
WHERE f.OBJECT_ID = fc.constraint_object_id
AND t.OBJECT_ID = fc.referenced_object_id
AND OBJECT_NAME(t.object_id) = 'Employees'      --  Just show the FKs which reference a particular table
ORDER BY 2

SQL不太清楚,所以我们来看一个例子。

所以,假设我想把Employees表放到微软心爱的Northwind数据库中,但SQL Server告诉我有一个或多个外键阻止了我这样做。

上面的SQL命令将返回这些结果…

Foreign Keyes

它显示有3个外键引用Employees表。换句话说,在第一次删除这三个外键之前,不允许删除(删除)这个表。

在结果中,第一行是以下外键约束在结果中的显示方式。

1
2
3
ALTER TABLE [dbo].[Employees]  WITH NOCHECK
ADD CONSTRAINT [FK_Employees_Employees] FOREIGN KEY([ReportsTo])
REFERENCES [dbo].[Employees] ([EmployeeID])

倒数第二列显示了删除这些外键之一时需要使用的SQL命令,例如:

1
ALTER TABLE [Employees] DROP CONSTRAINT [FK_Employees_Employees]

…右边的列显示了创建它的SQL…

1
2
3
ALTER TABLE [Employees] WITH NOCHECK
ADD CONSTRAINT [FK_Employees_Employees]
FOREIGN KEY([ReportsTo]) REFERENCES [Employees] ([EmployeeID])

使用所有这些命令,您可以删除相关的外键以允许您删除表,然后在以后重新创建表。

呸。希望这有帮助。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
SELECT PKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
       PKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O1.SCHEMA_ID)),
       PKTABLE_NAME = CONVERT(SYSNAME,O1.NAME),
       PKCOLUMN_NAME = CONVERT(SYSNAME,C1.NAME),
       FKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
       FKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O2.SCHEMA_ID)),
       FKTABLE_NAME = CONVERT(SYSNAME,O2.NAME),
       FKCOLUMN_NAME = CONVERT(SYSNAME,C2.NAME),
       -- Force the column to be non-nullable (see SQL BU 325751)
       --KEY_SEQ             = isnull(convert(smallint,k.constraint_column_id), sysconv(smallint,0)),
       UPDATE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsUpdateCascade')
                                        WHEN 1 THEN 0
                                        ELSE 1
                                      END),
       DELETE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsDeleteCascade')
                                        WHEN 1 THEN 0
                                        ELSE 1
                                      END),
       FK_NAME = CONVERT(SYSNAME,OBJECT_NAME(F.OBJECT_ID)),
       PK_NAME = CONVERT(SYSNAME,I.NAME),
       DEFERRABILITY = CONVERT(SMALLINT,7)   -- SQL_NOT_DEFERRABLE
FROM   SYS.ALL_OBJECTS O1,
       SYS.ALL_OBJECTS O2,
       SYS.ALL_COLUMNS C1,
       SYS.ALL_COLUMNS C2,
       SYS.FOREIGN_KEYS F
       INNER JOIN SYS.FOREIGN_KEY_COLUMNS K
         ON (K.CONSTRAINT_OBJECT_ID = F.OBJECT_ID)
       INNER JOIN SYS.INDEXES I
         ON (F.REFERENCED_OBJECT_ID = I.OBJECT_ID
             AND F.KEY_INDEX_ID = I.INDEX_ID)
WHERE  O1.OBJECT_ID = F.REFERENCED_OBJECT_ID
       AND O2.OBJECT_ID = F.PARENT_OBJECT_ID
       AND C1.OBJECT_ID = F.REFERENCED_OBJECT_ID
       AND C2.OBJECT_ID = F.PARENT_OBJECT_ID
       AND C1.COLUMN_ID = K.REFERENCED_COLUMN_ID
       AND C2.COLUMN_ID = K.PARENT_COLUMN_ID

1
2
3
4
5
6
SELECT
  object_name(parent_object_id),
  object_name(referenced_object_id),
  name
FROM sys.foreign_keys
WHERE parent_object_id = object_id('Table Name')


最简单的方法是在SQL中使用sys.foreign_keys_列。在这里,表包含所有外键的对象ID,它们与引用的列ID、引用的表ID以及引用的列和表相关。由于ID保持不变,因此对于模式和表中的进一步修改,结果将是可靠的。

查询:

1
2
3
4
5
6
7
8
9
10
SELECT    
OBJECT_NAME(fkeys.constraint_object_id) foreign_key_name
,OBJECT_NAME(fkeys.parent_object_id) referencing_table_name
,COL_NAME(fkeys.parent_object_id, fkeys.parent_column_id) referencing_column_name
,OBJECT_SCHEMA_NAME(fkeys.parent_object_id) referencing_schema_name
,OBJECT_NAME (fkeys.referenced_object_id) referenced_table_name
,COL_NAME(fkeys.referenced_object_id, fkeys.referenced_column_id)
referenced_column_name
,OBJECT_SCHEMA_NAME(fkeys.referenced_object_id) referenced_schema_name
FROM sys.foreign_key_columns AS fkeys

我们还可以使用"Where"添加过滤器

1
2
WHERE OBJECT_NAME(fkeys.parent_object_id) = 'table_name' AND
OBJECT_SCHEMA_NAME(fkeys.parent_object_id) = 'schema_name'


我正在使用此脚本查找与外键相关的所有详细信息。我正在使用information.schema。以下是SQL脚本:

1
2
3
4
5
6
7
8
9
10
11
12
SELECT
    ccu.table_name AS SourceTable
    ,ccu.constraint_name AS SourceConstraint
    ,ccu.column_name AS SourceColumn
    ,kcu.table_name AS TargetTable
    ,kcu.column_name AS TargetColumn
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
    INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
        ON ccu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
        ON kcu.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME  
ORDER BY ccu.table_name

弗斯特

1
EXEC sp_fkeys 'Table', 'Schema'

然后使用nimbletext播放结果


一些好的答案。但我喜欢有一个查询的答案。本代码是采取从一sys.sp _ helpconstraint(系统程序)

这是微软的工作方式看起来如果有外键的表相关。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
--setup variables. Just change 'Customer' to tbl you want
DECLARE @objid INT,
    @objname nvarchar(776)
SELECT @objname = 'Customer'    
SELECT @objid = object_id(@objname)

IF EXISTS (SELECT * FROM sys.foreign_keys WHERE referenced_object_id = @objid)
    SELECT 'Table is referenced by foreign key' =
        db_name() + '.'
        + rtrim(schema_name(ObjectProperty(parent_object_id,'schemaid')))
        + '.' + object_name(parent_object_id)
        + ': ' + object_name(object_id)
    FROM sys.foreign_keys
    WHERE referenced_object_id = @objid
    ORDER BY 1

答案:想看样本测试_ dB _ name.dbo.account:FK _ _客户帐户


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
SELECT
OBJECT_NAME(parent_object_id) 'Parent table',
c.NAME 'Parent column name',
OBJECT_NAME(referenced_object_id) 'Referenced table',
cref.NAME 'Referenced column name'
FROM
sys.foreign_key_columns fkc
INNER JOIN
sys.columns c
   ON fkc.parent_column_id = c.column_id
      AND fkc.parent_object_id = c.object_id
INNER JOIN
sys.columns cref
   ON fkc.referenced_column_id = cref.column_id
      AND fkc.referenced_object_id = cref.object_id  WHERE   OBJECT_NAME(parent_object_id) = 'tablename'

如果你想得到的一切外交关系排除密钥表的其他表where条款写的"tablename


1
2
3
4
 SELECT OBJECT_NAME(fk.parent_object_id) AS ReferencingTable,
        OBJECT_NAME(fk.constraint_object_id) AS [FKContraint]
  FROM sys.foreign_key_columns AS fk
 WHERE fk.referenced_object_id = OBJECT_ID('ReferencedTable', 'U')

本节目的关系。如果是对外的关键约束。我是predates FK约束在数据库表使用触发器来执行。一些指的完整性,有时,没有什么,但同样的命名来表示柱的关系(指完整性和没有在所有)。

幸运的是,我们有一个一致的场景我能如此命名是引用表这样的评论:

1
SELECT OBJECT_NAME(object_id) FROM sys.columns WHERE name LIKE 'client_id'

这一选择为基础的用于生成脚本的是什么我需要做的在相关的表。


我已经使用这个在2008年和随访。它类似于其他一些解决方案,但所有的名字,真是一场cased手柄(latbin)collations案例的特异性。此外,你可以送它一个单表的名称和检索信息是一个表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
-->>SPECIFY THE DESIRED DB
USE ???
GO

/*********************************************************************************************

    LIST OUT ALL PRIMARY AND FOREIGN KEY CONSTRAINTS IN A DB OR FOR A SPECIFIED TABLE

*********************************************************************************************/

DECLARE @tblName VARCHAR(255)

/*******************/

    SET @tblName = NULL-->NULL will return all PK/FK constraints for every table in the database

/*******************/

SELECT PKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
       PKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O1.schema_id)),
       PKTABLE_NAME = CONVERT(SYSNAME,O1.name),
       PKCOLUMN_NAME = CONVERT(SYSNAME,C1.name),
       FKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
       FKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O2.schema_id)),
       FKTABLE_NAME = CONVERT(SYSNAME,O2.name),
       FKCOLUMN_NAME = CONVERT(SYSNAME,C2.name),
       -- Force the column to be non-nullable (see SQL BU 325751)
       KEY_SEQ             = isnull(CONVERT(SMALLINT,K.constraint_column_id),0),
       UPDATE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.object_id,'CnstIsUpdateCascade')  
                                        WHEN 1 THEN 0
                                        ELSE 1
                                      END),
       DELETE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.object_id,'CnstIsDeleteCascade')  
                                        WHEN 1 THEN 0
                                        ELSE 1
                                      END),
       FK_NAME = CONVERT(SYSNAME,OBJECT_NAME(F.object_id)),
       PK_NAME = CONVERT(SYSNAME,I.name),
       DEFERRABILITY = CONVERT(SMALLINT,7)   -- SQL_NOT_DEFERRABLE
FROM   sys.all_objects O1,
       sys.all_objects O2,
       sys.all_columns C1,
       sys.all_columns C2,
       sys.foreign_keys F
       INNER JOIN sys.foreign_key_columns K
         ON (K.constraint_object_id = F.object_id)
       INNER JOIN sys.indexes I
         ON (F.referenced_object_id = I.object_id
             AND F.key_index_id = I.index_id)
WHERE  O1.object_id = F.referenced_object_id
       AND O2.object_id = F.parent_object_id
       AND C1.object_id = F.referenced_object_id
       AND C2.object_id = F.parent_object_id
       AND C1.column_id = K.referenced_column_id
       AND C2.column_id = K.parent_column_id
       AND (   O1.name = @tblName
            OR O2.name = @tblName
            OR @tblName IS NULL)
ORDER BY PKTABLE_NAME,FKTABLE_NAME

工作时gishu我什么什么"能产生和使用下面的SQL在SQL Server 2005

1
2
3
4
5
6
7
8
9
10
SELECT t.name AS TableWithForeignKey, fk.constraint_column_id AS FK_PartNo,
       c.name AS ForeignKeyColumn, o.name AS FK_Name
  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
       INNER JOIN sys.objects AS o ON fk.constraint_object_id = o.object_id
  WHERE fk.referenced_object_id = (SELECT object_id FROM sys.tables
                                        WHERE name = 'TableOthersForeignKeyInto')
  ORDER BY TableWithForeignKey, FK_PartNo;

它显示的表列的名称和密钥,所有在1查询。


确定主密钥和唯一键的所有数据库中的表A…

本应列表所有的约束和尽头,你可以把你的滤波器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/
WITH   ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME)
AS
(
SELECT  CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,
        PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE=  oParentColDtl.DATA_TYPE,        
        REFERENCE_TABLE_NAME='' ,
        REFERENCE_COL_NAME=''

FROM sys.key_constraints AS PKnUKEY
    INNER JOIN sys.tables AS PKnUTable
            ON PKnUTable.object_id = PKnUKEY.parent_object_id
    INNER JOIN sys.index_columns AS PKnUColIdx
            ON PKnUColIdx.object_id = PKnUTable.object_id
            AND PKnUColIdx.index_id = PKnUKEY.unique_index_id
    INNER JOIN sys.columns AS PKnUKEYCol
            ON PKnUKEYCol.object_id = PKnUTable.object_id
            AND PKnUKEYCol.column_id = PKnUColIdx.column_id
     INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=PKnUTable.name
            AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT  CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE='FK',
        PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,    
        REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,
        REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30))
FROM sys.foreign_key_columns FKC
    INNER JOIN sys.sysobjects oConstraint
            ON FKC.constraint_object_id=oConstraint.id
    INNER JOIN sys.sysobjects oParent
            ON FKC.parent_object_id=oParent.id
    INNER JOIN sys.all_columns oParentCol
            ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
    INNER JOIN sys.sysobjects oReference
            ON FKC.referenced_object_id=oReference.id
    INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=oParent.name
            AND oParentColDtl.COLUMN_NAME=oParentCol.name
    INNER JOIN sys.all_columns oReferenceCol
            ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/

)

SELECT * FROM   ALL_KEYS_IN_TABLE
WHERE  
    PARENT_TABLE_NAME  IN ('YOUR_TABLE_NAME')
    OR REFERENCE_TABLE_NAME  IN ('YOUR_TABLE_NAME')
ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;

(请参考阅读通过http://blogs.msdn.com / B / sqltips /档案/ 469136.aspx/16/2005/09


有一种方法可以获取所选ID的所有职责的计数。只需更改@dbtablename value、@dbrowid value及其类型(如果int,则需要删除第82行中的""。.set@sql=)。享受。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
DECLARE @dbTableName VARCHAR(MAX) = 'User'
DECLARE @dbRowId uniqueidentifier = '21d34ecd-c1fd-11e2-8545-002219a42e1c'

DECLARE @FK_ROWCOUNT INT
DECLARE @SQL nvarchar(MAX)

DECLARE @PKTABLE_QUALIFIER sysname
DECLARE @PKTABLE_OWNER sysname
DECLARE @PKTABLE_NAME sysname
DECLARE @PKCOLUMN_NAME sysname
DECLARE @FKTABLE_QUALIFIER sysname
DECLARE @FKTABLE_OWNER sysname
DECLARE @FKTABLE_NAME sysname
DECLARE @FKCOLUMN_NAME sysname
DECLARE @UPDATE_RULE SMALLINT
DECLARE @DELETE_RULE SMALLINT
DECLARE @FK_NAME sysname
DECLARE @PK_NAME sysname
DECLARE @DEFERRABILITY sysname

IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL
    DROP TABLE #Temp1;
CREATE TABLE #Temp1 (
    PKTABLE_QUALIFIER sysname,
    PKTABLE_OWNER sysname,
    PKTABLE_NAME sysname,
    PKCOLUMN_NAME sysname,
    FKTABLE_QUALIFIER sysname,
    FKTABLE_OWNER sysname,
    FKTABLE_NAME sysname,
    FKCOLUMN_NAME sysname,
    UPDATE_RULE SMALLINT,
    DELETE_RULE SMALLINT,
    FK_NAME sysname,
    PK_NAME sysname,
    DEFERRABILITY sysname,
    FK_ROWCOUNT INT
    );
DECLARE FK_Counter_Cursor CURSOR FOR
    SELECT PKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
       PKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O1.SCHEMA_ID)),
       PKTABLE_NAME = CONVERT(SYSNAME,O1.NAME),
       PKCOLUMN_NAME = CONVERT(SYSNAME,C1.NAME),
       FKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
       FKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O2.SCHEMA_ID)),
       FKTABLE_NAME = CONVERT(SYSNAME,O2.NAME),
       FKCOLUMN_NAME = CONVERT(SYSNAME,C2.NAME),
       -- Force the column to be non-nullable (see SQL BU 325751)
       --KEY_SEQ             = isnull(convert(smallint,k.constraint_column_id), sysconv(smallint,0)),
       UPDATE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsUpdateCascade')
                                        WHEN 1 THEN 0
                                        ELSE 1
                                      END),
       DELETE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsDeleteCascade')
                                        WHEN 1 THEN 0
                                        ELSE 1
                                      END),
       FK_NAME = CONVERT(SYSNAME,OBJECT_NAME(F.OBJECT_ID)),
       PK_NAME = CONVERT(SYSNAME,I.NAME),
       DEFERRABILITY = CONVERT(SMALLINT,7)   -- SQL_NOT_DEFERRABLE
    FROM   SYS.ALL_OBJECTS O1,
           SYS.ALL_OBJECTS O2,
           SYS.ALL_COLUMNS C1,
           SYS.ALL_COLUMNS C2,
           SYS.FOREIGN_KEYS F
           INNER JOIN SYS.FOREIGN_KEY_COLUMNS K
             ON (K.CONSTRAINT_OBJECT_ID = F.OBJECT_ID)
           INNER JOIN SYS.INDEXES I
             ON (F.REFERENCED_OBJECT_ID = I.OBJECT_ID
                 AND F.KEY_INDEX_ID = I.INDEX_ID)
    WHERE  O1.OBJECT_ID = F.REFERENCED_OBJECT_ID
           AND O2.OBJECT_ID = F.PARENT_OBJECT_ID
           AND C1.OBJECT_ID = F.REFERENCED_OBJECT_ID
           AND C2.OBJECT_ID = F.PARENT_OBJECT_ID
           AND C1.COLUMN_ID = K.REFERENCED_COLUMN_ID
           AND C2.COLUMN_ID = K.PARENT_COLUMN_ID
           AND O1.NAME = @dbTableName
OPEN FK_Counter_Cursor;
FETCH NEXT FROM FK_Counter_Cursor INTO @PKTABLE_QUALIFIER, @PKTABLE_OWNER, @PKTABLE_NAME, @PKCOLUMN_NAME, @FKTABLE_QUALIFIER, @FKTABLE_OWNER, @FKTABLE_NAME, @FKCOLUMN_NAME, @UPDATE_RULE, @DELETE_RULE, @FK_NAME, @PK_NAME, @DEFERRABILITY;
WHILE @@FETCH_STATUS = 0
   BEGIN
        SET @SQL = 'SELECT @dbCountOut = COUNT(*) FROM [' + @FKTABLE_NAME + '] WHERE [' + @FKCOLUMN_NAME + '] = ''' + CAST(@dbRowId AS VARCHAR(MAX)) + '''';
        EXECUTE sp_executesql @SQL, N'@dbCountOut int OUTPUT', @dbCountOut = @FK_ROWCOUNT OUTPUT;
        INSERT INTO #Temp1 (PKTABLE_QUALIFIER, PKTABLE_OWNER, PKTABLE_NAME, PKCOLUMN_NAME, FKTABLE_QUALIFIER, FKTABLE_OWNER, FKTABLE_NAME, FKCOLUMN_NAME, UPDATE_RULE, DELETE_RULE, FK_NAME, PK_NAME, DEFERRABILITY, FK_ROWCOUNT) VALUES (@FKTABLE_QUALIFIER, @PKTABLE_OWNER, @PKTABLE_NAME, @PKCOLUMN_NAME, @FKTABLE_QUALIFIER, @FKTABLE_OWNER, @FKTABLE_NAME, @FKCOLUMN_NAME, @UPDATE_RULE, @DELETE_RULE, @FK_NAME, @PK_NAME, @DEFERRABILITY, @FK_ROWCOUNT)
      FETCH NEXT FROM FK_Counter_Cursor INTO @PKTABLE_QUALIFIER, @PKTABLE_OWNER, @PKTABLE_NAME, @PKCOLUMN_NAME, @FKTABLE_QUALIFIER, @FKTABLE_OWNER, @FKTABLE_NAME, @FKCOLUMN_NAME, @UPDATE_RULE, @DELETE_RULE, @FK_NAME, @PK_NAME, @DEFERRABILITY;
   END;
CLOSE FK_Counter_Cursor;
DEALLOCATE FK_Counter_Cursor;
GO
SELECT * FROM #Temp1
GO


这是外国的自然人的任何密钥选定的表。* assumes a _ firstablename _ secondtablename格式。

1
2
3
4
5
 DECLARE @tablename AS VARCHAR(MAX)
 SET @tablename = 'yourtablename'
 SELECT name
 FROM YOURDATABASE.sys.objects
 WHERE type_desc = 'FOREIGN_KEY_CONSTRAINT' AND (name LIKE '%_' + @tablename + 'empdb_%' OR name LIKE '%_' + @tablename )

这是一个更一般的形式:

1
2
3
4
 SELECT name
 FROM YOURDATABASE_PROD.sys.objects
 WHERE type_desc = 'FOREIGN_KEY_CONSTRAINT' AND name LIKE '%' + @tablename + '%' AND
 name NOT LIKE '[a-zA-Z0-9]' + @tablename + '%' AND name NOT LIKE '%' + @tablename + '[a-zA-Z0-9]'

以下解决方案对我有效:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
--Eliminar las llaves foraneas
DECLARE @query VARCHAR(8000)
DECLARE cursorRecorrerTabla cursor FOR

SELECT  'ALTER TABLE [PoaComFinH].['+sch.name+'].['+referencingTable.Name+'] DROP CONSTRAINT ['+foreignKey.name+']' 'query'
FROM PoaComFinH.sys.foreign_key_columns fk
JOIN PoaComFinH.sys.tables referencingTable ON fk.parent_object_id = referencingTable.object_id
JOIN PoaComFinH.sys.schemas sch ON referencingTable.schema_id = sch.schema_id
JOIN PoaComFinH.sys.objects foreignKey ON foreignKey.object_id = fk.constraint_object_id
JOIN PoaComFinH.sys.tables referencedTable ON fk.referenced_object_id = referencedTable.object_id


--3ro. abrir el cursor.
OPEN cursorRecorrerTabla
fetch NEXT FROM cursorRecorrerTabla
INTO @query
while @@fetch_status = 0
BEGIN
--inicio cuerpo del cursor
    print @query
    EXEC(@query)
--fin cuerpo del cursor
fetch NEXT FROM cursorRecorrerTabla
INTO @query
END
--cerrar cursor
close cursorRecorrerTabla
deallocate cursorRecorrerTabla