Thursday, November 17, 2016

Create Manager Hierarchy for Organization in SSMS


Today we will explore on Manager hierarchy level. To do this first we have to create a source table. Let’s assume the source table having columns with following data.


Create Script:

CREATE TABLE [dbo].[ManagerHierarchy](

       [EmpID] [int] NULL,

       [EmpName] [varchar](200) NULL,

       [ManName] [varchar](200) NULL,

       [manID] [int] NULL

) ON [PRIMARY]



GO

SET ANSI_PADDING OFF

GO

INSERT [dbo].[ManagerHierarchy] ([EmpID], [EmpName], [ManName], [manID]) VALUES (1, N'Subhadip', NULL, NULL)

GO

INSERT [dbo].[ManagerHierarchy] ([EmpID], [EmpName], [ManName], [manID]) VALUES (2, N'Pritam', N'Subhadip', 1)

GO

INSERT [dbo].[ManagerHierarchy] ([EmpID], [EmpName], [ManName], [manID]) VALUES (3, N'tanmoy', N'Subhadip', 1)

GO

INSERT [dbo].[ManagerHierarchy] ([EmpID], [EmpName], [ManName], [manID]) VALUES (4, N'Sourav', N'Pritam', 2)

GO

INSERT [dbo].[ManagerHierarchy] ([EmpID], [EmpName], [ManName], [manID]) VALUES (5,
N'Titas', N'Tanmoy', 3)

GO

INSERT [dbo].[ManagerHierarchy] ([EmpID], [EmpName], [ManName], [manID]) VALUES (6, N'Anurag', N'Sourav', 4)

GO




Now we have to format the data from coming from source table. Here we will form the in below format.
Empname, EmpID, ReportsToMan, ReportsToManID, ManPath, EmpLevel




To make above format we have write CTE (Common Table Expression) on top of the source table.
SQL Script:
;WITH EmployeeSet(Empname, EmpID, ReportsToMan, ReportsToManID, ManPath, EmpLevel)
AS
(SELECT
      EmpName,
      EmpID, 
      ManName,
      manID,
      cast((EmpName + ',') as varchar(2000)),
       0
    FROM [ManagerHerarchy] AS e
    WHERE EmpName = 'Subhadip'
    UNION ALL
    SELECT
              e.EmpName,
        e.EmpID,    
        e.ManName,
        e.manID,
           cast(d.ManPath + (e.EmpName + ',') as varchar(2000)),
        d.EmpLevel + 1
       
    FROM [ManagerHerarchy] AS e
              JOIN EmployeeSet AS d ON e.ManID = d.EmpID
)
select * FROM EmployeeSet
Now we have to store the CTE to a Temp table.
SQL Query:
select * into #tempTbl FROM EmployeeSet
Now the challenge is to split the string value of ManPath column and put each value to a column (Ex: level 1, level 2 etc.)
For simplicity, we have to create a function for split.
SQL Script:
CREATE FUNCTION [SplitFunction](@InputStr varchar(max))         
returns @outputtable TABLE (items varchar(max))         
as         
begin         
    declare @idx int   
    declare @Delimiter varchar(max)     
    declare @slice varchar(max)         
    set @Delimiter = ','    
    select @idx = 1         
        if len(@InputStr)<1 or @InputStr is null  return         
       
    while @idx!= 0         
    begin         
        set @idx = charindex(@Delimiter,@InputStr)         
        if @idx!=0         
            set @slice = left(@InputStr,@idx - 1)         
        else         
             set @slice = @InputStr         
            
        if(len(@slice)>0)    
            insert into @outputtable(Items) values(LTRIM(RTRIM(REPLACE(REPLACE(@slice,CHAR(9),''),CHAR(13)+CHAR(10),''))))         
    
        set @InputStr = right(@InputStr,len(@InputStr) - @idx)         
        if len(@InputStr) = 0 break         
    end     
return         
end

Now we have to use this above function to get the string value into column format.
SQL Script:
SELECT EmpName,
       ReportsToMan,
          EmpLevel,
ISNULL((SELECT items FROM (select ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS Position,  items from [dbo].[SplitInputStrToColumn] (A.ManPath)) S where Position = 1)  ,'' )AS Level1,
ISNULL((SELECT items FROM (select ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS Position,  items from [dbo].[SplitInputStrToColumn] (A.ManPath)) S where Position = 2)  ,'' )AS Level2,
ISNULL((SELECT items FROM (select ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS Position,  items from [dbo].[SplitInputStrToColumn] (A.ManPath)) S where Position = 3)  ,'' )AS Level3,
ISNULL((SELECT items FROM (select ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS Position,  items from [dbo].[SplitInputStrToColumn] (A.ManPath)) S where Position = 4)  ,'' )AS Level4
from #tempTbl A

