2

我有以下 SQL 语句来检索删除约束语句。

SELECT DISTINCT 'ALTER TABLE '+TABLE_NAME+' DROP CONSTRAINT '+CONSTRAINT_NAME AS 'DropConstraintStatement'
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
WHERE TABLE_NAME = 'USER';

这个查询的结果是:

  1. ALTER TABLE UNITS DROP CONSTRAINT FK_USER_TASK_ID
  2. ALTER TABLE UNITS DROP CONSTRAINT PK_USER
  3. ALTER TABLE UNITS DROP CONSTRAINT UQ_USER_NAME_VERSION

我想在 Java 应用程序中执行这些语句,因此我需要对这些语句进行排序,以便删除主键约束位于最后一个位置,例如:

  1. ALTER TABLE UNITS DROP CONSTRAINT FK_USER_TASK_ID
  2. ALTER TABLE UNITS DROP CONSTRAINT UQ_USER_NAME_VERSION
  3. ALTER TABLE UNITS DROP CONSTRAINT PK_USER

使用本机 SQL 是否有可能做到这一点?

4

1 回答 1

2

INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE不包含区分 PK 和其他约束的必要信息。如果您确定您的 PK 名称以 PK 开头,您可以尝试ORDER BY像这样添加:

ORDER BY CASE WHEN CONSTRAINT_NAME LIKE 'PK%' THEN 1 ELSE 0 END

但是,我建议切换到 SQL Server 系统视图以获得更精确的数据。sys.key_constraints保存有关主键和唯一约束以及sys.foreign_keys外键的信息。

WITH CTE AS 
(
    SELECT OBJECT_NAME(parent_object_id) AS TABLE_NAME
        , name AS CONSTRAINT_NAME, Type
    FROM sys.key_constraints
    WHERE parent_object_id = object_id('YourTable')

    UNION

    SELECT OBJECT_NAME(parent_object_id) AS TABLE_NAME
        , name AS CONSTRAINT_NAME, Type
    FROM sys.foreign_keys
    WHERE parent_object_id = object_id('YourTable')
)
SELECT 'ALTER TABLE '+TABLE_NAME+' DROP CONSTRAINT '+CONSTRAINT_NAME AS 'DropConstraintStatement'
FROM CTE 
ORDER BY CASE WHEN Type = 'PK' THEN 1 ELSE 0 END
于 2013-06-17T14:19:12.780 回答