How to truncate all tables of a given database in SQL Server - sql-server

I have to execure in test environment the truncate of all tables of three different test databases. I need sql query that considers the table constraints because all the codes that I tested on AdventureWorks database are raising the following error:
Cannot TRUNCATE TABLE 'Person.CountryRegion' because it is being referenced by object 'vStateProvinceCountryRegion'

You could try something like:
-- Disable all FK constraints...
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL";
GO
-- TRUNCATE TABLES...
-- Enable all FK constraints...
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL";
GO

Related

Cannot insert duplicate key row in object '[Reporting].[SecurityPrincipal]' due to trigger '[Reporting].[SecurityPrincipal_Insert_UniqueName]

Possible way to resolve Dynamics Ax Management Reporter issue:
Cannot insert duplicate key row in object '[Reporting].[SecurityPrincipal]' due to trigger '[Reporting].[SecurityPrincipal_Insert_UniqueName]
This could help admins with Dynamics Ax environment integrated with Management Reporter.
After successful integrations we had the error "Cannot insert duplicate key row in object '[Reporting].[SecurityPrincipal]' due to trigger '[Reporting].[SecurityPrincipal_Insert_UniqueName]", probably due to pre-existing user records.
Solution(Maybe not the best)
1. Stop Management Reporter service
2.Go to MSSQL server for ManagementReporter database and execute the following;
ALTER TABLE [Reporting].[SecurityPrincipal] NOCHECK CONSTRAINT ALL
ALTER TABLE [Reporting].[ControlColumnMaster] NOCHECK CONSTRAINT ALL
ALTER TABLE [Reporting].[ControlReportScheduleTask] NOCHECK CONSTRAINT ALL
ALTER TABLE [Reporting].[ControlReportContributorSettings] NOCHECK CONSTRAINT ALL
ALTER TABLE [Reporting].[ControlReport] NOCHECK CONSTRAINT ALL
ALTER TABLE [Reporting].[ControlReportGroups] NOCHECK CONSTRAINT ALL
ALTER TABLE [Reporting].[SecurityCompanyPermissionIntegration] NOCHECK CONSTRAINT ALL
ALTER TABLE [Reporting].[ControlRowMaster] NOCHECK CONSTRAINT ALL
ALTER TABLE [Reporting].[ControlTreeMaster] NOCHECK CONSTRAINT ALL
ALTER TABLE [Reporting].[ControlReportSchedule] NOCHECK CONSTRAINT ALL
Delete all domain user records only. Do not delete the user "Everyone" and "Management Reporter"
enter code hereDELETE FROM [ManagementReporter].[Reporting].[SecurityPrincipal] WHERE Name like 'domain%'
Re enable all constraints, start the service and hope for the table to be repopulated.
Hope this helps someone in need as I found no solutions online.

SQL Server - Alter Table FOREIGN KEY Conflict when using EXEC sp_msforeachtable

I am attempting to migrate some data from one database to another using Microsoft SQL Server. Both databases have a "Properties/Locations" type of table that is referenced by a foreign key.
Unfortunately, even though the entities referenced in the two tables are the same, the primary keys are not. As such, in order to migrate the data, I am trying to temporarily disable the foreign key constraint, insert and update the data appropriately, and then re-enable the constraint.
However, I am receiving the following message:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__TwelveCri__Store__114A936A". The conflict occurred in database "API", table "dbo.Properties", column 'ID'.
While, I understand the general reason why the error is being thrown (it is not finding a match between the column StoreID in the Reports table and the ID columns in Properties), I do not understand why it is doing so in this specific case.
BEGIN TRAN
USE API;
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL";
SET IDENTITY_INSERT Midamcorp.TwelveCriticalsReports ON;
INSERT INTO Midamcorp.TwelveCriticalsReports (ID, StoreID, InspectorName, ReportTime, ReportDate, PointsPoss, PointsReceived)
SELECT
id, storeID, inspectorName, reportTIme, reportDate, pointsPoss, pointsReceived
FROM
midAmCorp.dbo.criticalReports;
SET IDENTITY_INSERT Midamcorp.TwelveCriticalsReports OFF;
UPDATE API.Midamcorp.TwelveCriticalsReports
SET StoreID = 1
WHERE StoreID = 4;
!--- MORE UPDATE STATEMENTS HERE ---!
USE API
SET IDENTITY_INSERT Midamcorp.SecretShopperReportSummary ON;
INSERT INTO Midamcorp.SecretShopperReportSummary(ID, StoreID, PointsPoss, PointsReceived, DriveTime, CompletedBy, DateOfVisit)
SELECT
id, storeID, pointsPoss, pointsReceived, driveTime, completedBy, dateOfVisit
FROM
midamCorp.dbo.secretShopperReportSummary;
SET IDENTITY_INSERT Midamcorp.SecretShopperReportSummary OFF;
!--- MORE UPDATE STATEMENTS HERE ---!
USE API
SET IDENTITY_INSERT Midamcorp.SecretShopperReportDetails ON;
INSERT INTO Midamcorp.SecretShopperReportDetails(ID, ReportID, QuestionID)
SELECT
id, reportID, questionID
FROM
midAmCorp.dbo.secretShopperReportDetails;
SET IDENTITY_INSERT Midamcorp.SecretShopperReportDetails OFF;
SELECT *
FROM Midamcorp.TwelveCriticalsReports
WHERE StoreID NOT IN (SELECT StoreID FROM dbo.Properties);
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL";
COMMIT TRAN;
The SELECT statement at near the end returns no results, which is what I would expect if the relationships were properly updated. However, I am still receiving the error message noted above, presumably from the EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL"; statement.
Any advice would be appreciated.

