Wednesday, August 20, 2014

Difference between CTE and Temp Table and Table Variable

Temp Table or Table variable or CTE are commonly used for storing data temporarily in SQL Server. In this article, you will learn the differences among these three.

CTE

CTE stands for Common Table expressions. It was introduced with SQL Server 2005. It is a temporary result set and typically it may be a result of complex sub-query. Unlike temporary table its life is limited to the current query. It is defined by using WITH statement. CTE improves readability and ease in maintenance of complex queries and sub-queries. Always begin CTE with semicolon.

A sub query without CTE is given below :

SELECT * FROM (

SELECT Addr.Address, Emp.Name, Emp.Age From Address Addr

Inner join Employee Emp on Emp.EID = Addr.EID) Temp

WHERE Temp.Age > 50

ORDER BY Temp.NAME


By using CTE above query can be re-written as follows :

  1. ;With CTE1(Address, Name, Age)--Column names for CTE, which are optional
  2. AS
  3. (
  4. SELECT Addr.Address, Emp.Name, Emp.Age from Address Addr
  5. INNER JOIN EMP Emp ON Emp.EID = Addr.EID
  6. )
  7. SELECT * FROM CTE1 --Using CTE
  8. WHERE CTE1.Age > 50
  9. ORDER BY CTE1.NAME

When to use CTE

  1. This is used to store result of a complex sub query for further use.
  2. This is also used to create a recursive query.

Temporary Tables

In SQL Server, temporary tables are created at run-time and you can do all the operations which you can do on a normal table. These tables are created inside Tempdb database. Based on the scope and behavior temporary tables are of two types as given below-
  1. Local Temp Table

    Local temp tables are only available to the SQL Server session or connection (means single user) that created the tables. These are automatically deleted when the session that created the tables has been closed. Local temporary table name is stared with single hash ("#") sign.                  CREATE TABLE #LocalTemp( UserID int,Name varchar(50), Address varchar(150)) GO insert into #LocalTemp values ( 1, 'Shailendra','Noida'); GO Select * from #LocalTemp
    The scope of Local temp table exist to the current session of current user means to the current query window. If you will close the current query window or open a new query window and will try to find above created temp table, it will give you the error.
  2. Global Temp Table

    Global temp tables are available to all SQL Server sessions or connections (means all the user). These can be created by any SQL Server connection user and these are automatically deleted when all the SQL Server connections have been closed. Global temporary table name is stared with double hash ("##") sign.                                                                                                                      CREATE TABLE ##GlobalTemp( UserID int, Name varchar(50), Address varchar(150)) GO insert into ##GlobalTemp values ( 1, 'Shailendra','Noida'); GO Select * from ##GlobalTemp
    Global temporary tables are visible to all SQL Server connections while Local temporary tables are visible to only current SQL Server connection.

Table Variable

This acts like a variable and exists for a particular batch of query execution. It gets dropped once it comes out of batch. This is also created in the Tempdb database but not the memory. This also allows you to create primary key, identity at the time of Table variable declaration but not non-clustered index.             GO
DECLARE @TProduct TABLE
(
SNo INT IDENTITY(1,1), ProductID INT,
Qty INT
) 
--Insert data to Table variable @Product 
INSERT INTO @TProduct(ProductID,Qty)
SELECT DISTINCT ProductID, Qty FROM ProductsSales ORDER BY ProductID ASC 
--Select data
Select * from @TProduct
--Next batch
GO
Select * from @TProduct --gives error in next batch

Note

Temp Tables are physically created in the Tempdb database. These tables act as the normal table and also can have constraints, index like normal tables.

CTE is a named temporary result set which is used to manipulate the complex sub-queries data. This exists for the scope of statement. This is created in memory rather than Tempdb database. You cannot create any index on CTE.

Table Variable acts like a variable and exists for a particular batch of query execution. It gets dropped once it comes out of batch. This is also created in the Tempdb database but not the memory.

Wednesday, August 13, 2014

getting nth highest salary in sqlserver 2008

SELECT * FROm tbl_Employee
order by Salary




declare @N int
set @N=5

