Monday, November 28, 2016

Bubble Sort in Collection VBA

'Sorting Collection in VBA
    For l = 1 To mycoll1.Count - 1
           'MsgBox mycoll1(l)
            For m = l + 1 To mycoll1.Count
                       
            If (IsNumeric(Mid(mycoll1(l), 1, 2))) And (IsNumeric(Mid(mycoll1(m), 1, 2))) Then
                    If CInt(Mid(mycoll1(l), 1, 2)) > CInt(Mid(mycoll1(m), 1, 2)) Then
                     'store the lesser item
                         mycoll1temp = mycoll1(m)
                     'remove the lesser item
                         mycoll1.Remove m
                      're-add the lesser item before the
                    'greater Item
                         mycoll1.Add mycoll1temp, mycoll1temp, l
                     End If
            ElseIf (IsNumeric(Mid(mycoll1(l), 1, 2))) And (IsNumeric(Mid(mycoll1(m), 1, 1))) Then
                    If CInt(Mid(mycoll1(l), 1, 2)) > CInt(Mid(mycoll1(m), 1, 1)) Then
                     'store the lesser item
                         mycoll1temp = mycoll1(m)
                     'remove the lesser item
                         mycoll1.Remove m
                      're-add the lesser item before the
                    'greater Item
                         mycoll1.Add mycoll1temp, mycoll1temp, l
                     End If
            ElseIf (IsNumeric(Mid(mycoll1(l), 1, 1))) And (IsNumeric(Mid(mycoll1(m), 1, 2))) Then
                    If CInt(Mid(mycoll1(l), 1, 1)) > CInt(Mid(mycoll1(m), 1, 2)) Then
                     'store the lesser item
                         mycoll1temp = mycoll1(m)
                     'remove the lesser item
                         mycoll1.Remove m
                      're-add the lesser item before the
                    'greater Item
                         mycoll1.Add mycoll1temp, mycoll1temp, l
                        
                     End If
            ElseIf (IsNumeric(Mid(mycoll1(l), 1, 1))) And (IsNumeric(Mid(mycoll1(m), 1, 1))) Then
                    If CInt(Mid(mycoll1(l), 1, 1)) > CInt(Mid(mycoll1(m), 1, 1)) Then
                     'store the lesser item
                         mycoll1temp = mycoll1(m)
                     'remove the lesser item
                         mycoll1.Remove m
                      're-add the lesser item before the
                    'greater Item
                         mycoll1.Add mycoll1temp, mycoll1temp, l
                        
                     End If
           
            End If
            Next
           
    Next

Sunday, November 13, 2016

Friday, November 11, 2016

MOD Function

http://www.get-digital-help.com/2014/06/03/learn-how-the-mod-function-works/

Moving Average Chart

http://www.get-digital-help.com/2015/11/03/follow-stock-market-trends-moving-average/

Tuesday, November 8, 2016

Updating Data Using Cursor in VBA

Option Private Module
Option Explicit
Dim conn As ADODB.Connection, dateval As String, day As String, month As String, Yr As String
Dim empCode As String
Dim rst As ADODB.Recordset, querystring, i As Integer, rowcount As Long

Sub updateempDetailsForOracle()
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
dateval = ThisWorkbook.Sheets(1).Range("A1")
empCode = ThisWorkbook.Sheets(1).Range("A2")
If InStr(Mid(dateval, 1, 2), "/") > 0 Then
        day = Mid(dateval, 1, 1)
        month = Mid(dateval, 3, 1)
        Yr = Mid(dateval, 5, 4)
Else
        day = Mid(dateval, 1, 2)
        month = Mid(dateval, 4, 2)
        Yr = Mid(dateval, 7, 4)

End If

querystring = "update empDetails set empDOJ=" & Chr(39) & Yr & "-" & month & "-" & day & Chr(39) & " where empCode=" & empCode
i = 1
rowcount = ThisWorkbook.Sheets(1).Range("B" & Rows.Count).End(xlUp).Row
If (rowcount > 1) Then
        ThisWorkbook.Sheets(1).Range("A2:B" & rowcount).ClearContents
End If
    conn.ConnectionString = "Data Source=empDetails;Initial Catalog=dbMentorMenteedetails;uid="*";pwd="*"
    conn.CursorLocation = adUseServer
    conn.Open
    rst.Open querystring, conn, adOpenDynamic
       
        conn.Close
        Set rst = Nothing
        Set conn = Nothing
End Sub

Check Directory Exists If Not Create

