15 Oct 2011

SQL SERVER – Get Date Time in Any Format – UDF – User Defined Functions

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

13 Oct 2011

Page Methods

Design
<asp:ScriptManager id="SM1" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
    </asp:ScriptManager>

PageMethods.getDistance(fromto,OnSuccess,OnError);

function OnSuccess(result)
    {
        if (result==null)
        {
        }
        else
        {
            txtKM.value=result;
        }
    }
    function OnError(err)
    {

    }

code behind

<System.Web.Services.WebMethod()> _
Public Shared Function getDistance(ByVal FromTo As String) As String
        Try

            Dim CityFrom, CityTo As Integer
            CityFrom = Val(FromTo.Split("|")(0))
            CityTo = Val(FromTo.Split("|")(1))

            Dim db As DBAccess = New DBAccess

            db.AddParameter("@Case", 7)
            db.AddParameter("@PlaceFrom", CityFrom)
            db.AddParameter("@PlaceTo", CityTo)

            Dim dt As DataTable
            dt = db.ExecuteDataTable(, "usp_LTC")
            If dt.Rows.Count = 0 Then
                Return ""
            Else
                Return dt.Rows(0)(0)
            End If
        Catch ex As Exception
            Throw ex
        End Try

    End Function

limit the no of items user can check in ckeckboxlist using jquery

<script type="text/javascript" language="javascript">
        //Count the Total Selection in CheckBoxList - BusinessType
        $('#<%= cblBusinessType.ClientID %>').find('input:checkbox').click(function()
        {
             var totCount=0;

             jQuery('#<%= cblBusinessType.ClientID %>').find("input:checkbox").each(function() {

             if (jQuery(this).attr("checked"))
             {
               totCount++;
             }

           });
           if(totCount > 3)
           {
               alert("Select up to 3 Business Types only...");
               return false;
           }

           return true;

        });
</script>

Date validation and comparision as dd-MMM-yyyy in javascript

validateDate.months = {jan: 0, feb: 1, mar: 2, apr: 3, may: 4, jun: 5, jul: 6, aug: 7, sep: 8, oct: 9, nov: 10, dec: 11};
    function validateDate(string) //used to validate
    {
        var m = /^(\d\d)-(\w{3})-(\d{4})$/.exec(string);
        if (!m) return false;
        var month = validateDate.months[m[2].toLowerCase()];
        if (typeof month != "number") return false;
        var date = +m[1];
        var year = +m[3];
        var d = new Date(year, month, date);
        if (d.getDate() != date || d.getMonth() != month) return false;
        return true;
    }

    function GetMyDate(string)//used to cmpare
    {
        var m = /^(\d\d)-(\w{3})-(\d{4})$/.exec(string);
        if (!m) return false;
        var month = validateDate.months[m[2].toLowerCase()];
        if (typeof month != "number") return false;
        var date = +m[1];
        var year = +m[3];
        var d = new Date(year, month, date);
        return d;
    }

Checkboxlist atleast on item checked in javascript

//id  is the client id of checkbox list
function isChecked(id)
    {
        var chkListModules= document.getElementById (id);
        var chkListinputs = chkListModules.getElementsByTagName("input");
        for (var i=0;i<chkListinputs.length;i++)
        {
            if (chkListinputs[i].checked)
            {
                return true;
            }
        }
        return false;
    }

12 Oct 2011

Ajax check PartialLoad in javascript

function pageLoad(sender, args)
    {
        if (args.get_isPartialLoad())
        {
            //alert('Ajax call');
            //$('#grid').hide().slideDown(500);
        }
        else
        {
            //alert('PostBack or initial load');
            $('#grid').hide().slideDown(500);
        }
    }

8 Oct 2011

Find refrence of table in SQL Server 2008

SELECT     cast(f.name AS VARCHAR(255)) AS foreign_key_name
           ,r.keycnt
           ,cast(c.name AS VARCHAR(255)) AS foreign_table
           ,cast(fc.name AS VARCHAR(255)) AS foreign_column_1
           ,cast(fc2.name AS VARCHAR(255)) AS foreign_column_2
           ,cast(p.name AS VARCHAR(255)) AS primary_table
           ,cast(rc.name AS VARCHAR(255)) AS primary_column_1
           ,cast(rc2.name AS VARCHAR(255)) AS primary_column_2
FROM       sysobjects f
INNER JOIN sysobjects c ON f.parent_obj = c.id
INNER JOIN sysreferences r ON f.id = r.constid
INNER JOIN sysobjects p ON r.rkeyid = p.id
INNER JOIN syscolumns rc ON r.rkeyid = rc.id
                            AND r.rkey1 = rc.colid
INNER JOIN syscolumns fc ON r.fkeyid = fc.id
                            AND r.fkey1 = fc.colid
LEFT JOIN  syscolumns rc2 ON r.rkeyid = rc2.id
                             AND r.rkey2 = rc.colid
LEFT JOIN  syscolumns fc2 ON r.fkeyid = fc2.id
                             AND r.fkey2 = fc.colid
WHERE      f.type = 'F'
           AND p.name = 'Mtrghighendprg'
ORDER      BY cast(p.name AS VARCHAR(255))

5 Oct 2011

Reading XML String in SQL 2008

declare @OrderList xml
set @OrderList = '<Order>
<Item>
<Prod ID=''60000'' Qty=''200''></Prod>
</Item>
<Item>
<Prod ID=''60180'' Qty=''1000''></Prod>
</Item>
</Order>'

select
D.element.value('@ID', 'nvarchar(255)') as ID,
D.element.value('@Qty','nvarchar(255)') as Qty
 from @OrderList.nodes('/Order/Item/Prod') as D(element)