Pages

2 Sept 2013

Manipulating and Accessing CSS Class Names in Jquery

jQuery allows you to easily add, remove, and toggle CSS classes, which comes in handy for a variety of practical uses. Here are the different syntaxes for accomplishing this: 

$("div").addClass("content"); // adds class "content" to all <div> elements
$("div").removeClass("content"); // removes class "content" from all <div> elements
$("div").toggleClass("content");

// toggles the class "content" on all <div> elements (adds it if it doesn't exist, //
and removes it if it does)

You can also check to see if a selected element has a particular CSS class, and then run some code if it does. You would check this using an if statement. Here is an example: 

if ($("#myElement").hasClass("content")) {
 // do something here
}

You could also check a set of elements (instead of just one), and the result would return "true" if any one of the elements contained the class.

Selecting Elements in jQuery


The jQuery library allows you to select elements in your XHTML by wrapping them in $("") (you could also use single quotes), which is the jQuery wrapper. Here are some examples of “wrapped sets” in jQuery: 

$("div"); // selects all HTML div elements
$("#myElement"); // selects one HTML element with ID "myElement"
$(".myClass"); // selects HTML elements with class "myClass"
$("p#myElement"); // selects HTML paragraph element with ID "myElement"
$("ul li a.navigation");

// selects anchors with class "navigation" that are nested in list items
jQuery supports the use of all CSS selectors, even those in CSS3. Here are some examples of alternate selectors: 

$("p > a"); // selects anchors that are direct children of paragraphs
$("input[type=text]"); // selects inputs that have specified type
$("a:first"); // selects the first anchor on the page
$("p:odd"); // selects all odd numbered paragraphs
$("li:first-child"); // selects each list item that's the first child in its list
jQuery also allows the use of its own custom selectors. Here are some examples:
$(":animated"); // selects elements currently being animated
$(":button"); // selects any button elements (inputs or buttons)
$(":radio"); // selects radio buttons
$(":checkbox"); // selects checkboxes
$(":checked"); // selects checkboxes or radio buttons that are selected
$(":header"); // selects header elements (h1, h2, h3, etc.) 

1 Sept 2013

RowDataBound Event of GridView of asp.net with C#

Row DataBound event of GridView:-
Here we are binding the DropDownList in GridView and runtime set the dropdown selected value according to GridView Column.

Step1:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
             DataKeyNames="EmpID" onrowdatabound="GridView1_RowDataBound">
          <Columns>
          <asp:TemplateField  HeaderText="SetEno">
          <ItemTemplate>
          <asp:DropDownList ID="ddlEmpid" runat="server" Width="90%" DataSourceID="SqlDataSource1" DataTextField="EMPID"
                                DataValueField="EMPID"  >
          </asp:DropDownList>
          </ItemTemplate>              
         
          </asp:TemplateField>
       <asp:TemplateField HeaderText="Empid" Visible="false">
          <ItemTemplate>
          <asp:Label ID="lblEmpNo" runat="server" Text='<%# Eval("EmpNo") %>' />
          </ItemTemplate>
          </asp:TemplateField>
            <asp:BoundField DataField="EMPID" HeaderText="EmployeeID" ReadOnly="true"  />
            <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" />
            <asp:BoundField DataField="Address" HeaderText="Address" />
            <asp:BoundField DataField="Mobile" HeaderText="Mobile" />
                 
          </Columns>
        </asp:GridView>
Step2:-

    <asp:SqlDataSource ID="SqlDataSource1" runat="server"  ConnectionString="<%$ ConnectionStrings:mycon %>"
                SelectCommand="SELECT [EMPID] FROM EMPLOYEEID"></asp:SqlDataSource>
   
step3:-

public partial class GridViewDropDown : System.Web.UI.Page
{
    SqlConnection con;
    protected void Page_Load(object sender, EventArgs e)
    {
        string conection;
        conection = System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString.ToString();
        con = new SqlConnection(conection);
     
            FillGrid();
         }
    protected void FillGrid()
    {
        SqlCommand cmd = new SqlCommand("select * from employee", con);
        con.Open();
        GridView1.DataSource = cmd.ExecuteReader();
        GridView1.DataBind();
        con.Close();
    }


    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {              
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddl = (DropDownList)e.Row.FindControl("ddlEmpid");
            Label lblEmpid = ((Label)e.Row.FindControl("lblEmpNo"));
          //  string y = (String)DataBinder.Eval(e.Row.DataItem, "FirstName");
            string x=lblEmpid.Text.ToString().Trim();
            ddl.SelectedValue = x;
        }
    }
   
}

