Tag : set based example


Specific row at the top then sort the rest result set in SQL Server

In this post, “Specific row at the top then sort the rest result set in SQL Server“, we are going to learn that how we can order a result set in a customized way which cannot be achieved using ORDER by Clause in a simple way.

To demonstrate this, let’s create a sample table named as “tbl_Department” and insert some dummy rows in it. Below is the code to create the sample table:

IF(OBJECT_ID('dbo.tbl_Department') IS NOT NULL)
DROP TABLE tbl_Department
GO
CREATE TABLE tbl_Department
(
DeptId INT IDENTITY(1,1) NOT NULL,
DeptName VARCHAR(256) NOT NULL,
DeptAddress VARCHAR(512),
DeptContact VARCHAR(15)
)
GO

Now, add some sample rows into the table:

INSERT INTO tbl_Department
(DeptName, DeptAddress, DeptContact)
VALUES
('Engineering', 'New Delhi', '1234567890'),
('Human Resources', 'Chennai', '9876543210'),
('Admin', 'Kolkata', '2763282789'),
('Human Resources', 'New Delhi', '1928272727'),
('Not Assigned', 'Mumbai', '1839288976')
GO

Let’s have a look at the table data now:

Sample table

Sample table

From … More


Extract the first number from an alphanumeric string in sql server 4

In this post, we are going to learn how to extract the first numeric value from an alphanumeric string in SQL Server. To demonstrate this, we will create a dummy table and then we will insert some dummy rows into that table. Finally, we will use a SELECT statement to extract the first numeric value from the given alphanumeric string for each row of the table.

Let’s create the dummy table as below:

--Create dummy table named testTable
IF(OBJECT_ID('dbo.testTable')) IS NOT NULL
DROP TABLE dbo.testTable
GO
CREATE TABLE dbo.testTable
(
val VARCHAR(100)
)
GO

Now, let’s insert some alphanumeric values in this table as below:

--Insert some dummy rows in testTable
INSERT INTO dbo.testTable
(val)
VALUES
('1846855445-DB-FC-D-B-FEDACAE'),
('912898124-B--EB-CBD-EEC'),
('AFAA---E-EDDEC-1080731029'),
('FFDE-DA-B-A-BCE-1807799782'),
('DDFAD-DDE-D-EB-FFDFBB-1683269209'),
('522822568-C-EFC--ACCA-EDB'),
('BDDAC-C-C-A-EC-450054394'),
('DBCD-D-AA-AD-EFA-385921800'),
('EF-B-ED-BBC-FEBC-599561669'),
('BED--F-BC-FD')

We have below sample records in the testTable:

--Get data from testTable
SELECT * FROM dbo.testTable
Sample records in testTable

Sample records in testTable

Now, to extract the … More


Unfolding | Set Based Approach | Get Continuous Start Date of the Current Project – Episode 8 1

In this video, we are going to learn;

  1. How and when to use Apply operator in SQL Server, and
  2. How to compare rows on a given logic

You can download the script used in this example from below the video.


/******************************************************************************************************************************************************
Start using the SetBasedApproach database
******************************************************************************************************************************************************/
--Start using the existing database SetBasedApproach which has been already created in this series
USE SetBasedApproach
GO

/******************************************************************************************************************************************************
Create required objects
******************************************************************************************************************************************************/
--Drop the EmployeeMaster table if it exists already in the database
IF(OBJECT_ID('dbo.EmployeeMaster') IS NOT NULL)
DROP TABLE dbo.EmployeeMaster

--Create Employee master table
CREATE TABLE dbo.EmployeeMaster
(
EmpID INT NOT NULL PRIMARY KEY,
EmpName NVARCHAR(255) NOT NULL
)

--Drop the project master table if it exists already in the database
IF(OBJECT_ID('dbo.ProjectMaster') IS NOT NULL)
DROP TABLE dbo.ProjectMaster

--Create project master table
CREATE TABLE dbo.ProjectMaster
(
ProjectID INT NOT NULL PRIMARY KEY,
ProjectName VARCHAR(255)
)

--Drop the EmployeeProjectDetail table if it exists already 
More

Unfolding | Set Based Approach | Create Attendance Report – Episode 7 1

In this video, we are going to learn;

  1. Generate date list from the given date range dynamically
  2. Repeat the date list for each employee without using a loop or recursive CTE

You can download the script used in this example from below the video.

/******************************************************************************************************************************************************
Start using the SetBasedApproach database
******************************************************************************************************************************************************/
--Start using the existing database SetBasedApproach which has been already created in this series
USE SetBasedApproach
GO

/******************************************************************************************************************************************************
Create required objects
******************************************************************************************************************************************************/
--Drop the EmployeeMaster table if it exists already in the database
IF(OBJECT_ID('dbo.EmployeeMaster') IS NOT NULL)
DROP TABLE dbo.EmployeeMaster

--Create Employee master table
CREATE TABLE dbo.EmployeeMaster
(
EmpID INT NOT NULL PRIMARY KEY,
EmpName NVARCHAR(255) NOT NULL
)

