SQL Server 2008按主键选择约束顺序

时间:2013-06-17 13:43:27

标签: sql sql-server sql-server-2008 sorting constraints

我有以下SQL语句来检索drop constraint语句。

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
  4. 我想在Java应用程序中执行这些语句,因此我需要对这些语句进行排序,使得drop主键约束位于最后位置,如:

    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
    4. 使用本机SQL执行此操作是否有可能?

1 个答案:

答案 0 :(得分: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