Wednesday, October 20, 2010

Read XML in SQL Server 2005/2008

Can read an xml file format in SQL Server 2005 2005/2008

To read the attributes use "@AttributeName"

To read the node under it use "NodeName[0]"

Just copy/patse the below given stuff in sql server and run it.


--//---------- Declare ----------//
DECLARE @xmlTest XML
SET @xmlTest = '<GUIDs>
<GUID Temp="a">1</GUID>
<GUID Temp="a">2</GUID>
<GUID Temp="a">3</GUID>
<GUID Temp="b">4</GUID>
<GUID Temp="b">5</GUID>
</GUIDs>'


--//---------- Set Query ----------//
SELECT Temp , MAX(GUID) FROM (
SELECT xmlTest.value('.', 'INT') AS GUID , xmlTest.value('@Temp', 'VARCHAR(36)') AS Temp
FROM @xmlTest.nodes('/GUIDs/GUID') d(xmlTest) ) AS A
GROUP BY Temp

Wednesday, August 18, 2010

Apply group by clause on Datatable in C#

The blog will explain how to retrieve a data table using C# using a group by clause.
//The way to call the Group By Function
//Argument 1 = Data table in IMAGE 1
//Argument 2 = The fields you want for the data table returned
//Argument 3 = The field you want to group by
//Argument 4 = The function you want to do It can be either SUM, COUNT, AVG etc.
DataTable dtGroupedBy = GetGroupedBy(dt, "CodeName,Quantity,Current", "CodeName", "Sum");
/// <summary>
/// The group by clause for Data Table
/// </summary>
/// <param name="dt">The main data table to be filtered with the Group By.</param>
/// <param name="columnNamesInDt">The Fields sent seperated by commas. EG "Field1,Field2,Field3"</param>
/// <param name="groupByColumnNames">The column name which should be used for group by.</param>
/// <param name="typeOfCalculation">The calculation type like Sum, Avg Or Count.</param>
/// <returns></returns>
private DataTable GetGroupedBy(DataTable dt, string columnNamesInDt, string groupByColumnNames, string typeOfCalculation)
{
    //Return its own if the column names are empty
    if (columnNamesInDt == string.Empty || groupByColumnNames == string.Empty)
    {
        return dt;
    }

    //Once the columns are added find the distinct rows and group it bu the numbet
    DataTable _dt = dt.DefaultView.ToTable(true, groupByColumnNames);

    //The column names in data table
    string[] _columnNamesInDt = columnNamesInDt.Split(',');

    for (int i = 0; i < _columnNamesInDt.Length; i = i + 1)
    {
        if (_columnNamesInDt[i] != groupByColumnNames)
        {
            _dt.Columns.Add(_columnNamesInDt[i]);
        }
    }


    //Gets the collection and send it back
    for (int i = 0; i < _dt.Rows.Count; i = i + 1)
    {
        for (int j = 0; j < _columnNamesInDt.Length; j = j + 1)
        {
            if (_columnNamesInDt[j] != groupByColumnNames)
            {
                _dt.Rows[i][j] = dt.Compute(typeOfCalculation + "(" + _columnNamesInDt[j] + ")", groupByColumnNames + " = '" + _dt.Rows[i][groupByColumnNames].ToString() + "'");
            }
        }
    }

    return _dt;
}


Screen shots to show the achievements


Image 1 :

Image 2 :

Related Blog

Apply "Multiple" column Group By on DataTable in C#

Wednesday, August 4, 2010

SQL 2005/2008 Query to retrieve a comma seperated single row from a table.

SQL 2005/2008 Query to retrieve a comma seperated single row from a table.




This query will help to combine all records in a single row result with comma seperation. I have taken both type string as well as integers.



-- Take a table variable
DECLARE @TBL as TABLE(VAL1 INT, VAL2 VARCHAR(10));
-- POPULATE THE VALUES
INSERT INTO @TBL VALUES(10,'A');
INSERT INTO @TBL VALUES(20,'B');
INSERT INTO @TBL VALUES(30,'C');
INSERT INTO @TBL VALUES(40,'D');
INSERT INTO @TBL VALUES(50,'E');
-- Show the values in tables
SELECT * FROM @TBL;

-- Declare variables
DECLARE @CommaValsInt AS VARCHAR(MAX);
DECLARE @CommaValsString AS VARCHAR(MAX);

