Tuesday, 10 September 2019

SQL Server: Difference between Truncate and Delete and Error: Cannot truncate table 'Table1' because it is being referenced by a FOREIGN KEY constraint.


Delete:

=> Deletes the tables rows.

=>Delete * from table1 = > Deletes all rows in a tables

If you need a conditional deletion, include Where clause in to the DELETE statement.

Delete * from table1 where column1= 'aaaa'



Truncate:

=>Deletes or removes all rows in a table

=> Doesnt need any where clause for Truncate


Error:
Cannot truncate table 'Table1' because it is being referenced by a FOREIGN KEY constraint.

Note:
When a table has a foreign key relationship, 1st we always we need to delete rows from child table and then parent table.
 Even child table doesnt have any rows, if we use Truncate table it will still give you the above error.

As an alternative, try Delete from Table in that cases

No comments:

Post a Comment

VBScript: How to use Dictionary in VBScript | VBScript objects

=>To declare and create object of a vbscript dictionary: Dim objDictionary Set objDictionary = CreateObject("Scripting.Dictionar...