SELECT *
FROM tbl_Employee Emp1
WHERE (@N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM tbl_Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)

Monday, July 14, 2014

Method Hiding in C#

Introduction

Method hiding in C# is similar to the function overriding feature in C++. Functions of the base class are available to the derived class. If the derived class is not happy, one of the functions available to it from the base class can define its own version of the same function with the same function signature, just differing in implementation. This new definition hides the base class definition. Take the following program for example.

P1.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{

}

class Demo
{
  public static void Main()
  {
     DC obj = new DC();
     obj.Display();
  }
}

Output

BC::Display
The above program compiles and runs successfully to give the desired output. The above program consists of a base class BC which consists of a public function named Display(). Class DC is derived from BC. So Display() of BC is Inherited by Class DC. It's as if DC has a function called Display(). Class Demo has the entry point function Main(). Inside Main we create an object obj of class DC and invoke the function Display(). What is called is the Display ofBC because its inherited by the derived class DC.
For some unknown reason the derived class was not happy with the implementation of the Display() function that it had inherited from its Base class BC. So the derived class made a bold decision to define its own version of the functionDisplay(). Thus, you could see code for Display() function in class BC as well as in class DC.

P2.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     DC obj = new DC();
     obj.Display();
  }
}

Output

DC::Display
On compilation the above program threw a warning which said
P2.cs(11,15): warning CS0108: 'DC.Display()' hides inherited member 
'BC.Display()'. Use the new keyword if hiding was intended. P2.cs(3,15): 
(Location of symbol related to previous warning)
The compiler warns us about Display() of DC forcibly hiding Display() of BC. The compiler smells something dicy and requests us to use the new keyword if the hiding was intentional.
The above program compiles to produce an executable. We run the executable to get the desired output as shown above. The Display() of derived class DC is invoked as it hides the Display() of base class BC. But an executable with warnings is like a neatly dressed man with unpolished shoes. We need to remove the warning. We need to tell the compiler that the implementation of Display() in derived class was intentional. We do this by using the modifier new as shown in the program below.

P3.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     DC obj = new DC();
     obj.Display();
  }
}

Output

DC::Display
The addition of the modifier new to the function Display() in Derived class informs the compiler that the implementation of Display() in Derived class was intentional, thus stopping the compiler from throwing any warnings at us. Can you tell what the output of the above program will be?

P4.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class TC : DC
{

}

class Demo
{
  public static void Main()
  {
     TC obj = new TC();
     obj.Display();
  }
}

Output

DC::Display
The above program compiles and runs successfully to give the desired output. Class TC is derived from DC. SoDisplay() of DC is Inherited by Class TC. It's as if TC has a function called Display(). Class Demo has the entry point function Main(). Inside Main we create an object obj of class TC and invoke the function Display(). What gets called is the Display of DC because its inheritted by the derived class TC. Now what if we were to define and invoke classTC's own version of Display() ? Simple! We would have to define a function Display inside class TC with a new modifier as follows.

P5.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class TC : DC
{
  new public void Display()
  {
     System.Console.WriteLine("TC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     TC obj = new TC();
     obj.Display();
  }
}

Output

TC::Display
The above program comples and runs successfully to give the desired output.

Polymorphism, Method Hiding and Overriding in C#


Overview
One of the fundamental concepts of object oriented software development is polymorphism. The term polymorphism (from the Greek meaning "having multiple forms") in OO is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow a variable to refer to more than one type of object.
Example Class Hierarchy
Let's assume the following simple class hierarchy with classes A, B and C for the discussions in this text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the easier examples, we will only refer to a part of this class hierarchy.
Inherited Methods
A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses
    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A {}

        class Test
        {
            static void Main(string[] args)
            {
                A a = new A();
                a.Foo();  // output --> "A::Foo()"

                B b = new B();
                b.Foo();  // output --> "A::Foo()"
            }
        }
    }
     