GridView default Pager using CSS Class Styles in ASP.Net

In this article I will explain how to style the GridView default Pager using CSS Class Styles in ASP.Net.

Database
For this article I am making use of the Microsoft’s Northwind Database. Download and install instructions are provided in the link below

HTML Markup
The HTML Markup consists of an ASP.Net GridView. For the GridView I have enabled paging using the AllowPaging property and I have also specified on the OnPageIndexChanging event.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
    runat="server" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging">
    <Columns>
        <asp:BoundField DataField="ContactName" HeaderText="Contact Name" ItemStyle-Width="150px" />
        <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="100px" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100px" />
    </Columns>
    <PagerStyle HorizontalAlign = "Right" CssClass = "GridPager" />
</asp:GridView>



Namespaces
You will need to import the following namespaces
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


Binding the GridView
Below is the code to bind the GridView with records from the Customers table of the Northwind database
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindGrid();
    }
}

private void BindGrid()
{
    string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}


Styling the GridView Pager
In order to style the GridView Pager you need to follow the following
1. Add the following CSS classes to the page or the CSS file.
<style type="text/css">
    body
    {
        font-family: Arial;
        font-size: 10pt;
    }
    .GridPager a, .GridPager span
    {
        display: block;
        height: 15px;
        width: 15px;
        font-weight: bold;
        text-align: center;
        text-decoration: none;
    }
    .GridPager a
    {
        background-color: #f5f5f5;
        color: #969696;
        border: 1px solid #969696;
    }
    .GridPager span
    {
        background-color: #A1DCF2;
        color: #000;
        border: 1px solid #3AC0F2;
    }
</style>

2. Next you need to assign the Pager CSS Class to the Page using the PagerStyle-CssClass property as shown below

<PagerStyle HorizontalAlign = "Right" CssClass = "GridPager" />

28 Aug 2013

ADO.NET Interview Question - Asp.net C#, VB.net

Which architecture does Datasets follow?

Datasets follow the disconnected data architecture.

16. What is the role of the DataSet object in ADO.NET?

One of the major component of ADO.NET is the DataSet object, which always remains disconnected from the database and reduces the load on the database.

What is a DataReader object?

The DataReader object helps in retrieving the data from a database in a forward-only, read-only mode. The base class for all the DataReader objects is the DbDataReader class.

The DataReader object is returned as a result of calling the ExecuteReader() method of the Command object. The DataReader object enables faster retrieval of data from databases and enhances the performance of .NET applications by providing rapid data access speed. However, it is less preferred as compared to the DataAdapter object because the DataReader object needs an Open connection till it completes reading all the rows of the specified table.

An Open connection to read data from large tables consumes most of the system resources. When multiple client applications simultaneously access a database by using the DataReader object, the performance of data retrieval and other related processes is substantially reduced. In such a case, the database might refuse connections to other .NET applications until other clients free the resources.

How can you identify whether or not any changes are made to the DataSet object since it was last loaded?

The DataSet object provides the following two methods to track down the changes:
The GetChanges() method - Returns the DataSet object, which is changed since it was loaded or since the AcceptChanges() method was executed.
The HasChanges() method - Indicates if any changes occurred since the DataSet object was loaded or after a call to the AcceptChanges() method was made.

Mention different types of data providers available in .NET Framework. - Interview Question

.NET Framework Data Provider for SQL Server - Provides access to Microsoft SQL Server 7.0 or later version. It uses the System.Data.SqlClient namespace.
.NET Framework Data Provider for OLE DB - Provides access to databases exposed by using OLE DB. It uses the System.Data.OleDb namespace.
.NET Framework Data Provider for ODBC - Provides access to databases exposed by using ODBC. It uses the System.Data.Odbc namespace.
.NET Framework Data Provider for Oracle - Provides access to Oracle database 8.1.7 or later versions. It uses the System.Data.OracleClient namespace.

Name the two properties of the GridView control that have to be specified to turn on sorting and paging.

