Does anyone know a query for listing out all foreign keys in a database with "WITH NOCHECK" description applied to it? (removing them will boost performance and stability).
相关问题
- sql execution latency when assign to a variable
- What is the best way to cache a table from a (SQL)
- php PDO::FETCH_ASSOC doesnt detect select after ba
- Bulk update SQL Server C#
- SQL to Parse a Key-Value String
相关文章
- Entity Framework 4.3.1 failing to create (/open) a
- Code for inserting data into SQL Server database u
- Delete Every Alternate Row in SQL
- Linux based PHP install connecting to MsSQL Server
- SQL Azure Reset autoincrement
- How do we alias a Sql Server instance name used in
- Is recursion good in SQL Server?
- how to handle os.system sigkill signal inside pyth
The following code retrieves all foreign keys that are marked 'WITH NOCHECK' and then uses an ALTER statement to fix them up:
The following script will generate the alter statements that will both check existing data and prevent any new violations for foreign keys that are not currently trusted ('with nocheck').
Execute it in SQL Server Management Studio to generate the scripts and then copy them into a query window to execute them.
I know this is an old question with some old answers that have some good info. However, I just wanted to share a script that I have been using to address this problem area in quite a few different databases for us:
This will generate a collection of ALTER statements to fix this "NOCHECK" problem with foreign keys and constraints. This is based on some queries provided by Brent Ozar but tweaked by me for my purposes and ease of use. This could easily be tweaked with a
UNION
to make it a single query.FYI, I have used this exclusively in Azure SQL Database environments. I'm not sure if there are limitations on older versions of SQL Server but it works great in Azure.
The following will return the name of the foreign keys in the current database that are disabled i.e. WITH NOCHECK
For SQL Server 2005/2008:
There was some discussion in the answer about the difference between disabled & not trusted. What's below explains the differnce Here's some code to clarify the difference between is_disabled & isnotrusted.
is_disabled
means the constraint is disabledisnottrusted
means that SQL Server does not trust that the column has been checked against the foreign key table.Thus it cannot be assumed that re-enabling the foreign key constraint will be optimized. To ensure the optimizer trusts the column, it's best to drop the foreign key constraint & re-create it with the
WITH CHECK
option (4.)WITH NOCHECK should only ever be applied to FK's temporarily, or they become useless to the optimiser as your linked article points out. From BOL:
This will identify all your Foreign Keys: (working on the WITH NOCHECK bit...)
Ref.
As an aside, in both SQL Server 2000 and 2005, you can check if any data violates a constraint using: