Saturday, 20 May 2017

SSIS - A Basic Demo

Creating SSIS project and getting started

So let’s understand the very first requirement of the project. Goal of this demo is understanding SSIS project basics.

In this Demo we are going to learn, how we can Upload data from a txt file to Sql server database.

We have Customer.txt file as follows. (Make sure you create one and save it somewhere for demo purpose.)


Note: DOB is in “dd/mm/yyyy” format.

First requirement is,loading data from above text file into Customer table in the SSISDB database in Sql server management studio. (Create the database and table in your machine for demo purpose)


Step 1 – Create SSIS project.


Goto File menu and click on New Project Option. 


Select Integration Service Project and click Ok button. (Change the Project name if you want.)


Step 2 – Create New Package

·         In SSIS world Package is an executable file.
·         Visual studio provides a UI interface called SSIS designer for designing packages.
·         Internally package is an XML file which will be executed by special utility called “dtsexec”.This utility will installed as a part of MSBI installation. 
·         Packages will be have an extension called DTSX which stands for “Data transformation services executable”. In earlier version of sql server to perform ETL we had a feature called “Data Transformation services”. DTSX is named after it.
                          
Step 3 – Design Control Flow

Double click the new created package in solution explorer.
As you can see in SSIS designer we have several tabs – Control Flow, Data Flow, Parameters, Event Handlers, and Package Explorer. We will look into each one of these tabs one by one.
Right now we are interested in Control Flow tab.

·         This tab will let us decide what need to be done.
·         You will notice we have SSIS toolbox in left side. If it is not available in your demo then you can get it from View>>Other Windows>>SSIS toolbox.

Toolbox contains tasks like Data Flow Task, Execute Sql Task etc. Each task let us achieve some different behaviour.

·         Right now our requirement asks us to load data from a text file to Sql server database and for that we will be required “DataFlow Task”. Simply drag the task from SSIS toolbox to SSIS designer.
Right click the newly created “Data Flow Task” and select rename. Name it as “CsvCustomer to TblCustomer”.



Step 3 – Add DestinationConnection Manager

Other than all these tabs, SSIS designer also provides something called Connection Managers section. It's located in the bottom Corner of the designer.
Simply right click the area and select “New Ado.Net Connection…”


Click New button

Enter Server Name, Enter Credential, and Select Database and click OK.



Click Ok again.
Rename connection manager if you want.


Step 4 – Add SourceConnection Manager

Now it’s time to add Source Connection Manager.
Right click the connection manager area but this time select “New Flat file Connection...”
It will launch “Flat file Connection manager editor”.


In left side of the dialog couple of sections are defined like General, Columns, and Advanced etc.
Select Columns sections. No need to change any settings at this moment. Simply click Ok.
                          

Step 5 – Configure Data Flow Task

After that double click Data Flow task. It will take you to Data flow tab.


Step 6 –Add Source

Data flow tab is the one which will actually decide ETL. Here we will define, from where to where data will flow and if there is any transformation required or not.
As soon as you move to the Data Flow tab, you will notice a change in the SSIS toolbox.


As you can see, tasks in the toolbox is segregated into three groups – Sources, Transforms and Destinations. “Common” is a special group which contain mostly used sources, transformations and destinations.
We are interested in “Flat file source”. You will find it in “Other Sources” section. Simply drag it to SSIS designer and rename it to “CustomerCsv”

Step 7 – Configure Source
Double click the CustomerCsv source. It will launch “Flat file source editor”. Select “Flat File Connection Manager” from the dropdown.



Move to the column section and make any changes if required and click ok.

Step 8 – Add Destination

Drag Ado.Net destination from “Other Destinations” section to SSIS designer and rename it to “TblCustomer”. 

Step 9 – Configure Destination

Destination task cannot configured unless and until it have a proper input.
Now click the “CustomerCsv” source. You will notice two arrows coming out of it. Blue one and red one. We will talk about red one later. Blue one is the one though which data will flow. Hence this arrow is called as “Data Flow Path”. Take that arrow and connect it to “TblCustomer” destination.



Step 10- Configure Destination (Continued)