The properties of the GridView control that need to be specified to turn on sorting and paging are as follows:
The AllowSorting property of the Gridview control indicates whether sorting is enabled or not. You should set the AllowSorting property to True to enable sorting.
The AllowPaging property of the Gridview control indicates whether paging is enabled or not. You should set the AllowPaging property to True to enable paging.

Asp.net interview questions on gridview C#, vb.net

What is DataGrid...

We can define DataGrid as a Powerfull WebServer tool which is used for displaying information from a DataSource in a tabular form an enables us to perform Sorting, Paging and Editing by setting a few properties and creating a couple of event handlers.

How Web DataGrid is Different from Windows DataGrid Control...

The WebPage DataGrid control is Different from Windows DataGrid in entire programming paradigm. Let's see...

* Web DataGrid Control performs a round trip to the server.
* Web DataGrid manage State.
* Windows DataGrid Control Supports master-detail data structure while web Datagrid doesn't.
* In Web DataGrid ,you can Edit only one row at a time.
* Web DataGrid Does not inherently support sorting, but raises events while Windows DataGrid does support.
* Web DataGrid supports Paging.
* You can bind Web DataGrid Control to any object that supports the IEnumerable interface.

How do you bind data in the DataGrid?

Binding Data in DataGrid means how we show the data from a table or a relation in our DataGrid.

Suppose We want to show the data of "Customers" table of "Northwind" database present in SQL Server on the Button Click. Now Follow the given steps....

step 1: Drag a DataGrid and a Button control on the Page.
step 2: In the Code behind Use the namespace as
using System.Data.SqlClient;
step 3: Write the following code in the Button's Click event handler...