SQLServer Foreign Key Checks Disabled But Still Can't Drop Table

I have a SQLServer database which I want to drop a table from. The table has FK constraints, but in this case it doesn't matter because when I repopulate the table, the FKs will be replaced correctly.
I've done EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all" which gives a message: sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINTS all" succeded, but when I try to drop my table I get the following SQL error: SQL Error: Could not drop object 'myTable' because ti is referenced by a FOREIGN KEY constraint.
Should the command not have affected my entire database and allowed me to drop the table without an issue? I've also tried doing EXEC sp_msforeachtable "ALTER TABLE myTable NOCHECK CONSTRAINT all" which results in the same error.
NOCheck disable the constraints so they won't be enforced. This would allow you to delete the data without violating the constraint.
Dropping the table would make the constraint definition invalid. You can't have a constraint that references a table that doesn't exist. You wouldn't be able to drop the referenced column from the table either while the constraint exists.
If you will be repopulating the table, just delete the table data and reload it. If you absolutely must drop and recreate the table, you'll need to include the drop & create statements for your foreign key constraints as well.
Note that if you disable the constraint, you'll need to enable using WITH CHECK CHECK (yes twice). The first check turns the constraint on for new data, the second tells SQL to validate the existing data. If you only do one, new data will be checked, but the existing data will not be 'TRUSTED', which can affect how SQL will leverage the FK reference in queries.
Should the command not have affected my entire database and allowed me
to drop the table without an issue?
No. It doesn't matter what the NOCHECK state is; if there are FK constraints that reference a target table, that target table cannot be dropped.
The only way to drop the table is to first drop the FK constraints that reference it.

How to drop tables with no constraint checking

I need to update the data and schema from dev to staging dbs where I want to DROP/CREATE a group of tables. I need to over-ride the FK constraint checks. Looking at the MS's ALTER TABLE syntax tree - i know it's there but i can't identify the correct syntax.
#Rup: It looks like the hangup is from other tables' FKs. Is there a way to turn all constraint checking off or do i need to produce the list of tables/FKs?
ALTER TABLE yourtable
NOCHECK CONSTRAINT ALL
and a variation on this theme is to disable all the constraints of all the tables delete all the data, and then add all the constraints back again.
exec sp_MSforeachtable #command1='alter table ? nocheck constraint all', #whereand='and substring(o.name,1,1) <> ''_'''
exec sp_MSforeachtable #command1='delete from ?'
exec sp_MSforeachtable #command1='alter table ? check constraint all', #whereand='and substring(o.name,1,1)<> ''_'''
The nice thing here is that with all the constraints disabled, you can delete the data in any order
You can drop the constraints, drop the tables and re-create. It should also be possible to drop the tables in the correct order and re-create if there are no circular constraints.
ALTER TABLE DROP CONSTRAINT

Clear all the rows in a table resetting the identity specification back to zero and without affecting the foreign keys?

We have already created the database framework, with all the relations and dependencies. But inside the tables were just the dummy data, and we need to get rid of these dummy data, and start adding the correct ones. How can we clear everything and leave the primary keys (IsIdentity: yes) back to zero, and also without affecting the foreign-table relational structure.
Thanks a lot!
You can take the following steps:
-- disable all foreign key constraints
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
-- delete data in all tables
EXEC sp_MSForEachTable "DELETE FROM ?"
-- enable all constraints
exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
More on disabling constraints and triggers here
if some of the tables have identity columns we may want to reseed them
EXEC sp_MSforeachtable "DBCC CHECKIDENT ( '?', RESEED, 0)"
Note that the behaviour of RESEED differs between brand new table, and one which had had some date inserted previously from BOL:
DBCC CHECKIDENT ('table_name', RESEED, newReseedValue)
The current identity value is set to
the newReseedValue. If no rows have
been inserted to the table since it
was created, the first row inserted
after executing DBCC CHECKIDENT will
use newReseedValue as the identity.
Otherwise, the next row inserted will
use newReseedValue + 1. If the value
of newReseedValue is less than the
maximum value in the identity column,
error message 2627 will be generated
on subsequent references to the table.
I'd use TRUNCATE:
-- Truncate table (very fast, and it resets Identity as well)
EXEC sp_MSForEachTable "TRUNCATE TABLE ?"
Of course, disable and re-enable check constraints too, as suggested by kristof.
Reseeding:
DBCC CHECKIDENT (yourtable, reseed, 1)
is for setting the primary key on 1
delete from table should delete the data, but not affect any other things.
Generate Database schema-only sql file using Database publishing wizard and enable the option to drop the tables if exists. Run this script on your database and This will flush everything and give you fresh schema as you need.

Resources