Tuesday, August 13, 2013

Row Constructor - Multiple Row Inserts Using Single SQL Query

Row constructor feature of SQL Server 2008 help with single query to insert multiple rows

Old Approach
 

insert into Customer(id,name,Age) values (100,'Ricardo',45)
insert into Customer(id,name,Age) values (101,'Michael',42)
insert into Customer(id,name,Age) values (102,'Antony',44)
insert into Customer(id,name,Age) values (103,'Zeus',43)




New Approach
 
 
insert into 
 Customer(id,name,Age)
 values
   (100,'Ricardo',45),
   (101,'Michael',42),
   (102,'Antony',46),
   (101,'Zeus',43)


Tuesday, August 06, 2013

Distinct() LINQ

Distinct() in LINQ is usually used to return Distinct item based on default comparison logic.
  
string[] customer = { "Jeniffer", "Steve", "Anderson", "Evan" };
var distinctCustomerList = from customerList in
customer.Distinct()
select customerList;








 

We need to tell Distinct to ignore the case by following.

 string[] customer = { "Jeniffer", "Steve", "Anderson", "Evan", "EVAN" };

var distinctCustomerList = from customerList in
     customer.Distinct(StringComparer.CurrentCultureIgnoreCase)
     select customerList;



This is pretty straight forward and LINQ uses its default Compare logic to find Distinct.
The default Compare Logic need to be changed when working on custom objects like below

 
public class Customer
{
public string CustomerId { get; set; }
public string FirstName { get; set; }
}

We need to implement IEquatable interface for determining equality of instances.

  
public class Customer : IEquatable
{
public string CustomerId { get; set; }
public string FirstName { get; set; }

public bool Equals(Customer other)
{
//Check whether the compared object is null.
if (Object.ReferenceEquals(other, null)) return false;

//Check whether the compared object references the same data.
if (Object.ReferenceEquals(this, other)) return true;

//Check whether the Customer' properties are equal.
return CustomerId.Equals(other.CustomerId) && FirstName.Equals(other.FirstName);
}

public override int GetHashCode()
{

// Get the hash code for the Textual field if it is not null.
int hashTextual = CustomerId == null ? 0 : CustomerId.GetHashCode();

// Get the hash code for the Digital field.
int hashDigital = FirstName.GetHashCode();

// Calculate the hash code for the object.
return hashDigital ^ hashTextual;
}
}



Finally call the Distinct methods to filter out duplicates

  
var cList = new List();
cList.Add(new Customer { CustomerId = "100", FirstName = "Jeniffer" });
cList.Add(new Customer { CustomerId = "100", FirstName = "Steve" });
cList.Add(new Customer { CustomerId = "102", FirstName = "Anderson" });
cList.Add(new Customer { CustomerId = "103", FirstName = "Evan" });
cList.Add(new Customer { CustomerId = "103", FirstName = "Evan" });
IEnumerable lstCustomer = cList.Distinct();