简体   繁体   English

如何在SQL Server中验证数据?

[英]How to validate data in sql server?

I have an issue related to data in sql server. 我有一个与sql server中的数据有关的问题。 In my database some of the constraint were not enabled ie they were not checked , After some time working on it we found this issue that a parent rows can be deleted without deleting child, which was an issue. 在我的数据库中,某些约束未启用,即未选中它们,经过一段时间的处理后,我们发现此问题是可以删除父行而不删除子行,这是一个问题。 I enabled all the constraint in the database using query 我使用查询启用了数据库中的所有约束

ALTER TABLE tbl_name CHECK CONSTRAINT ALL 

above query was executed on all the tables of that database without any error . 以上查询已在该数据库的所有表上执行,没有任何错误。 But my concern is whether it will work or not , if it will work on the existing data then what will happen to that data whose parent table data has been deleted. 但是我担心的是,它是否将起作用,如果它将对现有数据起作用,那么将删除其父表数据的那个数据将会发生什么。

I want to know is there any way such that I can validate such data data whose parent record doesn't exist in the entire database. 我想知道有什么方法可以验证其父记录不在整个数据库中的此类数据。 There are about 270 constraint containing FOREIGN KEY AND UNIQUE KEY . 大约有270 constraint包含FOREIGN KEY AND UNIQUE KEY 270 constraint I don't want to go for manual option. 我不想手动选择。

Please help me out. 请帮帮我。

ALTER TABLE tbl_name CHECK CONSTRAINT ALL

only re-enables the constraints. 仅重新启用约束。 Importantly, the constraints are not checked against the existing data in the database (nor are they trusted by the optimizer). 重要的是,不会针对数据库中的现有数据检查约束(优化器也不会信任约束)。 If you want that to occur, you need to specify WITH CHECK as well: 如果希望发生这种情况,则还需要指定WITH CHECK

ALTER TABLE tbl_name WITH CHECK CHECK CONSTRAINT ALL

(And yes, the word CHECK appears twice) (是的,单词CHECK出现了两次)

If you execute this, and there are orphaned child rows (or other invalid constraints), then the ALTER TABLE will fail with an error message. 如果执行此操作,并且有孤立的子行(或其他无效约束),则ALTER TABLE将失败并显示一条错误消息。 There's nothing SQL Server can do to fix this issue - it's for you to decide whether to a) remove the orphaned rows, or b) to re-create, in some manner, a suitable parent row for them. SQL Server无法解决此问题-您需要决定是(a)删除孤立的行,还是b)以某种方式为它们重新创建合适的父行。

You can also add the 'ON DELETE CASCADE' code to the end of foreign keys to prevent orphaned child rows from persisting. 您还可以在外键的末尾添加“ ON DELETE CASCADE”代码,以防止孤立的子行持续存在。

This is more of a 'better practice' going forward than a solution, but I believe Damien_The_Unbeliever has answered your main question. 这更多的是“更好的实践”,而不是解决方案,但是我相信Damien_The_Unbeliever回答了您的主要问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM