Let’s assume you have a database messing around with sample data and want an easy and fast way to delete all data.
What you can use:
sp_MSforeachtable: Stored Procedure to perform same actions for all tables in the specified database
DELETE: Removes rows from a table or view. More here
TRUNCATE TABLE name: Identical to DELETE statement with no Where clause. Both removes all rows in a table but TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.
Have in Mind
You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint, so instead, use DELETE statement without a WHERE clause. The reason is that
TRUNCATE TABLE is not logged and it cannot activate a trigger.
-- Disable Referential Integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO
EXEC sp_MSForEachTable 'IF OBJECTPROPERTY(object_id(''?''), ''TableHasForeignRef'') = 1 DELETE FROM ? else TRUNCATE TABLE ? '
GO
-- Enable Referential Integrity Again
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
GO
What confuses sometimes is the use of virtual keyword, so let’s keep some notes in order to remember it.
Definition
The virtual keyword is used to modify a method or property declaration, in which case the method or the property is called a virtual member. The implementation of a virtual member can be changed by an overriding member in a derived class.
Have in mind
You cannot use the virtual modifier with the following modifiers: static, abstract, override.
How to use it
A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
When to use it
When you want to support polymorphism. When objects derive from a common class, having some common behavior but there are some small differences at the implementation of each object’s behavior.
Examples
using System;
class TestVirtual
{
public class Shape
{
public const double pi = Math.PI;
protected double x, y;
public Shape() { }
public Shape (double x, double y)
{
this.x = x;
this.y = y;
}
//This method can be overriden
public virtual double Area()
{
return x*y;
}
}
public class Circle: Shape
{
public Circle(double r): base(r, 0)
{
}
// This method is being overriden
public override double Area()
{
return pi * x * x;
}
}
public class Rectangle: Shape
{
public Rectangle(double x, double y): base(x, y){}
}
public static void Main()
{
double r = 3.0, h = 5.0;
Shape c = new Circle(r);
Shape s = new Rectangle(r, h);
// Display results:
Console.WriteLine("Area of Circle = {0:F2}", c.Area());
Console.WriteLine("Area of Rectangle = {0:F2}", s.Area());
}
}
Results
Area of Circle: 28.27
Area of Rectangle: 15