Dim pathname As String, tripid As String, respCreate
Sub ChecknCreateDirectory()
tripid = "12"
pathname = "C:\Users\" & Environ("username") & "\Google Drive\" & tripid
   If (Len(Dir(pathname, vbDirectory)) = 0) Then
         rspCreate = MsgBox("Directory doesn't exist, do you wish to create it?", vbYesNo)
            If (rspCreate = vbYes) Then
                MkDir "C:\Users\" & Environ("username") & "\Google Drive\" & tripid
            End If
    End If
End Sub

Monday, November 7, 2016

Create Pivot Table Using CTE

http://sqlmag.com/t-sql/create-pivoted-tables-3-steps

CTE

Extracting Data using Cursor in VBA

Option Private Module
Option Explicit
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset, querystring, i As Integer, rowcount As Long
'get employeelis for Oracle Domain
Sub getempDetailsForOracle()
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
querystring = "Select tbemp.empCode,tbemp.empName from empDetails tbemp join tbldomainList tbdom on " _
& "tbemp.empDomainId=tbdom.domainId  where tbdom.domainId=8"
i = 1
rowcount = ThisWorkbook.Sheets(1).Range("B" & Rows.Count).End(xlUp).Row
If (rowcount > 1) Then
        ThisWorkbook.Sheets(1).Range("A2:B" & rowcount).ClearContents
End If
    conn.ConnectionString = "Data Source=empDetails;Initial Catalog=*;uid=*;pwd=*"
    conn.CursorLocation = adUseClient
    conn.Open
    rst.Open querystring, conn, adOpenStatic
        Do While Not rst.EOF
        i = i + 1
             ThisWorkbook.Sheets(1).Range("A" & i) = rst.Fields(0).Value
             ThisWorkbook.Sheets(1).Range("B" & i) = rst.Fields(1).Value
                rst.MoveNext
        Loop
        rst.Close
        conn.Close
        Set rst = Nothing
        Set conn = Nothing
End Sub

Setting SQL Server 2008 Authentication New Login

Create a Login for SQL Server 2008

get ServerName in SQL

SELECT @@SERVERNAME;

Saturday, November 5, 2016

Create Custom Events using Withevents in VBA

WithEvents specifies that one or more declared member variables refer to an instance of a'
class that can raise events. WithEvents connects the event system to the  variable and
lets you utilize the events of the object.

In this example; we have raised cellSelect event. On selection of value in "A1"; we can
get cell name, cell address, colorindex and cell content in column B,C,D,E.

Steps:
 1.Declare a variable with  WithEvents and classname in Sheet where we need to raise
events.

 2.Write attributes and methods in a class, There are three attributes, for selecting
range, cell name, &set color and one method for setting color in selected range.

3.Declare 3 variables for three attributes for selected range, color and name.

4.Declare an event cellSelect.

5.RaiseEvent inside set property for selected Range.

6.Write a method named methodColor for assigning colorindex to a selected cell.


              Dim rngVar As Range
              Dim intColor As Integer
              Dim strName As String
              Public Event cellSelect(cell As Range)
   Public Property Set selectedRng(objVar As Range)
            Set rngVar = objVar
            RaiseEvent cellSelect(rngVar)
   End Property
   Public Property Get selectedRng() As Range
          Set selectedRng = rngVar
   End Property

  Public Property Let Name(objName As String)
         strName = objName
  End Property
  Public Property Get Name() As String
         Name = strName
  End Property

  Public Property Let Color(objColor As Integer)
        intColor = objColor
  End Property
  Public Property Get Color() As Integer
         Color = intColor
  End Property
  Sub methodColor()
        selectedRng.Interior.ColorIndex = Color
  End Sub


7.Now write an event procedure rng_cellSelect

8.Now assign  selected Range under Private Sub
  Worksheet_SelectionChange(ByVal Target As Range)




Private WithEvents rng As clsWithEvents
Dim i As Integer
Private Sub rng_cellSelect(cell As Range)
    rng.Color = 24
    If (rng.Color < 1) And (rng.Color > 56) Then
            MsgBox "Error! please enter a color index between 1 and 56"
    End If
        rng.Name = "First Cell"
        rng.methodColor
        rng.selectedRng.Select
        i = rng.Color
        Selection.Offset(0, 1).Value = "Name: " & rng.Name
        Selection.Offset(0, 2).Value = "Address:  " & Selection.Address
        Selection.Offset(0, 3).Value = "Interior color Index:  " & i
        Selection.Offset(0, 4).Value = "Cell Content  " & Selection.Value
       
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        Set rng = New clsWithEvents
       
            If (Target.Address = Range("A1").Address) Then
                Set rng.selectedRng = Target
           
           
            End If
