Tuesday, April 5, 2022

What is Recursion in Programming

Recursion is calling a function itself multiple times to solve a given problem. Just like loops, you also need to specify when that function should stop calling itself. Such a condition is called as the base condition. 

For example, consider the below code which prints "Hello World" repeatedly. The showMessage function calls itself multiple times but the base condition is not defined and hence, this leads to an infinite loop.
function showMessage(n) {
    console.log("Hello world ", n);
    showMessage(n - 1);
}

showMessage(10);

Now, observe the code after adding the base condition. When n becomes 0, the recursive call stops.
function showMessage(n){
    if(n==0){
        return;
    }
    console.log("Hello world ",n);
    showMessage(n-1);
}

showMessage(10);
Let us see how to use recursion to perform some calculations. The below code calculates the sum of first n numbers.
function sum(n){
    if(n==1){
        return 1
    }
    else{
        return n+sum(n-1);
    }
}

var sumResult=sum(10);
console.log(sumResult);

Every recursion can be replaced with an equivalent iteration statement. Recursive algorithms are usually slower than iterative algorithms. In the above example which calculates the sum of first n numbers. Here, the sum of first 10 numbers is checked. If you want the sum of first 600000 numbers, the recursive code will crash. Interestingly, the below iterative algorithm to calculate the sum of n numbers has the same complexity, O(n).
function sum(n){
    var sum=0;
    while(n!=0){
        sum+=n;
        n--;
    }
    return sum;
}

var sumResult=sum(600000);
console.log(sumResult);

But the below equivalent code has a time complexity of O(1).
function sum(n){
    return n*(n+1)/2;
}

However, recursive algorithms have below advantages: 
  • Recursion adds clarity and sometimes reduces the time needed to write and debug code. 
  • Performs better in solving problems based on tree structures.

Sunday, June 27, 2021

Sample CSharp (C#) Program to Insert DataSet values Into SQL Server Database

Using this sample program you can insert multiple table data from DataSet to SQL Server database. The Insert query will be generated automatically based on the columns in the DataSet Tables. This sample also has transaction and exception handling implemented.

Here data loaded from xml.

As I implemented transaction, Data will be saved to Database only when all table inserted successfuly. If insertion failes inbetween data will be rollbacked.

C# Code:
static void Main(string[] args)
{
    var connectionString = "SQLSERVER_DATABSE_CONNECTIONSTRING_HERE";

    DataSet ds = new DataSet();
    ds.ReadXml("data.xml");

    using (var con = new SqlConnection(connectionString))
    using (var cmd = new SqlCommand())
    {
        con.Open();
        SqlTransaction transaction;
        transaction = con.BeginTransaction("SampleTransaction");
        cmd.Transaction = transaction;
        string tableName = string.Empty;

        try
        {
            foreach (DataTable table in ds.Tables)
            {
                string columns = string.Join(",", table.Columns.Cast().Select(c => c.ColumnName));
                string values = string.Join(",", table.Columns.Cast().Select(c => string.Format("@{0}", c.ColumnName)));
                tableName = table.TableName;

                string sqlCommandInsert = string.Format("INSERT INTO dbo.{0}({1}) VALUES ({2});", tableName, columns, values);

                cmd.CommandText = sqlCommandInsert;
                cmd.Connection = con;

                foreach (DataRow row in table.Rows)
                {
                    cmd.Parameters.Clear();
                    foreach (DataColumn col in table.Columns)
                        cmd.Parameters.AddWithValue("@" + col.ColumnName, row[col]);
                    var inserted = cmd.ExecuteNonQuery();
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(tableName);
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);

            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                Console.WriteLine(ex2.Message);
                Console.WriteLine(ex2.StackTrace);
            }
        }
    }

    Console.ReadLine();
}

Query to generate Single XML from multiple tables in SQL Server

Here is the sample code to generate a single xml from multiple table query in Sql Server. In this example I am querying data from two tables.

Sample Query :
SELECT
    (SELECT * FROM dbo.TableA FOR XML PATH('TableA'), TYPE),
    (SELECT * FROM dbo.TableB FOR XML PATH('TableB'), TYPE)
FOR XML PATH(''), ROOT('root')

XML Output :
<root>
   <TableA>
	 <Column1>Value1</Column1>
    	 <Column2>Value2</Column2>
   </TableA>
   <TableB>
	 <Column1>Value1</Column1>
    	 <Column2>Value2</Column2>
   </TableB>
</root>

You can load this Xml into DataSet using below C# code.
DataSet ds = new DataSet();
ds.ReadXml("queryResult.xml");