Double click the “TblCustomer” destination again. In the “configuration editor window” select Connection manager from dropdown and table to “Customer”



Click on “Mappings” section and confirm that all mappings are correct.



Click ok.

Step 11- Execute and Test the package

As I said sometime back, Package will be executed by a special utility called “DtsExec.exe”. Visual studio makes our life easy at the time of development. For testing simply press F5 ☻ everything else will be handled by Visual studio and package start executing.


Open database table and check the records.


Finally achieved.☻☻☻

Continue Reading →

Monday, 15 May 2017

MSBI (SSIS)

What is Data Warehouse?
In a very simple word it means, “It's a place where we store all of our data”.

How it is different from Database?
Usually data warehouse is also a database. The records from multiple data sources (may be some other databases)are collected and stored in Denormalized manner. It normally stores months or years of data to support historical analysis

What is Denormalization?
Normalization is a database designing technique which makes sure that there will not be any redundant data.
It makes our data more reliable (because there will not be any repeating data. Exiting data will be referred wherever required)
It makes database management easy.
It reduces the size of database.

What is Business Intelligence?
BI is all about leveraging our existing data and converting them into information or we can say Knowledge. We use this knowledge for making decisions in company.

BI or Business Intelligence is simply a solution for
Collect information from multiple data sources
Transform that data into meaningful information
And finally show data to users with elegant presentation.

Introduction to Business Intelligence development studio / Sql Server Data tools
In the Microsoft world we will use “Business Intelligence development studio” commonly known as BIDS for this purpose.

It’s an IDE which will let us develop Data Analysis and Business Intelligence solutions.
It has special project types and tools for developing “Sql server Integration Services”, “Sql server Analysis services” and “Sql server reporting services”.
With the release of Sql Server 2012, BIDS was renamed to Sql Server Data tools.


Basic idea on SSIS, SSAS and SSRS
Step 1. Open Sql Server Data Tools
Step 2. Click on File >> New >> Project. A dialog box will popup similar to like this


As you can see, it lets us create three kind of project. In order to perform a complete business intelligence task we need to go up with all these three projects.

1. Integration Services – SSIS – Sql server Integration services
It will let us perform wide range of data migration tasks. It let us collect data from various data sources and store them into central location.

2. Analysis Services – SSAS –Sql Server Analysis services
It will let us analyze the data

3. Reporting Services – SSRS – Sql Server Reporting services
It will let us create reports from analyzed data and present it to end user.

Start with SSIS
SSIS basically performs three basic things,

  •            Collect data from various sources. – We call it Extraction(E)
  •       Data obtained from different sources may or may not be same format. So first convert all of them according to business needs - We call it Transformation(T)
  •             Load them into one big data source(mostly Data Warehouse) – We call it Load(L)
Together termed as ETL process.

Simple ETL process using SSIS

Problem statement

You have Two excel files as follows,


·         You will collect data from first file (Datafile.xlsx).
·         Convert that data so that it match to second excel file format (merge Title, FirstName and LastName and call them as Name).
·         Dump final result to second file (Result.xlsx).

Step by Step Demo

Step 1. Create New Project
Click File >> New >> Project. Select Integration Services from the group. Specify some nice name. Say Ok.

It will open up SSIS designer which you will use for creating and maintaining Integration service packages. It looks like follows,


In the solution explorer under “SSIS packages” folder you will see one default package created with name “Package,dtsx”. If you want you can simply “rename it”or “remove it and add new one” (right click the folder and say “New SSIS Package”).
Note: Package is simply a collection of connections, control flow elements, data flow elements, event handlers, parameters etc. We will talk about each one of this as move further.
Step 2. Create Connection Manager for Excel File
2.1 Right click Connection Manager and Say New Connection.

2.2 Select Excel from the popup and click on Add.

2.3 Click the browse button and select the excel file and click on OK.

Step 3. Rename Connection Managers
3.1 Right click the connection manager just added and rename it to SourceExcelManager.