-- Gets the sql query with Comma Seperated
SELECT
@CommaValsInt = COALESCE(@CommaValsInt + ',', '') + CAST(VAL1 AS VARCHAR(10))
, @CommaValsString = COALESCE(@CommaValsString + ''',''', '''') + VAL2
FROM
@TBL;
-- Show the result
SELECT @CommaValsInt AS ResultForInt , (@CommaValsString + '''') ResultForString

Saturday, July 17, 2010

Calculate Standard Deviation Using SQL Server

SQL Procedure to get the Standard Deviation



Hello everyone, here is the formaula to calculate the standard deviation.




-- Create a temp table insert some rows as raw data.
DECLARE @tbl AS TABLE(ID INT IDENTITY(1,1) , Val DECIMAL(18,4));
INSERT INTO @tbl VALUES (10.20 );
INSERT INTO @tbl VALUES (99.27 );
INSERT INTO @tbl VALUES (23.56 );
INSERT INTO @tbl VALUES (56.92 );
INSERT INTO @tbl VALUES (02.37 );
SELECT * FROM @tbl;

-- Declare variables @AVG , @Count.
-- @AVG is the average of the "Val".
-- @Count is the number of records in the table.
DECLARE @AVG DECIMAL(18,4), @Count INT;
SELECT @AVG = AVG(VAL) , @Count = COUNT(ID) FROM @tbl;
SELECT @AVG AS Average , @Count AS RecordCount;

-- Declare the sum of Deviation
-- FORMULA = Single value is substracted by the average. The square of the result and sum of all the values will get "@SumDev".
DECLARE @SumDev DECIMAL(18,4);
SELECT @SumDev = SUM( SQUARE(VAL - @AVG) ) AS SumSquareDeviation FROM @tbl;
SELECT @SumDev;

-- Get the final stanard Deviation
-- FORMULA = Gets the last @SumDev divide it by a number less than the total number of rows(@Count - 1). Get the quareroot and get the Standard Deviation
SELECT SQRT((@SumDev /(@Count-1))) AS StandardDeviation;


Thursday, July 8, 2010

Moving and Re-Ordering List Items within listboxes using jquery

ASPX Html





<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MoveItemsFromOneListBoxToAnother.aspx.cs" Inherits="MoveItemsFromOneListBoxToAnother" EnableEventValidation="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style>
body{font-size:13px; font-family:Verdana;}
</style>
<script language="javascript" type="text/javascript" src="JS/JQuery.js"></script>
<script language="javascript" type="text/javascript">

//On Ready
$(document).ready(function() {

//Selects the option on the postback event
SetTheDefaultSelected();

//Double click settings for the LIST items
$("select[name*='lstNonSelected']").dblclick(function() {
MoveToSelection();
});
$("select[name*='lstSelected']").dblclick(function() {
MoveFromSelection();
});

});

//Move to Selection box
function MoveToSelection() {

MoveTheOptions($("select[name*='lstNonSelected']").attr("id"), $("select[name*='lstSelected']").attr("id"));
}

//Move from Selection box
function MoveFromSelection() {
MoveTheOptions($("select[name*='lstSelected']").attr("id"), $("select[name*='lstNonSelected']").attr("id"));
}

//Swap the values
function MoveTheOptions(listBox1, listBox2) {
//Check if the list box is having any options selected
if ($("#" + listBox1 + " option:selected").val() == null) {
alert("Please select an option.");
return;
}

//Get iteself to an array
var arr = $("#" + listBox1 + " option:selected").map(function() { return "<option value='" + $(this).val() + "'>" + $(this).text() + "</option>"; });

//Insert a new option(s)
$("#" + listBox2 + "").append($.makeArray(arr).join(""));

//Remove the first list box
$("#" + listBox1 + " option:selected").remove();

//Refills the paycodes
RefillHiddenTextBox();
}

//Refills the txt pay codes
function RefillHiddenTextBox() {
//Refill the screen
var txt = $("select[name*='lstSelected'] option").map(function() { return this.value }).get().join(",");

//Sets the values to the textbox
$("input[name*='txtSelected']").val(txt);
}

//Set The Default Selected
function SetTheDefaultSelected() {
//Select Pay Codes
if ($("input[name*='txtSelected']").val() != "") {
//On the basis of value select the options
var txt = $("input[name*='txtSelected']").val().split(',');
//On the basis of value select the options
for (var i = 0; i < txt.length; i = i + 1) {
//Get the values
var val = $("select[name*='lstNonSelected'] option:[value='" + txt[i] + "']").val();
var text = $("select[name*='lstNonSelected'] option:[value='" + txt[i] + "']").text();

//Insert a new option
$("select[name*='lstSelected']").append("<option value='" + val + "'>" + text + "</option>");
//Remove the first list box
$("select[name*='lstNonSelected'] option:[value='" + txt[i] + "']").remove();
}
}
}

//Moves the options up or down using the buttons on the right hand side of the Selected List
function MoveUpOrDown(isUp)
{
var listbox = $("select[name*='lstSelected']");
if ($(listbox).find("option:selected").length == 0) {
alert("You need to select atleast one selection.");
}
else if ($(listbox).find("option:selected").length > 1) {
alert("You can only select one option to move Up or Down.");
}
else {
//Get the values
var val = $(listbox).find("option:selected").val();
var text = $(listbox).find("option:selected").text();
var index = $(listbox).find("option:selected").index();

//Get the length now
var length = $(listbox).find("option").length;

//Move it up or down
if (isUp == true) {
//Move the option a row above
index = (index == 0 ? index : index - 1);
//Insert the options
$("<option value='" + val + "'>" + text + "</option>").insertBefore($(listbox).find("option:eq(" + index + ")"));
}
else // Down
{
//Move the option a row down
index = (index == length - 1 ? index : index + 1);

$("<option value='" + val + "'>" + text + "</option>").insertAfter($(listbox).find("option:eq(" + index + ")"));
}

//Remove the options
$(listbox).find("option:selected").remove();
//Set the value as selected
$(listbox).val(val);

//Refill the textbox
RefillHiddenTextBox();
}
}

</script>
</head>
<body>
<form id="form1" runat="server">
<h1>Moving and Re-Ordering List Items within listboxes</h1>
<table cellspacing="5">
<tr>
<td colspan="4" align="center" style="color:Red"><asp:Literal ID="ltrlViewOption" runat="server" /></td>
</tr>
<tr>
<td><i><b>Non Selected Items</b></i></td>
<td>&nbsp;</td>
<td><i><b>Selected Items</b></i></td>
<td>&nbsp;</td>
</tr>
<tr>
<td><asp:ListBox ID="lstNonSelected" runat="server" Rows="10" CssClass="form" Width="250px" SelectionMode="Multiple" /></td>
<td>
<input type="button" class="button" value=">" onclick="MoveToSelection();" /><br /><br /><input type="button" class="button" value="<" onclick="MoveFromSelection();" />
</td>
<td><asp:ListBox ID="lstSelected" runat="server" Rows="10" CssClass="form" Width="250px" SelectionMode="Multiple" /></td>
<td>
<input type="button" class="button" value="Up" onclick="MoveUpOrDown(true) ;" style="width:50px" /><br /><br /><input type="button" class="button" value="Down" onclick="MoveUpOrDown(false) ;" style="width:50px" />
</td>
</tr>
<tr>
<td colspan="4" align="center"><asp:TextBox ID="txtSelected" runat="server" /><asp:Button ID="btnView" runat="server" Text="View Selected Options On Server Side" /></td>
</tr>
</table>
</form>
</body>
</html>



C# Code behind





using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MoveItemsFromOneListBoxToAnother : System.Web.UI.Page
{
//The list of data to be bound to the list
private IList<BindListClass> BindList
{
get
{
IList<BindListClass> obj = new List<BindListClass>();
obj.Add(new BindListClass() { Id = 1, Name = "James Bond" });
obj.Add(new BindListClass() { Id = 2, Name = "Bruce Wayne" });
obj.Add(new BindListClass() { Id = 3, Name = "Peter Parker" });
obj.Add(new BindListClass() { Id = 4, Name = "Tonk Stark" });
obj.Add(new BindListClass() { Id = 5, Name = "Ethen Hunt" });
return obj;
}
}

protected void Page_Load(object sender, EventArgs e)
{
//Hide the selected option
txtSelected.Style.Add("display", "none");

if (!IsPostBack)
{
//Bind the non selected list
lstNonSelected.DataSource = BindList;
lstNonSelected.DataTextField = "Name";
lstNonSelected.DataValueField = "ID";
lstNonSelected.DataBind();
}
else
{
//Show the selected values on the postback of the screen
ltrlViewOption.Text = "\""+ txtSelected.Text +"\" are the selected options after postback.";
}
}
}

public class BindListClass
{
public int Id { get; set; }

public string Name { get; set; }
}



Snapshot of Screen






Important Features





  • Can move the items from one listbox to another using buttons with text "<"
    and ">".

  • On double clicking will work on the listitems.

  • "Up" and "Down" buttons on the right of the Selected list will reorder the liteitems.

  • "View Selected Options On Server Side" will show the items selected on the server side.