我有以下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';
此查询的结果是:
我想在Java应用程序中执行这些语句,因此我需要对这些语句进行排序,使得drop主键约束位于最后位置,如:
使用本机SQL执行此操作是否有可能?
答案 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