Step 4. Create Destination connection manager
4.1 Follow the Step no 3 and create one more connection manager pointing to Result.xlsx file.
4.2 Rename connection manager to ExcelDestinationManager.
Step 5. Create control flow – Pass data from Source Excel to Destination Excel.
5.1 Make sure control flow tab is selected in SSIS designer.

5.2 Select data flow task from the toolbox and drag it into designer.

5.3 Rename Data Flow Task to “Source excel to Destination excel transfer task”

Control Flow
Control flow will be used to define the workflow. As the name implies it control the flow of execution.
·         What all tasks need to be executed?
·         What will be the sequence?
·         Whether tasks need to be executed in loops or not?
Etc.
Step 6. CreateData Flow.
Data Flow
Data Flow defines the flow of data between source and destination.
6.1 Double click the control flow created in last step.
6.2 It will take you to second tab that is Data Flow tab.

Step 7. Create Excel Source
7.1 Now you will see a different SSIS toolbox all together. In toolbox you will see couple of groups defined like Sources, Destinations and Transformations.
Take excel source from Source group and place it in designer.

Step 8. Configure Excel Source
8.1 Red Cross mark on excel source indicates that, it’s not configured yet. Double click the excel source. It will show up a dialog box something like this.

8.2 Select Data Source as "SourceExcelManager", Data Access Mode as "Table or View" and Name of the sheet as "DataSheet1" (Name of the sheet in the excel file).
Note: This Excel Source will perform the Extraction Task (E) in the ETL process
Step 9. Create Derived Column
9.1 From the SSIS toolbox from Transformation group drag Derived column to SSIS designer.
Step 10. Connect Source to Derived Column
10.1 Click the Excel source added in prior step.
You can see a small blue arrow attached to the source. We call it “Data Flow Path”.

Data Flow Path: It lets you define how data will flow.
Click on the blue arrow and connect it to Derived Column.

Note: we will speak about the red arrow in one of the future article in the series.
Step 11. Configure the derived column
11.1 Double click the derived column. Popup looks like follows.

11.2 Put down Derived Column Name as Name, Select Derived Column as <add>and expression as Title + “ “ + FirstName + “ “ + LastName
11.3 Click Ok.
Note: This DerivedColumn will perform the Transformation Task (T) in the ETL process
Step 12. Create Excel Destination
12.1 Add Excel Destination from the Destination group in SSIS toolbox.
Note: This Excel Destination will perform the Load Task (L) in the ETL process
Step 13. Connect Derived Column to Excel Destination
13.1 Just like step no 10, connect derived column to excel destination.
Step 14. Configure Excel Destination
14.1 Double click the Excel destination, popup looks like follow.

14.2 Set connection Manager to “ExcelConnectionManager”, Data Access mode to “Table or View” and Name of the excel sheet to “Datasheet1”.
14.3 Click on mapping and make sure its proper, if not make sure to do it before proceeding.

Note: In our case, mapping will be already done by the IDE itself (because names of columns are matching).
14.4 Click ok.
Step 15. Execute package
15.1 Press F5.
On successful execution you will get a screen something like this.

16.2 Open the Result.xlsx file and confirm the output.

We have successfully completed our very first lab on SSIS.

Hope you enjoyed reading this. Your comments, votes and suggestions motivates us for writing more stuffs like this.


Continue Reading →

Monday, 24 April 2017

Ways to Improve SQL Query Performance

1-Avoid Multiple Joins in a Single Query

Try to avoid writing a SQL query using multiple joins that includes outer joins, cross apply, outer apply and other complex sub queries. It reduces the choices for Optimizer to decide the join order and join type. Sometime, Optimizer is forced to use nested loop joins, irrespective of the performance consequences for queries with excessively complex cross apply or sub queries.

2-Eliminate Cursors from the Query

Try to remove cursors from the query and use set-based query; set-based query is more efficient than cursor-based. If there is a need to use cursor than avoid dynamic cursors as it tends to limit the choice of plans available to the query optimizer. For example, dynamic cursor limits the optimizer to using nested loop joins.

3-Avoid Use of Non-correlated Scalar Sub Query