--Drop the EmployeeAttendanceDetail table if it exists already in the database
IF(OBJECT_ID('dbo.EmployeeAttendanceDetail') IS NOT NULL)
DROP TABLE dbo.EmployeeAttendanceDetail

--Create EmployeeAttendanceDetail table which stores the attendance marked by the employees
CREATE TABLE dbo.EmployeeAttendanceDetail
(
RowId INT NOT NULL IDENTITY(1, 1),
CalendarDate 
More

Unfolding | Set Based Approach | Generate Rows Dynamically – Episode 6

In this video, we are going to learn;

  1. How we can Generate rows dynamically for each record of a table in set based approach, and
  2. How to do calculations on each row of a table generated dynamically

You can download the script used in this example from below the video.

--Use SetBasedApproach database
USE SetBasedApproach
GO
--Create the table EmployeeLoanDetail
CREATE TABLE dbo.EmployeeLoanDetail
(
EmpID INT NOT NULL,
EmpName VARCHAR(100) NOT NULL,
[Address] VARCHAR(256) NOT NULL,
LoanAmount NUMERIC(9, 2),
RepaymentTenureInMonth INT,
RepaymentStartDate DATE
)
GO
--Insert few records in the table
INSERT INTO dbo.EmployeeLoanDetail
(EmpID, EmpName, [Address], LoanAmount, RepaymentTenureInMonth, RepaymentStartDate)
SELECT 1 AS EmpID, 'Adam' AS EmpName, 'New Delhi' AS [Address],
100000 AS LoanAmount, 3 AS RepaymentTenureInMonth, '1-Feb-2016' AS RepaymentStartDate
UNION ALL SELECT 2, 'Joy', 'New Delhi', 150000, 5, '1-Mar-2016'
UNION ALL SELECT 3, 'Roy', 'New Delhi', 120000, 6, '1-Feb-2016'
UNION ALL SELECT 4, 'Mac', 'New Delhi', 160000, 8, '1-Dec-2016'
More

Unfolding | Set Based Approach | Tally Table – Episode 5

In this video, we are going to understand Tally table which is very useful in writing set based SQL queries. You can download the script which can be used to create the Tally table from below the video.

--Creating database SetBasedApproach
CREATE DATABASE SetBasedApproach
GO

--Started using database SetBasedApproach
USE SetBasedApproach
GO

--Creating tally table
CREATE TABLE dbo.Tally
(
N INT NOT NULL PRIMARY KEY
)

--Adding records
INSERT INTO dbo.Tally(N)
SELECT TOP 100000 ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS N
FROM master.sys.all_columns Tbl1
CROSS JOIN master.sys.all_columns Tbl2
More

Unfolding | Set Based Approach | How join works internally – Episode 4

In this video, we are going to understand how join works internally. If you have a good understanding of joins and how it works, you can skip this video and move to the next video in this series. If not, lets start understanding the joins. You can download the script used in this example from below the video.

Here is the example script used in this video.

--Create database
CREATE DATABASE SetBasedApproach
GO

--Start using the database
USE SetBasedApproach
GO

--Create employee table
CREATE TABLE dbo.Employee
(
[Emp ID] INT,
[Emp Name] VARCHAR(256)
)
GO

--Create department table
CREATE TABLE dbo.Department
(
[Emp ID] INT,
[Dept Name] VARCHAR(256)
)
GO

--Insert some values in employee table
INSERT INTO dbo.Employee ([Emp ID], [Emp Name])
VALUES(1, 'Adam'),
(2, 'Joy'),
(3, 'Roy'),
(4, 'Mac')
GO

--Insert some values in department table
INSERT INTO dbo.Department ([Emp ID], [Dept Name])
VALUES(1, 'Engineering'),
(2, 'Human Resources'),
More

Unfolding | Set Based Approach | SQL Server Query execution architecture – Episode 3

In this video, we are going to understand the query execution architecture which helps us to understand the importance of set based approach. When a T-SQL statement gets submitted to SQL server, it goes through multiple steps before we get the final output. Lets have a look on SQL Server query execution architecture.

More


Unfolding | Set Based Approach | Introduction to the course – Episode 2

This video will give you insight of the topic that we are going to cover in this series. We know that the thinking in terms of sets is creative and innovative and once you start understanding the concepts, believe me, you will find it is simple too. Writing set based queries needs a good understanding of SQL joins and other set based operators with some imagination ability, which we are going to learn in this course.

More


Unfolding | Set Based Approach | Why set based approach – Episode 1

Welcome to my course “Unfolding | Set Based Approach”. This is my first video tutorial series. In this series, I am going to share the concepts and techniques being used to create set based SQL queries.

This course is not based on how to write queries (this you can find at many places), rather it is based on how to think in set based manner. This course contains real life examples with deep insights to explore set based concepts, so that you can start thinking in terms of sets. Lets watch this video which explains why we should use set based approach instead of cursors or loops.

Please do share and comment if you like this. Also, please subscribe to our newsletter to be updated.

 

More