End Sub
Download File

Sunday, October 23, 2016

Extract Data from MS Access 2010 to Excel using ADODB Connection

Option Explicit
Dim conn As ADODB.Connection, i As Integer
Dim rst As ADODB.Recordset, querystring As String
Sub accesData()
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
i = 1
querystring = "Select [Order Id], sum(([Unit Price]*Quantity))  as Sales  from [Order Details] group  by [Order Id]"
conn.ConnectionString = "Provider=Microsoft.Access.OLEDB.10.0;Persist Security Info=False;Data Source=somu"
conn.Open
conn.CursorLocation = adUseClient
rst.Open querystring, conn, adOpenStatic
    Do While Not rst.EOF
        ThisWorkbook.Sheets(1).Range("A" & (i + 1)) = rst.Fields(0).Value
        ThisWorkbook.Sheets(1).Range("B" & (i + 1)) = rst.Fields(1).Value
        rst.MoveNext
        i = i + 1
    Loop
rst.Close
conn.Close
Set rst = Nothing
Set conn = Nothing
End Sub


Download Excel

Sample Database


Thursday, October 20, 2016

Create and Populate ListBox from MSSQL Database

Set conn = New ADODB.Connection
    Set rst = New ADODB.Recordset
   
    conn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=.;Initial Catalog=CourseMasterDB;"
    conn.Open
    querystring = "Select GeoName from MST_Geo"
    i = 0
    k = 3
   
           
            rst.Open querystring, conn, adOpenStatic
            ReDim geoArray(rst.RecordCount)
            Do While Not rst.EOF
            geoArray(i) = rst.Fields(0).Value
            rst.MoveNext
            i = i + 1
            Loop
   
            rst.Close
            conn.Close
            Set rst = Nothing
            Set conn = Nothing
           For k = 3 To ThisWorkbook.Sheets.Count
                            Set lookuprng = ThisWorkbook.Sheets(k).Columns("J:J").Find("Select GEO", LookIn:=xlValues, lookat:=xlWhole)
                            If (Not lookuprng Is Nothing) Then
                             ThisWorkbook.Sheets(k).Range(lookuprng.Address).ClearContents
                             ThisWorkbook.Sheets(k).Range(lookuprng.Offset(0, 1).Address).Validation.Delete
                            End If
                            rowcount = ThisWorkbook.Sheets(k).Range("J" & Rows.Count).End(xlUp).Row
                            ThisWorkbook.Sheets(k).Range("J" & (rowcount + 15)) = "Select GEO"
                            ThisWorkbook.Sheets(k).Range("J" & (rowcount + 15)).FontSize = 15
                            ThisWorkbook.Sheets(k).Range("J" & (rowcount + 15)).Interior.ColorIndex = 24
                         With ThisWorkbook.Sheets(k).Range("K" & (rowcount + 15)).Validation
                             .Delete
                             .Add Type:=xlValidateList, Formula1:=Join(geoArray, ",")
                             .InCellDropdown = True
                             .InputTitle = ""
                             .ErrorTitle = ""
                             .InputMessage = ""
                             .ErrorMessage = ""
                             .ShowInput = True
                             .ShowError = True
                        End With

Add Form Control CheckBox in VBA

objrng.Offset(k, 0) = rst.Fields(0).Value
                'add check box
                ThisWorkbook.Sheets(shtcnt).CheckBoxes.Add(Left:=objrng.Offset(k, 1).Left, Top:=objrng.Offset(k, 1).Top, Width:=objrng.Offset(k, 1).Width, Height:=objrng.Offset(k, 1).Height).Select
                ThisWorkbook.Sheets(shtcnt).Range(objrng.Offset(k, 1).Address).NumberFormat = ";;;"
                With Selection
               
                    .Caption = ""
                    .Name = ""
               
                    .LinkedCell = objrng.Offset(k, 1).Address
                End With

Wednesday, October 19, 2016

Using ShellExecute to open an .exe File

Public Declare Function ShellExecute _
    Lib "shell32.dll" _
        Alias "ShellExecuteA" ( _
            ByVal Hwnd As Long, _
            ByVal lpOperation As String, _
            ByVal lpFile As String, _
            ByVal lpParameters As String, _
            ByVal lpDirectory As String, _
            ByVal nShowCmd As Long) _
As Long
Sub my_Procedure()
pathname = "C:\Program Files (x86)\TechSmith\Camtasia Studio 8\CamRecorder.exe"