You can re-write your query to remove non-correlated scalar sub query as a separate query instead of part of the main query and store the output in a variable, which can be referred to in the main query or later part of the batch. This will give better options to Optimizer, which may help to return accurate cardinality estimates along with a better plan.

4-Avoid Multi-statement Table Valued Functions (TVFs)

Multi-statement TVFs are more costly than inline TFVs. SQL Server expands inline TFVs into the main query like it expands views but evaluates multi-statement TVFs in a separate context from the main query and materializes the results of multi-statement into temporary work tables. The separate context and work table make multi-statement TVFs costly.

5-Creation and Use of Indexes

We are aware of the fact that Index can magically reduce the data retrieval time but have a reverse effect on DML operations, which may degrade query performance. With this fact, Indexing is a challenging task, but could help to improve SQL query performance and give you best query response time.

6-Understand the Data

Understand the data, its type and how queries are being performed to retrieve the data before making any decision to create an index. If you understand the behavior of data thoroughly, it will help you to decide which column should have either a clustered index or non-clustered index. If a clustered index is not on a unique column then SQL Server will maintain uniqueness by adding a unique identifier to every duplicate key, which leads to overhead. To avoid this type of overhead choose the column correctly or make the appropriate changes.

7-Create a Highly Selective Index

Selectivity define the percentage of qualifying rows in the table (qualifying number of rows/total number of rows). If the ratio of the qualifying number of rows to the total number of rows is low, the index is highly selective and is most useful. A non-clustered index is most useful if the ratio is around 5% or less, which means if the index can eliminate 95% of the rows from consideration. If index is returning more than 5% of the rows in a table, it probably will not be used; either a different index will be chosen or created or the table will be scanned.

8-Position a Column in an Index

Order or position of a column in an index also plays a vital role to improve SQL query performance. An index can help to improve the SQL query performance if the criteria of the query matches the columns that are left most in the index key. As a best practice, most selective columns should be placed leftmost in the key of a non-clustered index.

9-Drop Unused Indexes

Dropping unused indexes can help to speed up data modifications without affecting data retrieval. Also, you need to define a strategy for batch processes that run infrequently and use certain indexes. In such cases, creating indexes in advance of batch processes and then dropping them when the batch processes are done helps to reduce the overhead on the database.

10-Don’t Access More Data Than You Need
Don’t return more columns or rows of data to the client than absolutely necessary. This just increases disk I/O on the server

11-Try to use with no lock option

12-Always use the option “SET NOCOUNT ON”
Continue Reading →

Thursday, 20 April 2017

Import MS Excel data to SQL Server table using C#

If you already have data in MS Excel file, and want to migrate your MS Excel data to SQL Server table, follow the below steps:
MY xls file.



CREATE a SQL Table


CREATE TABLE [dbo].[tblProduct](
 [PID] [int] NULL,
 [ProdName] [varchar](50) NULL,
 [ProdDesc] [varchar](50) NULL,
 [ProdCost] [varchar](50) NULL,
 [CREATED_DATE] [datetime] NULL
)

Your MS Excel sheet and SQL table are ready, now it’s time to write C# code to import the Excel sheet into the tblProduct table.

Create a MVC Project. 
In the homecontroller class add these namespaces.


using System.Data.OleDb;
using System.Data.SqlClient;

In the homecontroller class add these variables in class level


        SqlConnection Sqlcon;
        public static string strFileName = "";
        string strfileLocation = "";
        string constr, Query, sqlconn;

