Tag Archive nocheck

Byphunsanit

constraint check / nocheck

บางครั้งการที่ต้องใส่ข้อมูลลง sql server ครั้งละเยอะๆ หรือเป็น data ที่ export มาจากโครงสร้างเดิม อาจจะมีปัญหากับการตรวจสอบ constraint อย่างน้อยถ้า import ใส่ข้อมูลไปเยอะๆ มันก็ต้องใช้เวลาตรวจสอบข้อมูล ทำให้ช้าบ้างละ วิธีแก้คือปิดไปก่อน แล้วค่อยเปิดมันมาใหม่

query ตัวนี้เป็นตัวที่จะ generate sql ออกมาแก้เล็กน้อยตรง check หรือ nocheck และ is_not_trusted ก็จะใช้ได้ทั้งการปิดและเปิด constraint

​select
'alter table ' + quotename(s.name) + '.' + quotename(t.name) + ' with check check constraint ' + fk.name +';'
from
sys.foreign_keys fk
inner join
sys.tables t
on
fk.parent_object_id = t.object_id
inner join
sys.schemas s
on
t.schema_id = s.schema_id
where
fk.is_not_trusted = 1

หลังจาก execute​ แล้วยังไม่มีผลครับต้อง copy ผลลัพธ์ใน Results ที่จะออกมาประมาณ

alter table [dbo].[areas_cities_lang] with check check constraint FK_areas_amphur_lang_areas_amphur;
alter table [dbo].[areas_countries_lang] with check check constraint FK_areas_countrys_lang_areas_countrys;
alter table [dbo].[areas_geography_lang] with check check constraint FK_areas_geography_lang_areas_geography;
alter table [dbo].[areas_provinces] with check check constraint FK_areas_province_areas_geography;
alter table [dbo].[areas_provinces_lang] with check check constraint FK_areas_province_lang_areas_province;

ไป execute อีกครั้งหนึ่ง บางตารางมันไม่ยอม ต้องไปแก้ทีละตาราง แต่ยังไงก็เร็วกว่ามาเขียน query เองแน่นอน

ขอบคุณ Cr.Scott Munro สำรับคำตอบใน How to list out all Foreign Keys with “WITH NOCHECK” in SQL Server