protected void Button1_Click(object sender,EventArgs e)
{
SqlConnection con=new SqlConnection ("server=rajkumar;uid=sa;pwd=kumar;database=northwind) ;
SqlDataAdapter da_show=new SqlDataAdapter (" select ProductName, UnitPrice, UnitsInStock from Products", con);
DataSet ds=new DataSet;
da_show.Fill(ds, "Products");
GridView1.DataSource=ds.Tables["products"];
GridView1.DataBind( );
}

This will show all the rows and selected column in the DataGrid. The Column names in the DataGrid will be same as attributes name in the database table.

How do you customize the DataGrid...

Here I will show you how to Display only Selected Column in the DataGrid even when you selected all the columns in your Query in Code Behind file. Also I will show you how to change the Name of the Column in the DataGrid.

Suppose I want to Display only ProductName and UnitPrice from the table and Also Want To display ProductName as Product Name and UnitPrice as Price......So

Step 1 : In the Code behind file the code will be same as above.
Step 2 : Set the Property AutoGenerateColumns of DataGrid to false.
Step 3 : Go to source View and Insert TemplateColumns in the datagrid tag.

DOT NET/ASP.NET interview questions: - When to consider Data grid, data list, or repeater?

This is one of quiet often asked .NET/ASP.NET interview questions so prepare accordingly to answer it to the interviewer.

Many of the developers make a blind choice of choosing data grid directly, but that is not the right way.

Data grid provides ability to allow the end-user to sort, page, and edit its data. However, it comes at a cost of speed. Second, the display format is simple that is in row and columns. Real life scenarios can be more demanding that

With its templates, the Data List provides more control over the look and feel of the displayed data than the Data Grid. It offers better performance than data grid

Repeater control allows for complete and total control. With the Repeater, the only HTML emitted are the values of the data binding statements in the templates along with the HTML markup specified in the templates no "extra" HTML is emitted, as with the Data Grid and Data List. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time. However, repeater does not provide editing features like data grid so everything has to be coded by programmer. However, the Repeater does boast the best performance of the three data Web controls. Repeater is fastest followed by Datalist and finally data grid.

See video on ASP.NET 4.0 web.config transformation as follows: -


Reading HTML Data from any website

Hi,

This is how I solved the problem of extracting info from a html table.
Means, The site which have data in a tabular or list format, then you can read data by using HTMLAgility Pack.


Download HTMLAgilityPack.dll and add referce to it in your project.



Sample code are written as:-

HTML
<BODY>
<TABLE>
<TR>
<TD>Row 0, Col 0</TD>
<TD>Row 0, Col 1</TD>
</TR>
<TR>
<TD>Row 1, Col 0</TD>
<TD>Row 1, Col 1<TD>
</TR>
</TABLE>
</BODY>

Code
// Load the html document
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load("http://myServer/myTable.htm");

// Get all tables in the document
HtmlNodeCollection tables = doc.DocumentNode.SelectNodes("//TABLE");

// Iterate all rows in the first table
HtmlNodeCollection rows = tables[0].SelectNodes(".//TR");
for (int i = 0; i < rows.Count; ++i) {

// Iterate all columns in this row
HtmlNodeCollections cols = rows[i].SelectNodes(".//TD");
for (int j = 0; j < cols.Count; ++j) {

// Get the value of the column and print it
string value = cols[j].InnerText;
Console.WriteLine(value);
}
}

Result
Row 0, Col 0
Row 0, Col 1
Row 1, Col 0
Row 1, Col 1

27 Aug 2013

jQuery.each() JSON Example using Jquery

(function($) {
var json = [
    { "red": "#f00" },
    { "green": "#0f0" },
    { "blue": "#00f" }
];

$.each(json, function() {
  $.each(this, function(name, value) {
    /// do stuff
    console.log(name + '=' + value);
  });
});
//outputs: red=#f00 green=#0f0 blue=#00f
})(jQuery);

jQuery.each() Class Example using Jquery

This example shows you how to loop through each element with class=”productDesc” given in the HTML below.


<div class=”productDesc” >Red</div>
<div class=”productDesc” >Orange</div>
<div class=”productDesc” >Green</div>


$.each($('.productDesc'), function(index, value) { 
    console.log(index + ':' + value); 
});
//outputs: 1:Red 2:Orange 3:Green


You don’t have to include index and value these are just parameters which help determine which DOM element your currently iterating. You could also write it like this:

$.each($('.productDesc'), function() { 
    console.log($(this).html());
});
//outputs: Red Orange Green

26 Aug 2013

jQuery.each() Array Example with Jquery

var numberArray = [0,1,2,3,4,5];
jQuery.each(numberArray , function(index, value){
     console.log(index + ':' + value);
});
//outputs: 1:1 2:2 3:3 4:4 5:5

Basic jQuery.each() Function Example using JQuery


$('a').each(function(index, value){
      console.log($(this).attr('href'));
});
//outputs: every links href element on your web page

$('a').each(function(index, value){
    var ihref = $(this).attr('href');
    if (ihref.indexOf("http") >= 0)
    {
        console.log(ihref+'<br/>');
    }
});
//outputs: every external href on your web page

jQuery .each() Syntax using JQuery

//DOM ELEMENTS $("div").each(function(index, value) { console.log('div' + index + ':' + $(this).attr('id')); }); //outputs the ids of every div on the web page //ie - div1:header, div2:body, div3:footer //ARRAYS var arr = [ "one", "two", "three", "four", "five" ]; jQuery.each(arr, function(index, value) { console.log(this); return (this != "three"); // will stop running after "three" }); //outputs: one two three //OBJECTS var obj = { one:1, two:2, three:3, four:4, five:5 }; jQuery.each(obj, function(i, val) { console.log(val); }); //outputs: 1 2 3 4 5

getElementById OR get textbox Elements id on forms with using javascript

Method 1: Using an ID
Code:
function add(text){
    var TheTextBox = document.getElementById("Mytextbox");
    TheTextBox.value = TheTextBox.value + text;
}



Method 2: using the form:
Code:
function add(text){
    var TheTextBox = document.forms[0].elements['field_name']; //I think that's right, haven't done it in a while
    TheTextBox.value = TheTextBox.value + text;
}

Using dateadd in SQL Server to add intervals to dates

The syntax for the dateadd() function in SQL Server is as follows:

DATEADD (datepart, number, date)
"datepart" is the interval type you wish to add or subtract for example day, month, year, hour, minute, second. These can be abbreviated as dd and d for day, mm and m for month, yy and yyyy for year, hh for hour, mi and n for minute and ss and s for second.

The number is the amount of datepart units to add or subtract. For example if datepart was d and the number was 3 then it would add three days to the date specified.

And finally, date is the date to add/subtract the number of dateparts from. It can either be a column in the database, a constant value or a function such as GETDATE() which would return the current date and time.

Using the same examples from the MySQL post, to show the current date and time, and to add a month to the current date you would do this:

SELECT GETDATE(), DATEADD(month, 1, GETDATE())
which would give you the following result:

2008-10-03 14:57:09.907
2008-11-03 14:57:09.907
To subtract a month to the current, simply make a negative number value:

SELECT GETDATE(), DATEADD(month, -1, GETDATE())
which would give the following result:

2008-10-03 14:58:08.113
2008-09-03 14:58:08.113
And to use the same example from the MySQL article, if we have a table called "products" and it has a column called "backorder_date" which has a column type of date, we could run this query to add three days onto the back order date which is the value we might display on a website:

SELECT DATEADD(day, 3, backorder_date) AS backorder_date FROM products
and an example result

2008-10-18 00:00:00.000
It's very easy to add and subtract dates using Microsoft SQL Server. The are often circumstances when you would need to use this and do it in the database rather than in business logic or website code, such as calculating the backorder date of a product in the last example above.

23 Aug 2013

Contact Form For Mail Code in PHP through using MSN SMTP

Contact Form For Mail Code in PHP through using MSN SMTP

<?php
require_once('mail/class.phpmailer.php'); // download php mailer class

$fname = $_POST['fname']; // required
$lname = $_POST['lname']; // required
$contact = $_POST['contact']; // not required
$email = $_POST['email']; // not required
$address = $_POST['address']; // not required
$pcode = $_POST['code']; // not required
$price = $_POST['price']; // required
$qty = $_POST['qty']; // required
$comments = $_POST['comments']; // required



$strmsg=("<p>Hi, </p><p>Name: $fname $lname </p><p>Contact: $contact </p><p>Email -Id: $email </p><p>Address: $address </p><p>Product Code No.: $pcode </p><p>Price: $price </p><p>Quantity: $qty </p></br>Comments : $comments");

//echo($strmsg);

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet="UTF-8";
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.live.com';
$mail->Port = 587;
$mail->Username = 'frommailid';
$mail->Password = 'password';
$mail->SMTPAuth = true;

$mail->From = 'frommailid';
$mail->FromName = 'name';
$mail->AddAddress('emailid');
$mail->AddReplyTo('fromemilid', 'Information');

$mail->IsHTML(true);
$mail->Subject    = "subject";
//$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";
$mail->Body    = $strmsg;

if(!$mail->Send())
{
  echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
  echo "Your message was successfully sent! Thank you for contacting us, we will reply to your inquiry as soon as possible!";
}
?>

22 Aug 2013

Get Browsers Parameter Value From URL With Javascript Code, Asp.net HTML and PHP

function getURLParameters()
{
var sURL = window.document.URL.toString();

if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");

var arrURLParams = arrParams[1].split("&");

var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);

var i = 0;
for (i=0;i<arrURLParams.length;i++)
{
var sParam =  arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}

for (i=0;i<arrURLParams.length;i++)
{
alert(arrParamNames[i]+" = "+ arrParamValues[i]);
}
}
else
{
alert("No parameters.");
}
}

