Hi @Lylyy
TRUNCATE TABLE is a DDL command, it cannot check to see whether the records in the table are being referenced by a record in the child table.
Therefore, you need DELETE here, because the database is able to make sure that it isn't being referenced by another record.
How to delete all the data of a database while keep the table structure?
Solution 1:
Execute this script
SELECT 'DELETE ' + quotename(S.name) + '.' + quotename(T.name) + char(13) + char(10) + 'GO' + char(13) + char(10)
FROM sys.tables T JOIN sys.schemas S ON T.schema_id = S.schema_id
Then copy the query result to a new query window and execute(F5) until no error message received.
Solution 2:
- Create a table variable to store the constraint drop and creation scripts for the database.
- Load the data for all tables in the database.
- Execute a cursor to drop all constraints.
- Truncate all tables.
- Recreate all the constraints.
Please refer to this article for detailed scripts.
Best regards,
Cosmog Hong