'ThisWorkbook.Windows(1).WindowState = xlMinimized
procId = ShellExecute(0, "Open", pathname, vbNullString, "C:\", SW_SHOWNORMAL)
Application.Wait (Now + TimeValue("00:00:03"))
'AppActivate procId
Application.SendKeys ("{F9}"), True


end Sub

Wednesday, October 12, 2016

Select Query with Case

Select t3.LocationName, t1.CourseSDate,t1.CourseEDate,
CASE WHEN GI.CorporateId = 0 THEN GI.CompanyName ELSE CO.CORPORATENAME END AS ComapyName , ' ' as Venue from TRAN_SCINTERESTEDCOURSES t1
INNER JOIN TRAN_SCGENERALINFO GI ON T1.StudnetCardId = GI.StudnetCardId
 left JOIN MST_LOCATION t3 on t3.LocationId=t1.LocationId
 LEFT JOIN MST_CORPORATEDETAIL CO ON CO.CORPORATEID = GI.CorporateId where T1.StudnetCardId=4127

Wednesday, September 21, 2016

Populating ComboBox from SQl ResultSet

querystring = "Select AccomodationName from MST_ONSITEACCOMMODATION where CityName=" & Chr(39) & cityname & Chr(39)
                    conn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=.;Initial Catalog=Test;"
                    conn.Open
                    rst.Open querystring, conn, adOpenStatic
                    With ComboBox7
                                .Clear
                                    Do While Not rst.EOF
                                       .AddItem rst![AccomodationName]
                                                   
                                        rst.MoveNext
                                    Loop
                    End With
                                       
                    rst.Close
                    conn.Close
                    querystring = vbNullString
                    Set rst = Nothing
                    Set conn = Nothing

Sunday, September 11, 2016

Extract Data Using Select Query in VBA

Option Explicit

Dim conn As New ADODB.Connection, querystring As String, blockname As String, hadoopblockrowcount As Long
Dim rst As New ADODB.Recordset

Sub extractData()
blockname = Application.InputBox("Please Mention Block Name to be Created")
querystring = "Select t1.Cid,t1.CName,t1.PSName,t1.StDuration,t2.CourseExamId from MST_COURSE t1"
querystring = querystring & " join LNK_COURSE_EXAM t2 on t1.CId=t2.courseid"
querystring = querystring & " where t1.CId in(Select distinct CourseId from Lnk_COURSE_VENDOR where VendorId=32)and PSName is not null"
querystring = querystring & " Union Select t1.Cid, t1.CName,t1.PSName,t1.StDuration,null from MST_COURSE t1"
querystring = querystring & " where t1.CId in(Select distinct CourseId from Lnk_COURSE_VENDOR where VendorId=32)and PSName is not null;"

hadoopblockrowcount = 3
Application.ScreenUpdating = False
    conn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=.;Initial Catalog=CourseMasterDB;"
    conn.Open
    rst.Open querystring, conn, adOpenStatic
    Do While Not rst.EOF
    hadoopblockrowcount = hadoopblockrowcount + 1
    ThisWorkbook.Sheets(1).Range("A" & (hadoopblockrowcount)) = rst.Fields(0).Value
    ThisWorkbook.Sheets(1).Range("B" & (hadoopblockrowcount)) = rst.Fields(1).Value
    ThisWorkbook.Sheets(1).Range("C" & (hadoopblockrowcount)) = rst.Fields(2).Value
                If (rst.Fields(4).Value <> vbNullString) Then
                        ThisWorkbook.Sheets(1).Range("E" & (hadoopblockrowcount)) = "Y"
                Else
                        ThisWorkbook.Sheets(1).Range("E" & (hadoopblockrowcount)) = "N"
                End If
    ThisWorkbook.Sheets(1).Range("G" & (hadoopblockrowcount)) = rst.Fields(3).Value
        rst.MoveNext
    Loop
   
    rst.Close
    conn.Close
    Set rst = Nothing
    Set conn = Nothing
   
End Sub

Wednesday, August 31, 2016

Trim Entire Column in VBA

Sub TrimCol()
    Dim r As Range
    Set r = Intersect(Range("A1").EntireColumn, ActiveSheet.UsedRange)
    r.Value = Evaluate("IF(ROW(" & r.Address & "),IF(" & r.Address & "<>"""",TRIM(" & r.Address & "),""""))")
End Sub

Copy Range to Array

Dim myArray()
Sub copyRange2Array()
myArray = ThisWorkbook.Sheets(1).Range("A1:A4").Value
For i = 1 To UBound(myArray)
    MsgBox myArray(i, 1)
Next
End Sub

Tuesday, August 9, 2016

Finding Next Blank Row no in VBA

Sub test()
Dim myrng As Range
Set myrng = Range(ThisWorkbook.Sheets(1).Range("A1").Offset(0, 0), ThisWorkbook.Sheets(1).Range("A1").Offset(0, 0).End(xlDown))
MsgBox myrng.Rows.Count + 1
End Sub

Thursday, July 28, 2016

VBA code for autofilter on the basis of Color

keywordsmasterfile.Sheets(1).Range("A2:B2").AutoFilter field:=1, Criteria1:=RGB(204, 153, 255), Operator:=xlFilterCellColor

Saturday, June 25, 2016

Types of Cursor in MSSQL

SQL Server Different Types of Cursors

           
A Cursor allow us to retrieve data from a result set in singleton fashion means row by row. Cursor are required when we need to update records in a database table one row at a time. I have already explained the basic of cursor.
A Cursor impacts the performance of the SQL Server since it uses the SQL Server instances' memory, reduce concurrency, decrease network bandwidth and lock resources. Hence it is mandatory to understand the cursor types and its functions so that you can use suitable cursor according to your needs.
You should avoid the use of cursor. Basically you should use cursor alternatives like as WHILE loop, sub queries, Temporary tables and Table variables. We should use cursor in that case when there is no option except cursor.

Friday, June 17, 2016

Install Window Service Programmitcally

You can do it all in one executable. To pass installation parameters, you will need to derive classes System.ServiceProcess.ServiceProcessInstaller and System.ServiceProcess.ServiceInstaller. You only need to implement constructors of your classes.

Installation and uninstallation will be done by System.Configuration.Install.AssemblyInstaller. This class should use the assembly where the classes based on ServiceProcessInstaller and ServiceInstaller are implemented; the implementation will be found in your assembly automatically (which would create a hard-to-detect failure if you have a bug in the implementation). Not too bad though.

Finally, start/stop, etc. are handled by your service code which you create deriving the class System.ServiceProcess.ServiceBase. Triggering this actions is done by Service Controller. To do it programmatically you should use the class System.ServiceProcess.ServiceController.

You need to have a good reading of MSDN on the topics around the classes I listed above, which is well illustrated by code samples. This information is easy to find, a bit harder to understand the work flow and what happens in which process. (A Windows Service process is always a separate one; it takes another process to run installation and Service Controller part.) You can use all this like a cookbook, but I suggest you thoroughly understand it; in this case you won't have any problems.

You can even try to implement it all in one application as I did, but you still need to run it in at least two different processes: one would work in the Windows Service mode, another is must be interactive mode, which can be anything else, such as UI, Console or just invisible batch-mode application.

Important! You code can test System.Environment.UserInteractive during run time to calculate is currently running code is run as Windows Service or not.

Add Installer for Window Service

In the service project do the following:
  1. In the solution explorer double click your services .cs file. It should bring up a screen that is all gray and talks about dragging stuff from the toolbox.
  2. Then right click on the gray area and select add installer. This will add an installer project file to your project.
  3. Then you will have 2 components on the design view of the ProjectInstaller.cs (serviceProcessInstaller1 and serviceInstaller1). You should then setup the properties as you need such as service name and user that it should run as.

Start window Servicesin C#.Net

Develop & Install window Service in C#

Sunday, June 12, 2016

Looping through resutset in Table Valued Function

Database CASKoenigDB

alter function [dbo].[getFullMonthforRC](@TrainerID int,@CourseSDate datetime,@CourseEDate datetime,@LocationId int,@weekendstatus varchar(30),@courselist nvarchar(max)) 
returns  @TableofDates table(TrainerID int not null,trngdate datetime not null,locationid int not null) 
Begin 
declare @trnid int 
declare @lnid int 
Declare @startDate datetime 
declare @weekendbatch varchar(30)
Declare @interestedCourses nvarchar(max)
Declare @excluddates  datetime  
Declare @dateval  datetime
Declare @Count int
Declare @Loopcount int
Declare @endDate datetime
set @trnid=@TrainerID 
set @startDate=@CourseSDate 
 
set @endDate=@CourseEDate 
set @lnid=@LocationId 
set @weekendbatch=@weekendstatus 
set @interestedCourses=@courselist
  While (@startDate<=@endDate) begin
  if exists(Select  cast (ExcludedDate as nvarchar(max))  from TRAN_EXCLUDEDAY where InterestedCourseId=@interestedCourses)
  begin
  --counting total records
   Select @Count=count(*) from dbo.Split ( (Select  cast (ExcludedDate as nvarchar(max))  from TRAN_EXCLUDEDAY where InterestedCourseId=@interestedCourses),';')
   Set @Loopcount=1
   While  @Loopcount<=@Count
   begin
    Select @dateval=items from( Select *,ROW_NUMBER()over(Order by items)ID from dbo.Split ( (Select  cast (ExcludedDate as nvarchar(max))  from TRAN_EXCLUDEDAY where InterestedCourseId=@interestedCourses),';') ) RC where ID=@Loopcount 
   
    Set @Loopcount=@Loopcount+1
    if (@dateval=@startDate)  begin
      
       set @startDate=DATEADD(DAY, 1, @startDate)
    end
   
   end
   if  (@startDate<=@endDate) begin
     --print @startDate
     INSERT INTO @TableOfDates(TrainerID,trngdate,locationid) VALUES (@trnid,@startDate,@lnid) 
     set @startDate=DATEADD(DAY, 1, @startDate)
   end
  end
  else if not exists(Select  cast (ExcludedDate as nvarchar(max))  from TRAN_EXCLUDEDAY where InterestedCourseId=@interestedCourses )begin 
    --print @startDate
    INSERT INTO @TableOfDates(TrainerID,trngdate,locationid) VALUES (@trnid,@startDate,@lnid) 
    set @startDate=DATEADD(DAY, 1, @startDate)
  end 
end   
  
return 
End 

Saturday, June 11, 2016

Looping through resultset without using cursor

Database:CasKoenigDB

Declare @dateval as datetime

Declare @Count int

Declare @Loopcount int

Select IDENTITY(int, 1,1) ID,items into #Temp from dbo.Split ( (Select cast (ExcludedDate as nvarchar(max)) from TRAN_EXCLUDEDAY where InterestedCourseId=1707),';')

Select @Count=@@ROWCOUNT

Set @Loopcount=1

While @Loopcount<=@Count

begin

Select @dateval=items from #Temp where ID=@Loopcount

Set @Loopcount=@Loopcount+1

print @dateval



end
 
Drop table #Temp

Thursday, June 9, 2016

SQL query using Union All in pivottable

/****** Script for SelectTopNRows command from SSMS  ******/
DECLARE @TrainerID INT
DECLARE @CourseSDate DATETIME
DECLARE @CourseEDate DATETIME
DECLARE @LocationId INT
Declare @batchstatus varchar(30)
create TABLE #tbl1 (TrainerID INT,trngdate DATETIME, locationid INT)
DECLARE LDates CURSOR
FOR

SELECT mtt.TrainerID,TRAN_SCINTERESTEDCOURSES.coursesdate,TRAN_SCINTERESTEDCOURSES.courseedate,TRAN_SCINTERESTEDCOURSES.LocationId,TRAN_SCINTERESTEDCOURSES.tscheduletype as BatchStatus from TRAN_SCINTERESTEDCOURSES
join MST_LOCATION on TRAN_SCINTERESTEDCOURSES.LocationId = MST_LOCATION.LocationId
right outer join MST_TRAINER mtt on mtt.TrainerID=  TRAN_SCINTERESTEDCOURSES.TrainerId and TRAN_SCINTERESTEDCOURSES.TrainerId IS NOT NULL
where
  CONVERT(datetime,'2016-05-01')
        between DATEADD(month, DATEDIFF(month, 0, coursesdate), 0)
            and DATEADD(month, DATEDIFF(month, 0, courseedate), 0) ORDER BY CourseSDate
           
OPEN LDates
FETCH NEXT FROM LDates
INTO @TrainerID,@CourseSDate,@CourseEDate,@LocationId ,@batchstatus
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO #tbl1

SELECT TrainerID ,trngdate,locationid FROM getFullMonthforRC(@TrainerID,@CourseSDate,@CourseEDate,@LocationId,@batchstatus)
FETCH NEXT FROM LDates

INTO @TrainerID,@CourseSDate,@CourseEDate,@LocationId,@batchstatus
END
CLOSE LDates
DEALLOCATE LDates

select  EmpId, TrainerName,CASE WHEN [1] > 1 THEN 1 ELSE [1] END AS [1],CASE WHEN [2] > 1 THEN 1 ELSE [2] END AS [2],CASE WHEN [3] > 1 THEN 1 ELSE [3] END AS [3],CASE WHEN [4] > 1 THEN 1 ELSE [4] END AS [4],CASE WHEN [5] > 1 THEN 1 ELSE [5] END AS [5],CASE WHEN [6] > 1 THEN 1 ELSE [6] END AS [6],CASE WHEN [7] > 1 THEN 1 ELSE [7] END AS [7],CASE WHEN [8] > 1 THEN 1 ELSE [8] END AS [8],CASE WHEN [9] > 1 THEN 1 ELSE [9] END AS [9],CASE WHEN [10] > 1 THEN 1 ELSE [10] END AS [10],CASE WHEN [11] > 1 THEN 1 ELSE [11] END AS [11],CASE WHEN [12] > 1 THEN 1 ELSE [12] END AS [12],CASE WHEN [13] > 1 THEN 1 ELSE [13] END AS [13],CASE WHEN [14] > 1 THEN 1 ELSE [14] END AS [14],CASE WHEN [15] > 1 THEN 1 ELSE [15] END AS [15],CASE WHEN [16] > 1 THEN 1 ELSE [16] END AS [16],CASE WHEN [17] > 1 THEN 1 ELSE [17] END AS [17],CASE WHEN [18] > 1 THEN 1 ELSE [18] END AS [18],CASE WHEN [19] > 1 THEN 1 ELSE [19] END AS [19],CASE WHEN [20] > 1 THEN 1 ELSE [20] END AS [20],CASE WHEN [21] > 1 THEN 1 ELSE [21] END AS [21],CASE WHEN [22] > 1 THEN 1 ELSE [22] END AS [22],CASE WHEN [23] > 1 THEN 1 ELSE [23] END AS [23],CASE WHEN [24] > 1 THEN 1 ELSE [24] END AS [24],CASE WHEN [25] > 1 THEN 1 ELSE [25] END AS [25],CASE WHEN [26] > 1 THEN 1 ELSE [26] END AS [26],CASE WHEN [27] > 1 THEN 1 ELSE [27] END AS [27],CASE WHEN [28] > 1 THEN 1 ELSE [28] END AS [28],CASE WHEN [29] > 1 THEN 1 ELSE [29] END AS [29],CASE WHEN [30] > 1 THEN 1 ELSE [30] END AS [30],CASE WHEN [31] > 1 THEN 1 ELSE [31] END AS [31]
from
(SELECT distinct t1.EmpId,t1.TrainerName,t2.LocationName, Day(#tbl1.trngdate)as CourseDate FROM #tbl1  join MST_TRAINER t1
on #tbl1.TrainerID=t1.TrainerId LEFT Join MST_LOCATION t2 on t2.LocationId=#tbl1.locationid where t1.EmpId is not null  AND MONTH(#tbl1.trngdate)='05' ) RC
Pivot
(
COUNT(LocationName) for CourseDate in([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
)as Pivottable
union all
(SELECT EmpId, TrainerName,0 as [1],0 as [2],0 as [3],0 as [4],0 as [5],0 as [6],0 as [7],0 as [8],0 as [9],0 as [10],0 as [11],0 as [12],0 as [13],0 as [14],0 as [15],0 as [16],0 as [17],0 as [18],0 as [19],0 as [20],0 as [21],0 as [22],0 as [23],0 as [24],0 as [25],0 as [26],0 as [27],0 as [29],0 as [29],0 as [30],0 as [31]  from MST_TRAINER where isactive=1 and trainerid not in
(SELECT mtt.TrainerID from TRAN_SCINTERESTEDCOURSES
right outer join MST_TRAINER mtt on mtt.TrainerID=  TRAN_SCINTERESTEDCOURSES.TrainerId and TRAN_SCINTERESTEDCOURSES.TrainerId IS NOT NULL
where
  CONVERT(datetime,'2016-05-01')
        between DATEADD(month, DATEDIFF(month, 0, coursesdate), 0)
            and DATEADD(month, DATEDIFF(month, 0, courseedate), 0) ) and EmpId is not null   )
Drop table #tbl1

Wednesday, June 8, 2016

Recursive CTEs in AdventureWorks 2008

With myCTE(BusinessEnityID,ManagerId,lv)

As(

Select BusinessEntityID,ManagerId,1 From HumanResources.Employee

where ManagerID is null

union all

Select e.BusinessEntityID, e.ManagerId, lv+1 from HumanResources.Employee e

join myCTE on e.ManagerID=myCTE.BusinessEnityID



)
 
Select emp.BusinessEntityID,emp.JobTitle, c.FirstName+' '+C.LastName as [Name],

M.FirstName+'' +M.LastName as [Manager],lv

from HumanResources.Employee emp

join myCTE

on emp.BusinessEntityID=myCTE.BusinessEnityID

join Person.Person as C

on c.BusinessEntityID=emp.BusinessEntityID

Left Join Person.Person as M

on emp.ManagerID=M.BusinessEntityID order by lv

Pivot Example using a CTE

use AdventureWorks2008
GO
-- First we'll retrieve Orders from 2003 and place into a CTE
WITH OrdCTE AS (
SELECT VendorID, Name As VendorName,  DatePart(m,OrderDate) AS OrderMonth, POHdr.TotalDue
FROM Purchasing.PurchaseOrderHeader POHdr
join Purchasing.Vendor ON Vendor.BusinessEntityID = POHdr.VendorID
where YEAR(OrderDate) = 2003
)   
-- Now we'll query the CTE, and use a PIVOT statement           
SELECT VendorID, VendorName, [1] AS Jan,[2] AS Feb,[3] AS Mar,[4] AS Apr, 
 [5] AS May, [6] AS June, [7] AS July, [8] AS Aug, 
 [9] AS Sep, [10] AS Oct, [11] AS Nov, [12] AS Dec
FROM OrdCTE
-- we take each of the 12 possible values and associate them with 12 buckets
PIVOT (SUM(TotalDue) FOR OrderMonth IN ([1],[2],[3],[4],
 [5], [6], [7], [8],           
 [9], [10], [11], [12]))  as TempList

Query for Multiple CTEs

With CTE1 AS (

Select ProductID,sum(OrderQty) as TotalOrderQty from Sales.SalesOrderDetail

group by ProductID



),
CTE2 as(

Select p.ProductID,pc.ProductCategoryID, pc.Name from Production.Product p join Production.ProductSubcategory psc

on psc.ProductSubcategoryID=p.ProductSubcategoryID

join Production.ProductCategory pc

on pc.ProductCategoryID=psc.ProductCategoryID



)
Select * from (

Select CTE2.ProductCategoryId,CTE2.Name,CTE1.ProductId,CTE1.TotalOrderQty,

rn=ROW_NUMBER() over( PARTITION by CTE2.ProductCategoryId order by CTE1.TotalOrderQty desc)

from CTE1 join CTE2 on cte1.ProductID=cte2.ProductID

) CTE where rn<=3

Tuesday, June 7, 2016

Function in sql for removing weekend

ALTER Function [dbo].[calculateTotalTestData11](@interestCourseId int)   
returns nvarchar(max) --@temptable TABLE (dates datetime)      
AS   
BEGIN  
DECLARE @stDate DateTime;
DECLARE @endDate DateTime;
DECLARE @Location int;
SELECT @stDate=CourseSDate,@endDate=CourseEDate,@Location=LocationId from TRAN_SCINTERESTEDCOURSES where InterestedCourseId=@interestCourseId;
DECLARE @temptable table(dates datetime) ;
; WITH CTE(dt) 
 AS 
 (  
 SELECT @stDate 
 UNION ALL 
 SELECT DATEADD(D,1,dt) FROM CTE 
 where dt < @endDate 
 ) 
  insert into @temptable(dates) 
 select dt  from CTE where (CASE WHEN @location = 5  
 THEN (CASE WHEN DATENAME(dw, dt) = 'FRIDAY' THEN 1 ELSE 0 END)  
 ELSE  ( 
 CASE WHEN @location = 8 OR @location = 9
 THEN ((CASE WHEN DATENAME(dw, dt) = 'SATURDAY' OR  DATENAME(dw, dt) = 'SUNDAY'  THEN 1 ELSE 0 END)) 
 ELSE (CASE WHEN DATENAME(dw, dt) = 'Sunday' THEN 1 ELSE 0 END)  END) 
 END )=1 and dt <> @stDate and dt <>@endDate;
  
 return   STUFF((SELECT DISTINCT '; ' + CONVERT(nvarchar(11),dates,113) FROM @temptable FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')


END

Query for Specific Date Falling between Date Range

SELECT TRAN_SCINTERESTEDCOURSES.TrainerId,TRAN_SCINTERESTEDCOURSES.coursesdate,TRAN_SCINTERESTEDCOURSES.courseedate,TRAN_SCINTERESTEDCOURSES.LocationId,MST_LOCATION.LocationName from TRAN_SCINTERESTEDCOURSES  
inner join MST_LOCATION on TRAN_SCINTERESTEDCOURSES.LocationId = MST_LOCATION.LocationId where TrainerId is not null
and     CONVERT(datetime,'2016-05-01')
        between DATEADD(month, DATEDIFF(month, 0, CourseSDate), 0)
            and DATEADD(month, DATEDIFF(month, 0, CourseEDate), 0)