In the homecontroller  create a function below.


 public void UploadBulkData(string FilePath)
        {
            string OleDBConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=Excel 12.0;Persist Security Info=False";
            string Query = string.Empty;
            int BatchId = 0;
            sqlconn = ConfigurationManager.ConnectionStrings["TransactionDB"].ConnectionString;
            Sqlcon = new SqlConnection(sqlconn);
            #region Query
           // Query = @"SELECT * FROM [Sheet1$] WHERE PID IS NOT NULL";
            Query = @"SELECT
                             UCASE(RTRIM(LTRIM(PID))) AS PID,
                             UCASE(RTRIM(LTRIM(ProdName))) AS ProdName,
                             UCASE(RTRIM(LTRIM(ProdDesc))) AS ProdDesc,
                             UCASE(RTRIM(LTRIM(ProdCost))) AS ProdCost
                             FROM [Sheet1$]";
            #endregion

            using (OleDbConnection oledbConn = new OleDbConnection(OleDBConnectionString))
            {
                OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(Query, oledbConn);
                oledbConn.Open();

                DataSet ds = new DataSet();
                OleDbDataAdapter oda = new OleDbDataAdapter(Query, oledbConn);
                oledbConn.Close();
                oda.Fill(ds);
                DataTable Exceldt = ds.Tables[0];

                Exceldt.Columns.Add("CREATED_DATE", typeof(DateTime));
                foreach (DataRow row in Exceldt.Rows)
                {
                    row["CREATED_DATE"] = DateTime.Now.ToShortDateString();
                }

                //creating object of SqlBulkCopy    
                SqlBulkCopy objbulk = new SqlBulkCopy(Sqlcon);

                //assigning Destination table name    
                objbulk.DestinationTableName = "tblProduct";

                // inserting Datatable Records to DataBase
                Sqlcon.Open();
                objbulk.WriteToServer(Exceldt);
                Sqlcon.Close();
            }
        }


Now, It's time to call the above function.

        [HttpPost]
        public ActionResult Index(ProductModel model)
        {
            strfileLocation = @"D:\Projects\WebApplication1\WebApplication1\ProductSheet.xls"; //Server.MapPath("~/ProductSheet.xls");
            UploadBulkData(strfileLocation);
            return View();
        }

When you post the Index function, then it'll import all data from xls to your Sql table.
Continue Reading →

CTE and Temp Table and Table Variable - SQL SERVER

Temp tables
Behave just like normal tables, but are created in the TempDB database. They persist until dropped, or until the connection that created them disappears. They are visible in the procedure that created them and any procedures that that proc calls.

Just like normal tables, they can have primary keys, constraints and indexes, and column statistics are kept for the table. 

Temp tables, while they have space assigned to them in the tempDB database, will generally be accessed only from memory, unless the server is under memory pressure, or the amount of data in the table is large.

CREATE TABLE #LocalTemp
(
 UserID int,
 Name varchar(50), 
 Address varchar(150)
)
GO
insert into #LocalTemp values ( 1, 'Shailendra','Noida');
GO
Select * from #LocalTemp

Table Variables
These tables behave very much like other variables in their scoping rules. They are created when they are declared and are dropped when they go out of scope. They cannot be explicitly dropped.

Like with temp tables, table variables reside in TempDB. they have entries in the system tables in tempDB, just like temp tables, and they follow the same behaviour regarding whether they are in memory or on disk.

Table variables can have a primary key, but indexes cannot be created on them, neither are statistics maintained on the columns. This makes table variables less optimal for large numbers of rows, as the optimizer has no way of knowing the number of rows in the table variable.

 GO
 DECLARE @TProduct TABLE
 (
 SNo INT IDENTITY(1,1),
 ProductID INT,
 Qty INT
 ) 
 --Insert data to Table variable @Product 
 INSERT INTO @TProduct(ProductID,Qty)
 SELECT DISTINCT ProductID, Qty FROM ProductsSales ORDER BY ProductID ASC 
 --Select data
 Select * from @TProduct
 
 --Next batch
 GO
 Select * from @TProduct --gives error in next batch

CTE
CTE stands for Common Table expressions. It was introduced with SQL Server 2005. It is a temporary result set and typically it may be a result of complex sub-query. Unlike temporary table its life is limited to the current query. It is defined by using WITH statement. CTE improves readability and ease in maintenance of complex queries and sub-queries. Always begin CTE with semicolon.

;With CTE1(Address, Name, Age)--Column names for CTE, which are optional
AS
(
SELECT Addr.Address, Emp.Name, Emp.Age from Address Addr
INNER JOIN EMP Emp ON Emp.EID = Addr.EID
)
SELECT * FROM CTE1 --Using CTE 
WHERE CTE1.Age > 50
ORDER BY CTE1.NAME
Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives