Thursday, December 16, 2010

SQL Server: Convert 24 hour format time into 12 hour format

Hi,
Here is an example of converting time data type i.e.13:09 which is in 24 hr format into 12 hr format i.e  1:09 format.

Create Function :


alter FUNCTION dbo.Split1(@String varchar(8000), @Delimiter char(1))    
returns @temptable TABLE (items varchar(8000))    
as    
begin    
declare @idx int    
declare @slice varchar(8000)
declare @count int
declare @finaltime varchar(5)
set @count=0  
  
select @idx = 1    
if len(@String)<1 or @String is null  return    
  
while @idx!= 0    
begin    
set @count=@count+1
set @idx = charindex(@Delimiter,@String)    
if @idx!=0    
set @slice = left(@String,@idx - 1)    
else    
set @slice = @String    

if((len(@slice)>0))
begin
declare @hrtime varchar(2)
set @hrtime=convert(varchar(2),@slice)
if(@count=1)
begin
declare @hrinttime int
set @hrinttime=convert(int,@hrtime)
if(@hrinttime>12)
begin
set @hrinttime=@hrtime-12
end
else
begin
set @hrinttime=@hrtime
end


--insert into @temptable(Items) values(@hrinttime)
set @finaltime =@hrinttime
set @finaltime=@finaltime+':'


end
else
-- insert into @temptable(Items) values(@hrtime)
set @finaltime=@finaltime+@hrtime
  -- insert into @temptable(Items) values(@slice)
end

set @String = right(@String,len(@String) - @idx)    
if len(@String) = 0 break    
end

insert into @temptable (Items) values(@finaltime)
return    
end




Run Function in this way:
select top 10 * from Split1('13:09',':')  

Thursday, November 25, 2010

SQL Server:Execution Time Calculation For Queries

Hi,
This is the example for calculating Query execution time in SQL
The procedure is very simple, first take start time of query execution and then write the query and then get the end time of query execution and then calculate their difference



And below is the execution plan for the query

For execution plan you have to just run the query and click on the icon menu i.e. Display Estimated Execution Plan



Happy Coding,
Regards,
Krunal Panchal

Monday, November 22, 2010

SQL SERVER:Generating CSV in select command and again Generating Row wise data

Hi everyone,


Declare @chapters varchar(max)
select @chapters=coalesce(@chapters+',','')+ch.Chapter
from Chapter ch,Subject sb ,Syllabus s,Classroom c
--for syllabus
where s.SyllabusID ='3'
--for classroom
and c.SyllabusID =s.SyllabusID
and c.Classroom =1
--for subject
and sb.SyllabusID =s.SyllabusID
and sb.ClassroomID =c.ClassroomID
--and sb.Subject ='Eng.Lit.'
--for chapters
and ch.SyllabusID =s.SyllabusID
and ch.ClassroomID =c.ClassroomID
and ch.SubjectID =sb.SubjectID

select @chapters

Select * from UF_CSVToTable (@chapters)

Function UF_CSVToTable 