<body onload=" getURLParameters() ">

SQL SERVER – Get Date Time in Any Format

Refer the function and get familiar yourself with different format this function support. I have added few examples of how this function can be used at the end of the article


CREATE FUNCTION [dbo].[ufsFormat]
(
@Date datetime,
@fORMAT VARCHAR(80)
)
RETURNS NVARCHAR(80)
AS
BEGIN
DECLARE @Dateformat INT
DECLARE @ReturnedDate VARCHAR(80)
DECLARE @TwelveHourClock INT
DECLARE @Before INT
DECLARE @pos INT
DECLARE @Escape INT
-- (c) Pinal Dave http://www.SQLAuthority.com
SELECT @ReturnedDate='error! unrecognised format '+@format
SELECT @DateFormat=CASE @format
WHEN 'mmm dd yyyy hh:mm AM/PM' THEN 100
WHEN 'mm/dd/yy' THEN 1
WHEN 'mm/dd/yyyy' THEN 101
WHEN 'yy.mm.dd' THEN 2
WHEN 'dd/mm/yy' THEN 3
WHEN 'dd.mm.yy' THEN 4
WHEN 'dd-mm-yy' THEN 5
WHEN 'dd Mmm yy' THEN 6
WHEN 'Mmm dd, yy' THEN 7
WHEN 'hh:mm:ss' THEN 8
WHEN 'yyyy.mm.dd' THEN 102
WHEN 'dd/mm/yyyy' THEN 103
WHEN 'dd.mm.yyyy' THEN 104
WHEN 'dd-mm-yyyy' THEN 105
WHEN 'dd Mmm yyyy' THEN 106
WHEN 'Mmm dd, yyyy' THEN 107
WHEN 'Mmm dd yyyy hh:mm:ss:ms AM/PM' THEN 9
WHEN 'Mmm dd yyyy hh:mi:ss:mmm AM/PM' THEN 9
WHEN 'Mmm dd yy hh:mm:ss:ms AM/PM' THEN 109
WHEN 'mm-dd-yy' THEN 10
WHEN 'mm-dd-yyyy' THEN 110
WHEN 'yy/mm/dd' THEN 11
WHEN 'yyyy/mm/dd' THEN 111
WHEN 'yymmdd' THEN 12
WHEN 'yyyymmdd' THEN 112
WHEN 'dd Mmm yyyy hh:mm:ss:Ms' THEN 113
WHEN 'hh:mm:ss:Ms' THEN 14
WHEN 'yyyy-mm-dd hh:mm:ss' THEN 120
WHEN 'yyyy-mm-dd hh:mm:ss.Ms' THEN 121
WHEN 'yyyy-mm-ddThh:mm:ss.Ms' THEN 126
WHEN 'dd Mmm yyyy hh:mm:ss:ms AM/PM' THEN 130
WHEN 'dd/mm/yy hh:mm:ss:ms AM/PM' THEN 131
WHEN 'RFC822' THEN 2
WHEN 'dd Mmm yyyy hh:mm' THEN 4
ELSE 1 END
SELECT @ReturnedDate='error! unrecognised format ' +@format+CONVERT(VARCHAR(10),@DateFormat)
IF @DateFormat>=0
SELECT @ReturnedDate=CONVERT(VARCHAR(80),@Date,@DateFormat)
--check for favourite and custom formats that can be done quickly
ELSE IF @DateFormat=-2--then it is RFC822 format
SELECT @ReturnedDate=LEFT(DATENAME(dw, @Date),3) + ', ' + STUFF(CONVERT(NVARCHAR,@Date,113),21,4,' GMT')
ELSE IF @DateFormat=-4--then it is european day format with minutes
SELECT @ReturnedDate=CONVERT(CHAR(17),@Date,113)
ELSE
BEGIN
SELECT @Before=LEN(@format)
SELECT @Format=REPLACE(REPLACE(REPLACE( @Format,'AM/PM','#'),'AM','#'),'PM','#')
SELECT @TwelveHourClock=CASE WHEN @Before >LEN(@format) THEN 109 ELSE 113 END, @ReturnedDate=''
WHILE (1=1)--forever
BEGIN
SELECT @pos=PATINDEX('%[yqmidwhs:#]%',@format+' ')
IF @pos=0--no more date format strings
BEGIN
SELECT @ReturnedDate=@ReturnedDate+@format
BREAK
END
IF @pos>1--some stuff to pass through first
BEGIN
SELECT @escape=CHARINDEX ('\',@Format+'\') --is it a literal character that is escaped?
IF @escape<@pos BEGIN
SET @ReturnedDate=@ReturnedDate+SUBSTRING(@Format,1,@escape-1) +SUBSTRING(@format,@escape+1,1)
SET @format=RTRIM(SUBSTRING(@Format,@Escape+2,80))
CONTINUE
END
SET @ReturnedDate=@ReturnedDate+SUBSTRING(@Format,1,@pos-1)
SET @format=RTRIM(SUBSTRING(@Format,@pos,80))
END
SELECT @pos=PATINDEX('%[^yqmidwhs:#]%',@format+' ')--get the end
SELECT @ReturnedDate=@ReturnedDate+--'('+substring(@Format,1,@pos-1)+')'+
CASE SUBSTRING(@Format,1,@pos-1)
--Mmmths as 1--12
WHEN 'M' THEN CONVERT(VARCHAR(2),DATEPART(MONTH,@Date))
--Mmmths as 01--12
WHEN 'Mm' THEN CONVERT(CHAR(2),@Date,101)
--Mmmths as Jan--Dec
WHEN 'Mmm' THEN CONVERT(CHAR(3),DATENAME(MONTH,@Date))
--Mmmths as January--December
WHEN 'Mmmm' THEN DATENAME(MONTH,@Date)
--Mmmths as the first letter of the Mmmth
WHEN 'Mmmmm' THEN CONVERT(CHAR(1),DATENAME(MONTH,@Date))
--Days as 1--31
WHEN 'D' THEN CONVERT(VARCHAR(2),DATEPART(DAY,@Date))
--Days as 01--31
WHEN 'Dd' THEN CONVERT(CHAR(2),@date,103)
--Days as Sun--Sat
WHEN 'Ddd' THEN CONVERT(CHAR(3),DATENAME(weekday,@Date))
--Days as Sunday--Saturday
WHEN 'Dddd' THEN DATENAME(weekday,@Date)
--Years as 00--99
WHEN 'Yy' THEN CONVERT(CHAR(2),@Date,12)
--Years as 1900--9999
WHEN 'Yyyy' THEN DATENAME(YEAR,@Date)
WHEN 'hh:mm:ss' THEN SUBSTRING(CONVERT(CHAR(30),@date,@TwelveHourClock),13,8)
WHEN 'hh:mm:ss:ms' THEN SUBSTRING(CONVERT(CHAR(30),@date,@TwelveHourClock),13,12)
WHEN 'h:mm:ss' THEN SUBSTRING(CONVERT(CHAR(30),@date,@TwelveHourClock),13,8)
--tthe SQL Server BOL syntax, for compatibility
WHEN 'hh:mi:ss:mmm' THEN SUBSTRING(CONVERT(CHAR(30),@date,@TwelveHourClock),13,12)
WHEN 'h:mm:ss:ms' THEN SUBSTRING(CONVERT(CHAR(30),@date,@TwelveHourClock),13,12)
WHEN 'H:m:s' THEN SUBSTRING(REPLACE(':'+SUBSTRING(CONVERT(CHAR(30), @Date,@TwelveHourClock),13,8),':0',':'),2,30)
WHEN 'H:m:s:ms' THEN SUBSTRING(REPLACE(':'+SUBSTRING(CONVERT(CHAR(30), @Date,@TwelveHourClock),13,12),':0',':'),2,30)
--Hours as 00--23
WHEN 'hh' THEN REPLACE(SUBSTRING(CONVERT(CHAR(30), @Date,@TwelveHourClock),13,2),' ','0')
--Hours as 0--23
WHEN 'h' THEN LTRIM(SUBSTRING(CONVERT(CHAR(30), @Date,@TwelveHourClock),13,2))
--Minutes as 00--59
WHEN 'Mi' THEN DATENAME(minute,@date)
WHEN 'mm' THEN DATENAME(minute,@date)
WHEN 'm' THEN CONVERT(VARCHAR(2),DATEPART(minute,@date))
--Seconds as 0--59
WHEN 'ss' THEN DATENAME(second,@date)
--Seconds as 0--59
WHEN 'S' THEN CONVERT(VARCHAR(2),DATEPART(second,@date))
--AM/PM
WHEN 'ms' THEN DATENAME(millisecond,@date)
WHEN 'mmm' THEN DATENAME(millisecond,@date)
WHEN 'dy' THEN DATENAME(dy,@date)
WHEN 'qq' THEN DATENAME(qq,@date)
WHEN 'ww' THEN DATENAME(ww,@date)
WHEN '#' THEN REVERSE(SUBSTRING(REVERSE(CONVERT(CHAR(26), @date,109)),1,2))
ELSE
SUBSTRING(@Format,1,@pos-1)
END
SET @format=RTRIM(SUBSTRING(@Format,@pos,80))
END
END
RETURN @ReturnedDate
END
GO
SELECT [dbo].[ufsFormat] ('8/7/2008', 'mm/dd/yy')
GO
SELECT [dbo].[ufsFormat] ('8/7/2008', 'hh:mm:ss')
GO
SELECT [dbo].[ufsFormat] ('8/7/2008', 'mmm')
GO
SELECT [dbo].[ufsFormat] ('8/7/2008', 'Mmm dd yyyy hh:mm:ss:ms AM/PM')
GO
SELECT [dbo].[ufsFormat] ('8/7/2008', '#')
GO