Now we can store the output into Manager Hierarchy Level table.
How does SplitInputStrToColumn work?
First we have look on the Output of SplitInputStrToColumn Function.
Step1:
Select * from [SplitInputStrToColumn] ('Pritam,Das,Kantamoni')
Output:

Step2:
Now our aim should be, put this spitted values into defined columns. First row will move to Level1 Column, second row will move to Level2 Column and so on. To implement like this, we have to apply row number before the output of SplitInputStrToColumn Function.
Select ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as Position ,items from [SplitInputStrToColumn] ('Pritam,Das,Kantamoni')
Output:

Step3:
Based on Position we have to filter the spitted string values.
select Position,items from (Select ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as Position ,items from [SplitInputStrToColumn] ('Pritam,Das,Kantamoni'))b where b.Position=1

Output:

Monday, July 18, 2016

Physical structure of database in MS SQL Server

The physical structure of the database is divided into the MDF, NDF and LDF. We can say Primary Data files, Secondary data files and Log files respectively.

MDF (Primary Data files)
It store data of tables, stored procedures, views, triggers etc. The file name extension for primary data files is .mdf

NDF (Secondary data files)
An NDF file is a user defined secondary database file of Microsoft SQL Server with an extension .ndf, which store tables, stored procedures, views, triggers data. Moreover, when the size of the database file growing automatically from its specified size or we apply partition table, we can use .ndf file for extra storage and the .ndf file could be stored on a separate disk drive.

LDF (Log files)
Log files in SQL Server databases hold all the log information of transactions. Those information can be later used to recover the database in case of any mismanagement. The file name extension for primary data files is .ldf. 


When we create a database, it creates a data file with .mdf extension and log file with .ldf extension. For example if we create a database named “My_Database” in SQL Server then by default  it will create 2 files named “My_Database.mdf” and “My_Database_Log.ldf”.


SQL Server Architecture

Today we will discuss about Microsoft SQL Server architecture. Basically there are 3 components in SQL Server.
  •  Relational Engine (Query Processor)
  •  Storage Engine
  •  SQL Operating System (SQL OS)

Now we will discuss one by one.

Relational Engine (Query Processor)
When we run a query in window, it manages the execution of query. It mean, first check the syntax of query then request the query output data from Storage Engine and next return the result to query output.

Storage Engine
It manage storage and retrieval of the data on to the storage system (Computer Hard Disk) when we create database, schemas, tables, queries, views and other objects in SQL server.

SQL Operating System (SQL OS)

It is software program that is in host machine (Windows OS) and SQL Server. It controls entire SQL Server behavior and activities. It is a configurable operating system and provide Graphical user Interface (SSMS,BIDS,SSRS.SSIS tool).


What is Microsoft SQL Server ?

Microsoft SQL Server is a software application for relational database management system developed by Microsoft. By this application, we can create database server, database, table, schema and run SQL query to fetch the data from database.
Microsoft has released many versions of SQL Server.
  •     SQL Server 200
  •     SQL Server 2008
  •     SQL Server 2008 R2
  •     SQL Server 2012
  •     SQL Server 2014
  •     SQL Server 2016


Microsoft SQL Server  provide some service given below.
  • Analysis Services (SSAS)
  • Reporting Services (SSRS) 
  • Integration Services (SSIS)
  • SQL ServerManagement Studio (SSMS)
  • SQLCMD
  • Business Intelligence Development Studio (BIDS)

What is SQL ?

SQL (Structured Query Language) is a special-purpose programming language designed for managing data held in a relational database management system (RDBMS). It is designed based on relational algebra (Set theorem, Joins).

SQL consists of a data definition language(DDL), data manipulation language(DML), and Data Control Language(DCL).

The Data Definition Language (DDL) manages table and index structure in database. The most basic items of DDL are the CREATE, ALTER, RENAME, DROP and TRUNCATE statements.

The Data Manipulation Language (DML) manages add, update and delete data in database.


The Data Control Language (DCL) authorizes users to access and manipulate data. Its two main statements GRANT and REVOKE.

What is Relational model ?

The relational model (RM) for database management is an approach to  provide details of specific data pulled from various table based on existing relation mentioned between them.

For example, there are 3 tables and they are related by a common column named “Roll No” 

From this model we can get detailed data for Roll No 1 and 2.


A Relational Database is a digital database whose organization is based on the relational model of data.

What is Table ?

A table is a collection of related data held in a structured format within a database. It consists of columns, and rows.