The method Foo() can be overridden in classes B and C:
    using System;
    namespace Polymorphism
    {
        class A
        {
              public void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A
        {
              public void Foo() { Console.WriteLine("B::Foo()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"

                a = new B();
                a.Foo();  // output --> "A::Foo()"
            }
        }
    }
     
There are two problems with this code.
  • The output is not really what we, say from Java, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual. An example using virtual methods and polymorphism will be given in the next section.
  • Although the code compiles and runs, the compiler produces a warning:
...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'
This issue will be discussed in section Hiding and Overriding Methods.
Virtual and Overridden Methods
Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.
    using System;
    namespace Polymorphism
    {
        class A
        {
            public virtual void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A
        {
            public override void Foo() { Console.WriteLine("B::Foo()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"

                a = new B();
                a.Foo();  // output --> "B::Foo()"
            }
        }
     }
Method Hiding
Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:
    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A
        {
            public new void Foo() { Console.WriteLine("B::Foo()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"

                a = new B();
                a.Foo();  // output --> "A::Foo()"
            }
        }
    }
Combining Method Overriding and Hiding
Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
            class A
            {
                public void Foo() {}
            }

            class B : A
            {
                public virtual new void Foo() {}
            }
     
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
            class C : B
            {
                public override void Foo() {}
                // or
                public new void Foo() {}
            }
Conclusion
  • C# is not Java.
  • Only methods in base classes need not override or hide derived methods. All methods in derived classes require to be either defined as new or as override.
  • Know what your doing and look out for compiler warnings.

Thursday, July 10, 2014

ActionResult Return Type in MVC 3.0

Introduction

An ActionResult is a return type of a controller method in MVC. Action methods help us to return models to views, file streams, and also redirect to another controller's Action method. 

There are many derived ActionResult types in MVC that you may use to return the results of a controller method; these are more specific for a particular view. All Action Result Classes are derived from "ActionResult". In other words ActionResult is an abstract class that has several subtypes.

ViewResult

It renders a specified view to the response stream. The "ViewResult" class inherits from the abstract class "ViewResultBase" and is used to render a view. This class contains methods for finding the view to render and also for executing the result. This class also contains properties that identify the view (view Name) to render for the application.
public ViewResult ViewResultTest()
{
    return View("ViewResultTest");
}

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.view.aspx

PartialViewResult

The PartialViewResult class is inherited from the abstract "ViewResultBase" class and is used to render a partial view. This class contains methods for finding the partial view to render and also for executing the result. This class also contains properties that identify the partial view (View Name) to render for the application. PartialViews are not common as action results. PartialViews are not the primary thing being displayed to the user, which is the View. The partial view is usually a widget or something else on the page.
public PartialViewResult PartialViewResultTest()
{
    return PartialView("PartialViewResult");
}


RedirectResult

It is used to perform an HTTP redirect to a given URL. This class is inherited from the "ActionResult" abstract class.
public ActionResult RedirectResultTest()
{
    return Redirect("http://www.google.com/");
} 
public RedirectResult RedirectResultTest()
{
    return Redirect("http://www.google.com/");
}

http://msdn.microsoft.com/en-us/library/system.web.mvc.redirectresult.aspx
RedirectToRouteResult

RedirectToResult is used to redirect by using the specified route values dictionary. This class is inherited from the "ActionResult" abstract class.
public ActionResult RedirectToRouteResultTest(int? Id)
{
    return new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { controller = "Home", action = "List", Id = new int?() }));
}

http://msdn.microsoft.com/en-us/library/system.web.mvc.redirecttorouteresult.aspx

ContentResult

The ContentResult may be used to return to an action as plain text. This class is inherited from the "ActionResult" abstract class. 
public ActionResult ContentResultTest()
{
    return Content("Hello My Friend!");
} 
public ContentResult ContentResultTest()
{
    return Content("Hello My Friend!");
}

JsonResult

Action methods on controllers return JsonResult (JavaScript Object Notation result) that can be used in an AJAX application. This class is inherited from the "ActionResult" abstract class. Here Json is provided one argument which must be serializable. The JSON result object that serializes the specified object to JSON format.
public JsonResult JsonResultTest()
{
    return Json("Hello My Friend!");
}

http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonresult(v=vs.98).aspx