USE [CMS2012]
GO
/****** Object:  UserDefinedFunction [dbo].[UF_CSVToTable]    Script Date: 11/22/2010 17:15:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION [dbo].[UF_CSVToTable]
(
 @psCSString VARCHAR(max)
)
RETURNS @otTemp TABLE(sID VARCHAR(2000))
AS
BEGIN
 DECLARE @sTemp VARCHAR(max)

 WHILE LEN(@psCSString) > 0
 BEGIN
  SET @sTemp = LEFT(@psCSString, ISNULL(NULLIF(CHARINDEX(',', @psCSString) - 1, -1),
                    LEN(@psCSString)))
  SET @psCSString = SUBSTRING(@psCSString,ISNULL(NULLIF(CHARINDEX(',', @psCSString), 0),
                               LEN(@psCSString)) + 1, LEN(@psCSString))
  INSERT INTO @otTemp VALUES (@sTemp)
 END

RETURN
END


OutPut:



Happy Coding,
Regards,
Krunal Panchal

SQL SERVER: Generate Comma Separated List with SELECT statement

Hi everyone,
Many times i require the data from select command in comma seperated format
for e.g.

SELECT  [AdminId]
      ,[LoginId]
      ,[Password]
      ,[AdminType]
      ,[TaskId]
      ,[CreatedBy]
      ,[Status]
  FROM [CMS2012].[dbo].[Admin_Details]
  where AdminId in(3,4,5,6)
will give me result as...



But what i need is...
Login id:-
Mexus,Vibhorthegame@yahoo.co.in,qwe,123@mexuseducation.com
Password:-
Mexus,123123,qwe,123123
etc.....
so i wrote this SQL select statement...


Declare @Description varchar(4000)
Declare @password varchar(max)

select @Description  = coalesce(@Description + ',','')  + LoginId ,
@password =coalesce(@password+',','')+Password
FROM Admin_Details  where AdminId  in (3,4,5,6)

SELECT
     @Description ,@password

And what i got is...



Happy Coding,
Regards,
Krunal Panchal

Sunday, November 21, 2010

Order By with VARCHAR

Hi everyone,

In order by clause of varchar(50) column for numeric values,the result is different from order by with integer column..

E.g. select * from classroom order by classroom (where classroom is varchar(max) column)
the result is:
       1
       10
       11
       12
        2
        3
      ........
now suppose i need it order by like 1 2 3 4 5 ... i need to convert the column to integer , instead of changing the design of table you could write your query as this...

select * from classroom order by cast(classroom as integer)

would give you result as 1 2 3 4 5........

Happy Coding,
Regards,
Krunal Panchal

How to get Id of Just Inserted Value in SQL

Hi everyone,
This is a Simple example of Getting Unique Id (Auto Id) for the inserted value after insertion of values in SQL table

Declare @subjectid INT =NULL out
-----Insertion Process-----------

Insert into Subject(SyllabusID,ClassroomID,Subject)
values(@syllabusid ,@classroomid ,@strsubject )

------Get Id into @subjectid----
set @subjectid =SCOPE_IDENTITY ();

Happy Coding,
Regards,
Krunal Panchal

Stored Procedure For Inserting Values in Table In Multiple Column using CSV and getting their AutoId

Hi everyone,
I got indulged into one situation where i have to insert values in SQL table using CSV (Comma Seperated Values) , now the situation became more critical where i need to insert values at a particular ID for a particular table.
i.e. i am having 2 tables namely:classroom, subject, syllabus
now i have data like 4,5,6 to be checked if present and if they are not present then they should be inserted for particular syllabus-id, now by getting the classroom-id for particular syllabus-id i have to insert subject eg. English, Maths  for that particular classroom-id and syllabus-id .
I made the Stored Procedure for simple Insertion.......
But the problem was that after inserting the subject the parameter of subject became null OR '' so i stored it in one variable before inserting , and set the subject parameter again to the stored one.......


This whole process also could be done in asp.net with several checks and for loops , but i thought that if it would be done in asp.net then there would be much load to the server. Then i thought of making Stored Procedure for this whole process and here it is........

Stored Procedure......

-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Krunal N. Panchal
-- Create date: Monday,November ,22,2010
-- Description: This Stored Procedure is for School Merge [For Insertion of Classroom And Subject By CSV]
-- =============================================
alter PROCEDURE [dbo].[Insert_Classroom_Subject]
--Parameters of Stored Procedure--
@classroom varchar(max),
@subject varchar(max),
@syllabusid varchar(max),
@classroomid varchar(max) =null out,
 @subjectid varchar(max)=NULL out
AS
DECLARE @countclassroom int
    DECLARE @strclassroom VARCHAR(max)
    DECLARE @spotclassroom SMALLINT
     DECLARE @storedsubject varchar(max)
SET @storedsubject =@subject

--------------for classroom insertion--------------
WHILE @classroom <> ''

    BEGIN
SET @subject =@storedsubject
        SET @spotclassroom = CHARINDEX(',', @classroom)
        IF @spotclassroom>0
            BEGIN
                SET @strclassroom = CAST(LEFT(@classroom, @spotclassroom-1) AS varchar(max))
                SET @classroom = RIGHT(@classroom, LEN(@classroom)-@spotclassroom)
            END
        ELSE
            BEGIN
                SET @strclassroom = CAST(@classroom AS varchar(max))
                SET @classroom = ''
            END
          
            --Check Classroom if Present---          
            SELECT @countclassroom=count(1) FROM classroom
WHERE Classroom =@strclassroom
and SyllabusID =@syllabusid
----if Classroom not present then insert it----
IF @countclassroom =0
BEGIN
Insert into Classroom(Classroom ,SyllabusID )
values (@strclassroom ,@syllabusid )
set @classroomid=SCOPE_IDENTITY ();
END
Else
-----else get the id of the classroom for selected subject----
Begin
set @classroomid=(select classroomid from Classroom WHERE Classroom =@strclassroom
and SyllabusID =@syllabusid )
End

-------------------End of classroom insertion---------------------

-------------------For Subject Insertion-----------------------------

DECLARE @countsubject int
    DECLARE @strsubject VARCHAR(max)
 
    DECLARE @spotsubject SMALLINT


----------------For Storing the subject-------------
--SET @storedsubject =@subject

WHILE @subject <> ''
BEGIN
SET @spotsubject = CHARINDEX(',', @subject)
IF @spotsubject>0
BEGIN
SET @strsubject = CAST(LEFT(@subject, @spotsubject-1) AS varchar(max))
SET @subject = RIGHT(@subject, LEN(@subject)-@spotsubject)
END
ELSE
BEGIN
SET @strsubject = CAST(@subject AS varchar(max))
SET @subject = ''
END

-----------check if subject is present for particular classroom and syllabus
SELECT @countsubject=count(1) FROM subject
WHERE ClassroomID  =@classroomid
and SyllabusID =@syllabusid
and Subject =@strsubject

-----count is 0 then insert the subject------
IF @countsubject =0
Begin
Insert into Subject(SyllabusID,ClassroomID,Subject)
values(@syllabusid ,@classroomid ,@strsubject )
set @subjectid =SCOPE_IDENTITY ();
End

End
---------------------Setting value of subject-----------


     End
  


GO


Happy Coding.
Regards,
Krunal Panchal

Monday, November 15, 2010

UDF for Seperation of CSV in SQL

Hi All,

This is the UDF for values having delimiter as COMMA(,)

How to Use::

1) Copy & Paste the below UDF in SQL and Execute it

ALTER FUNCTION [dbo].[UF_CSVToTable]
(
 @psCSString VARCHAR(8000)
)
RETURNS @otTemp TABLE(sID VARCHAR(20))
AS
BEGIN
 DECLARE @sTemp VARCHAR(10)

 WHILE LEN(@psCSString) > 0
 BEGIN
  SET @sTemp = LEFT(@psCSString, ISNULL(NULLIF(CHARINDEX(',', @psCSString) - 1, -1),
                    LEN(@psCSString)))
  SET @psCSString = SUBSTRING(@psCSString,ISNULL(NULLIF(CHARINDEX(',', @psCSString), 0),
                               LEN(@psCSString)) + 1, LEN(@psCSString))
  INSERT INTO @otTemp VALUES (@sTemp)
 END

RETURN
END

2) Now write the Query eg:

select * from [Your Table Name] where [Your Column Name] IN
                                                                            (Select * from UF_CSVToTable('1,2,3,4,5')

Regards,
Krunal Panchal

Insertion & Selection in SQL storedprocedure with CSV

 Hi All,

This is the Stored Procedure for inserting multiple values in multiple columns in SQL

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[InsertProductMembers]
      (
            @MemberId varchar(100),
            @MemberProductId varchar(100)
      )
AS

      DECLARE @count int
      DECLARE @str VARCHAR(8000)
      DECLARE @spot SMALLINT
       DECLARE @str1 VARCHAR(8000)
      DECLARE @spot1 SMALLINT

    WHILE @MemberProductId <> ''
    BEGIN
        SET @spot = CHARINDEX(',', @MemberProductId)
        IF @spot>0
            BEGIN
                SET @str = CAST(LEFT(@MemberProductId, @spot-1) AS varchar)
                SET @MemberProductId = RIGHT(@MemberProductId, LEN(@MemberProductId)-@spot)
            END
        ELSE
            BEGIN
                SET @str = CAST(@MemberProductId AS varchar)
                SET @MemberProductId = ''
            END
          
      
              

        SET @spot1 = CHARINDEX(',', @MemberId)
        IF @spot1>0
            BEGIN
                SET @str1 = CAST(LEFT(@MemberId, @spot-1) AS varchar)
                SET @MemberId = RIGHT(@MemberId, LEN(@MemberId)-@spot)
            END
        ELSE
            BEGIN
                SET @str1 = CAST(@MemberId AS varchar)
                SET @MemberId = ''
            END        

  
SELECT @count=count(1) FROM test

     WHERE id=@str

     AND id1=@MemberId
  

     IF @count =0

     BEGIN

      INSERT INTO test (id, id1) VALUES( @str1,@str)

     END

   end
  

      RETURN


Regards,
Krunal Panchal

Sunday, November 14, 2010

Round Up Values in C

# include <stdio.h>
# include <conio.h>
void main()
{
double d;
int i;
clrscr();
d=8.5;
i=(d<0)?d-0.5:d+0.5;
printf("The round up value is ::%d",i);
getch();
}

Output: The round up value is ::9

Wednesday, October 20, 2010

Round Up Values in vb.net

 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim i As Integer
        Dim j As Double
        Dim res As Double
        Dim st() As String
        Dim st1() As Char
        Dim count As Integer
        Dim str As String

        j = 4.5
        'MsgBox(Math.Round(j))
        str = j.ToString
        If str.Contains(".") Then
            '   MsgBox("y")
            st = str.Split(".")
            For count = 0 To st.Length - 1

            Next
            Dim temp As Integer
            st1 = st(1).ToCharArray
            temp = CInt(st(0))
            If temp Mod 2 = 0 And st(1) = "5" Then
                i = CInt(j)
                i = i + 1
                'ElseIf temp Mod 2 = 0 And st1(0) = "4" And st1(1) = "9" Then
                '    i = CInt(j)
                '    i = i + 1

            Else
                i = Math.Round(j)
            End If
        Else
            ' MsgBox("n")
            i = Math.Round(j)
        End If

      

    
        MsgBox(i.ToString)


    End Sub

Sunday, August 22, 2010

My Remote Desktop

Hello guys,
Remote Desktop screen shot

 
HOW TO MAKE IT......


CODE BEHIND....
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MSTSCLib;

namespace SampleRDC
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                rdp.Server = txtServer.Text;
                rdp.UserName = txtUserName.Text;

                IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
                secured.ClearTextPassword = txtPassword.Text;
                rdp.Connect();
            }
            catch (Exception Ex)
            {
                MessageBox.Show("Error Connecting", "Error connecting to remote desktop " + txtServer.Text + " Error:  " + Ex.Message,MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                // Check if connected before disconnecting
                if (rdp.Connected.ToString() == "1")
                    rdp.Disconnect();
            }
            catch (Exception Ex)
            {
                MessageBox.Show("Error Disconnecting", "Error disconnecting from remote desktop " + txtServer.Text + " Error:  " + Ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

Silverlight webcam Demo

Hello guys,
Please visit this http://www.silverlightshow.net/items/Capturing-the-Webcam-in-Silverlight-4.aspx
Fantastic Demo