Thursday, January 23, 2014

Sunday, January 5, 2014

SQL - Select Distinct for Only One Column

PARTITION is used to select distinct value from only one column.
For example,
 
SELECT ID, ProductModel, ProductName FROM Products
where I want non-duplicate values of productName.

This code does the above problem

 
SELECT *
FROM (
    SELECT  ID, ProductName, ProductModel,
            ROW_NUMBER() OVER(PARTITION BY ProductName ORDER BY ID DESC) rn
    FROM Products
) a
WHERE rn = 1

Thursday, January 2, 2014

Jquery - Chosen

Chosen makes <select> much more user friendly but it doesn't works on Server side. Thus, hidden field is needed to pass selected value(s) to server side.

    $('#hiddenFields').val($('#select').val())


C# - Transactions

There are 2 main types of transaction; Connection transactions and Ambient transactions. Connection transaction is tied to one SqlConnection. Ambient transaction allows multiple SqlConnections.

Connection transaction
using (SqlConnection conn = new SqlConnection(_connStr))
    {
        conn.Open();
        SqlTransaction trans = conn.BeginTransaction();
        try{
            using (SqlCommand cmd = new SqlCommand(, conn, trans))
            {
                //sql work here
                trans.Commit(); 
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            try
            {
                trans.Rollback();
            }
            catch (Exception exRollback)
            {
                // Throws an InvalidOperationException if the connection is closed or the transaction has already been rolled back on the server.
                Console.WriteLine(exRollback.Message);
            }
        }
}
Ambient transaction
    try
    {
        using (TransactionScope scope = new TransactionScope())
        {
            //some methods here
            scope.Complete();
        }
    }
    catch (TransactionAbortedException ex)
    {
        writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
    }


  • http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope(v=vs.100).aspx