从数据库中删除记录

时间:2011-03-19 22:16:11

标签: sql-server sql-server-2008

嗨,请帮帮我 我有一个包含大量表格的数据库。我必须从整个数据库中删除所有记录(除了10个给定的studentID),其中studentId不在给定的10个ID中。 studentID是表中的主键和许多表中的外键。我不确定即使其他表可能具有相同的studentID,现在我想编写一个脚本来执行此任务,这将删除父表和子表(sql server 2008)中的所有记录。

1 个答案:

答案 0 :(得分:5)

对于外键约束,您必须首先从子表中执行删除。

这将是这样的,因为你已经有了StudentIDs,所以不需要连接到父表。

Delete child1 Where studentID not in (1,2,4,5,6,77,122,123,1222,12121,99999)
Delete child2 Where studentID not in (1,2,4,5,6,77,122,123,1222,12121,99999)
Delete child3 Where studentID not in (1,2,4,5,6,77,122,123,1222,12121,99999)
Delete students Where studentID not in (1,2,4,5,6,77,122,123,1222,12121,99999)

如果你有一个“孙子”表,例如学生 - >帐户 - > AccountHistory,然后你会以相反的顺序删除,例如:

Delete AccountHitory
where AccountID not in (
    select AccountID
    From Account
    Where studentID in (1,2,4,5,6,77,122,123,1222,12121,99999))

Delete Account Where studentID not in (1,2,4,5,6,77,122,123,1222,12121,99999)

Delete Student Where studentID not in (1,2,4,5,6,77,122,123,1222,12121,99999)

<小时/> 要查找外键链接的层次结构,可以使用此查询

示例表

create table student (studentid int identity primary key)
create table student_class (id int primary key, studentid int references student(studentid))
create table student_class_attendance (student_classid int references student_class(id), attended datetime)
create table invoice (id int primary key, studentid int references student(studentid), due datetime, amount money)

查询查找链接表

;with tmp(lvl,FK,PK) As (
    SELECT 1, FK.TABLE_NAME, PK.TABLE_NAME
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C 
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME 
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME 
    WHERE PK.TABLE_NAME = 'student'
    UNION ALL
    SELECT lvl+1, FK.TABLE_NAME, PK.TABLE_NAME
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C 
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME 
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME 
    INNER JOIN tmp on tmp.FK = PK.TABLE_NAME
)
SELECT *
FROM tmp
order by lvl desc
相关问题