European Windows 2019 Hosting BLOG

BLOG about Windows 2019 Hosting and SQL 2019 Hosting - Dedicated to European Windows Hosting Customer

European SQL Server 2019 Hosting :: Derived Tables Vs Common Table Expressions

clock August 30, 2022 07:19 by author Peter

T-SQL supports different types of table expressions,
    Views
    Functions
    Derived Tables (DT)
    Common Table Expressions (CTE)

We will have separate articles on functions and views. But today’s post is related to Derived Table and Common Table Expression and their differences. By the way, what is table expression?

Table expression - is a special type of named query which allows us to build relational-oriented queries. You create a special query, rename it, and can use it in multiple types ( at least as a view and a function)

You can wrap your query into views and functions, store them as an object in the database and call them as a user-defined table which can have an argument (function) or without it.

But unfortunately, the above sentence is not correct for DT and CTE. T-SQL provides your to wrap your query into Derived table and Common Table Expressions but storing them directly as a separate object is not possible.
Why do we need to use Derived Table and Common Table Expression?

When working with SELECT, we usually apply special searching/filtering to our queries. But in a few cases, it is not possible to do it.
SELECT
Row_number() over(order by SalesOrderDetailId) as rownum, *
FROM Sales.SalesOrderDetail AS SOD


Let’s try to filter numbers that are less than 200.
SELECT
Row_number() over(order by SalesOrderDetailId) as rownum, *
FROM Sales.SalesOrderDetail AS SOD
WHERE rownum < 200

As we know from this article, every statement has its logical execution number and Where executes before SELECT and defined alias in SELECT can’t be detected in WHERE. How about using expression directly:
SELECT
Row_number() over(order by SalesOrderDetailId) as rownum, *
FROM Sales.SalesOrderDetail AS SOD
WHERE Row_number() over(order by SalesOrderDetailId) < 200


It is also not possible because Windowed functions can only appear in the SELECT and ORDER clauses. (read error message)

So, how we can filter numbers?

Except for using views and functions there are 2 more options,
    Derived Tables
    Common Table Expressions

2 types of writing Derived tables,
SELECT * FROM
(
SELECT
Row_number() over(order by SalesOrderDetailId) as rownum,
SalesOrderID, CarrierTrackingNumber
FROM Sales.SalesOrderDetail AS SOD) AS DT
WHERE DT.rownum < 200


--second version of writing derived tables

SELECT * FROM
(
SELECT
Row_number() over(order by SalesOrderDetailId) as rownum,
SalesOrderID, CarrierTrackingNumber
FROM Sales.SalesOrderDetail AS SOD) AS DT(RowNumber, SalesOrderID, CTrackingNumber)
WHERE DT.RowNumber < 200


Now, it is possible to wrap and filters our query. When comparing with Subqueries, Derived tables allow us to wrap the entire query but in subqueries, the inner query “lived” in the WHERE clause.

There are 2 “but”s when using derived tables:

It is really hard to refer from one derived table to another when building complex queries:
SELECT ...
FROM (SELECT
    FROM (SELECT ...
        FROM T1
            WHERE ...) AS MyDT1
         WHERE ....) AS MyDT2
    WHERE ....


If you want to combine multiple instances of the same derived table, it will not be possible.
SELECT * FROM
 (
SELECT
Row_number() over(order by SalesOrderDetailId) as rownum,
SalesOrderID, CarrierTrackingNumber
FROM Sales.SalesOrderDetail AS SOD)
AS DT(RowNumber, SalesOrderID, CTrackingNumber)
INNER JOIN DT as DT2
ON DT.RowNumber = DT2.RowNumber

 

The problem here is related to the same-time execution of expression in the T-SQL lifetime.

To write it correctly, you need to type DT twice.
SELECT * FROM
 (
SELECT
Row_number() over(order by SalesOrderDetailId) as rownum,
SalesOrderID, CarrierTrackingNumber
FROM Sales.SalesOrderDetail AS SOD)
AS DT(RowNumber, SalesOrderID, CTrackingNumber)
INNER JOIN (SELECT
Row_number() over(order by SalesOrderDetailId) as rownum,
SalesOrderID, CarrierTrackingNumber
FROM Sales.SalesOrderDetail AS SOD)
AS DT2(RowNumber, SalesOrderID, CTrackingNumber)
ON DT.RowNumber = DT2.RowNumber

rom the usage point of view, CTE does the same thing DT does. We can wrap and filter, join, and order our queries like in DT. But you can think about it as version 2.0 of Derived Tables.
WITH CTE
AS(
SELECT
Row_number() over(order by SalesOrderDetailId) as rownum, *
FROM Sales.SalesOrderDetail AS SOD)
SELECT * FROM CTE
WHERE rownum < 200;

What are the advantages of using Common Table Expressions?

It is really easy to refer from one CTE to another,
WITH CTE
AS(
SELECT
Row_number() over(order by SalesOrderDetailId) as rownum, *
FROM Sales.SalesOrderDetail AS SOD)
,
CTE2 AS --from CTE2 we referred to CTE
(SELECT * FROM CTE)
SELECT * FROM CTE2;


If you want to combine multiple instances of the same expressions, it is also easy to do it with CTE.
WITH CTE
AS(
SELECT
Row_number() over(order by SalesOrderDetailId) as rownum, *
FROM Sales.SalesOrderDetail AS SOD)
SELECT * FROM CTE
INNER JOIN CTE as CTE2
ON CTE.rownum = CTE2.rownum


Writing recursive queries with CTE:
CREATE TABLE [dbo].[RecursiveTable](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Level] [int] NULL,
    [SubLevel] [int] NULL,
    [Name] [nvarchar](30) NOT NULL,
    [Position] [varchar](30) NULL
) ON [PRIMARY]
GO

WITH CTE
AS
(SELECT Id, Level, SubLevel, Name, Position
FROM Rekursiya WHERE Id = 1
UNION ALL
SELECT R.Id, R.Level, R.SubLevel, R.Name, R.Position
FROM CTE
INNER JOIN RecursiveTable AS R
ON R.SubLevel = CTE.Level)
SELECT * FROM CTE;

Working with PIVOT and Unpivot ( I’ll write a separate article about it )

HostForLIFEASP.NET SQL Server 2019 Hosting



European SQL Server 2019 Hosting :: Get ConnectionString For SQL Server

clock August 25, 2022 09:30 by author Peter

We always have chance to use connection strings, such as in an application. When we need it, the first idea is to acquire it from SQL Server Managerment Studio. However, it seems we cannot.

This article will introduce several ways that we can get connection strings easily. The article will cover the following:
    Introduction
    A - Get Connection string by SSMS (SQL Server Management Studio) --- no way
    B - Get Connection string from online reference or generator
    C - Get Connection String by Visual Studio, Server Explorer
    D - Get Conenction String by Microsoft Universal Data Link file (xxx.udl)

A - Get Connection String by SSMS
Although the first expection is to get Connection String from SSMS, but actually, we cannot. Open SSMS, right click a Database Connection => Properties.

Open the Server Properties Window. This is most possible place where I might get the database Connection String. However, we have all parameters available, but we cannot see the whole connection string.

Click the link "View Connection Properties" on the left panel of this Window:

As before, I can get all parameters, but not the connection string.
B - Get Connection String by online Reference or Generator

online Reference:
From the Web, we can check and get the connection string we need, such as in:

ConnectionStrings References - ConnectionStrings.com --- in general
    SQL Server connection strings - ConnectionStrings.com --- Specific for SQL Server

We can get connection string like this:

However, we do not have chance to test the connection string.

Online Generator:

We can use an online Connection String generator, such as:

    SQL Server Connection String Generator | Aireforge®

To generate a Connection String by your parameters:


You can get a real and ready connection string using your specifc parameters, but stil cannot make a test.

C - Get Connection String by Visual Studio's Server Explorer
In Visual Studio IDE, Click View => Server Explorer:

In the Server Explorer, click the Connect to Database icon:

To add a connection:

In this way, we can test if the connection is working.

Finally, click the Advanced Button. Then we can get the connection string at the bottom of the Advanced Properties Window.

Otherwise, after creating the connection, right click => Properties

In Properties Window, we will see the ConnectionString there too:

D - Get Connection String by Microsoft Universal Data Link file (xxx.udl)
We can create a Data.udl file in the computer:

Double click the Data.udl file, and set up the connection:


Click the Test Connection button:

Close the created connection, and open the Data.udl file by another editor, such as VS Code:


We will see the connection string:

HostForLIFEASP.NET SQL Server 2019 Hosting



European SQL Server Hosting :: How To Rename Database Objects In SQL Server?

clock August 18, 2022 08:26 by author Peter

This article demonstrates how we can easily rename various database objects like Tables, Columns, Constraints, Indexes, SP in SQL Server. You may have faced a scenario where sometimes we need to rename database objects to specify correct business significance and meaning to the system on production code. The database objects which were originally designed may not match the current business objects. To solve this problem, you may need to rename existing database objects like table name, column name, store procedure name, etc. The best and easiest way is to use SP_RENAME, a build-in stored procedure to rename these objects. This approach is recommended because we can run pre-deployment scripts in the environment before deploying these changes. SP_RENAME takes below arguments. Reference has been taken from Microsoft documentation.

Parameter Description
@objname Object Name. When renaming a column you need to specify table name.column name optionally you can also prefix schema name
@newname New name for the specified object
@objtype Type of the object. You can rename below objects using sp_rename:
COLUMN
DATABASE
INDEX
OBJECT
STATISTICS
USERDATATYPE
Default value for this parameter is TABLE

To demonstrates this, I am creating a table with Primary key, check constraint, non-clustered index and putting some data into this table. We will compare before and after snapshots.

CREATE TABLE OrderInfo
(
    Id INT IDENTITY(1, 1) NOT NULL,
    OrderMode VARCHAR(20) CONSTRAINT [CK_OrderInfo_OrderMode] CHECK (OrderMode IN ('ONLINE','OFFLINE')) NOT NULL,
    OrderName VARCHAR(100) NOT NULL,
    OrderDate DATETIME CONSTRAINT [DF_OrderInfo_OrderDate] DEFAULT (GETDATE()) NOT NULL,
    CONSTRAINT PK_OrderInfo_Id PRIMARY KEY NONCLUSTERED (Id ASC)
)

CREATE NONCLUSTERED INDEX IX_OrderInfo_OrderMode ON dbo.OrderInfo (OrderMode)

INSERT INTO  OrderInfo
VALUES
    ( 'ONLINE', 'Notebook', GETDATE()),
    ( 'ONLINE', 'PC', GETDATE()),
    ( 'OFFLINE', 'Printer', GETDATE())
GO

Before snapshot of table, constraints, and index.


One thing to keep in mind is that when we rename these objects, we need to make changes in dependencies of these objects. For example – if you are renaming a table and that table is being used in multiple SPs then we also to modify those SPs as well. But that is a manual activity to find and fix. This warning represents the same thing.

HostForLIFEASP.NET SQL Server 2019 Hosting

 



European SQL Server 2021 Hosting :: SQL IIF Function

clock August 15, 2022 09:02 by author Peter

In this post, we’ll explore the IIF SQL functionality. IIF (If and only if) function, and we’ll use the AdventureWorks database for our testing purposes. Let’s get started.
What’s IIF Function?

Introduced in SQL Server 2012
This function returns one of two values depending on the boolean expression [also known as condition] that evaluates true or false.
IIF is composed of the logical statement, the boolean expression known as the condition, followed by the “true” and the “false” expressions.
This function can be compared to CASE expressions and a shorthand way of writing a CASE expression.

IIF Syntax
-- Syntax
    IIF(boolean_expressions, true, false)
-- OR
    IIF(condition, true, false)


    Boolean expression or condition – this is required, and it is because of the value that needs to be tested.
    True - this is optional, but the value is returned if the condition is true.
    False - this is optional, but the value is returned if the condition is false.

Examples
1. Compare Numbers

-- Let's declare and initialize two numbers
DECLARE @NUM1 INT = 20;
DECLARE @NUM2 INT = 25

--OUTPUT: 25 is greater than 20
SELECT IIF( (@NUM2 > @NUM1), FORMATMESSAGE('%i is greater than %i', @NUM2, @NUM1),
                             FORMATMESSAGE('%i is greater than %i', @NUM1, @NUM2))
                             AS [ComparingNumbers];
--OUTPUT: TRUE
SELECT IIF(@NUM2 > @NUM1, 'TRUE', 'FALSE')  AS [ComparingNumbers];

SET @NUM1  = 120;
SET @NUM2  = 25;

--OUTPUT: 120 is greater than 25
SELECT IIF((@NUM1 > @NUM2), FORMATMESSAGE('%i is greater than %i', @NUM1, @NUM2),
                            FORMATMESSAGE('%i is greater than %i', @NUM2, @NUM1))
                             AS [ComparingNumbers];
--OUTPUT: TRUE
SELECT IIF(@NUM2 > @NUM1, 'FALSE', 'TRUE')  AS [ComparingNumbers];


As you can see from the example we have shown how we can easily compare numbers using the IIF function.

Output

2. Compare numbers within a table column
This section will try to explore some examples using the AdventureWorks database. Checking the Person Person table of the AdventureWorks database, you’ll see a NameStyle column. This column uses bit as its datatype. When it is 0, FirstName and LastName are stored in Western-style (first name, last name). Otherwise, when it is 1, it is stored in an Eastern-style (Lastname, first name) order.

Let’s try to use the IIF function here.
USE [AdventureWorks2019]
/** Let’s try to format the person’s names using either western-style or eastern-style by using IIF.*/
SELECT IIF(NameStyle = 0,
    CONCAT(FirstName, ', ' , LastName),
    CONCAT(LastName, ', ', FirstName))
FROM
[Person].[Person]


Output

3. Compare strings within a table column
In this example, we’ll try to get the Employee’s marital status by using the IIF function and joining the two tables [HumanResources].[Employee] and [Person].[Person] inside the AdventureWorks database. The column MaritalStatus uses the nchar(1) datatype, and M stands for married, while S stands for single.

Let’s see an example below.
USE [AdventureWorks2019]

SELECT TOP 10 IIF(MaritalStatus = 'M', 'Married', 'Single') as [Marital Status],
    FirstName,
    LastName
FROM [HumanResources].[Employee] E
INNER JOIN [Person].[Person] P
ON E.[BusinessEntityID] = P.[BusinessEntityID]

Output


4. Nested SQL IIF Statement
In this example, we’ll try to get the Person’s type by using a nested IIF function and checking the PersonType column, which uses nchar(2) as its datatype. Has many meanings.

Let’s see the list below.
    SC = Store Contact
    IN = Individual
    SP = Sales Person
    EM = Employee
    VC = Vendor Contact
    GC = General Contact

USE [AdventureWorks2019]
-- Randomly select rows in this table (10 percent)
SELECT TOP 10 PERCENT
       FirstName,
       LastName,
       IIF(PersonType = 'EM', 'Employee',
       IIF(PersonType = 'SC', 'Store Contact',
       IIF(PersonType = 'IN', 'Individual',
       IIF(PersonType = 'SP', 'Sales Person',
       IIF(PersonType=  'VC', 'Vendor Contact',
       IIF(PersonType = 'GC', 'General Contact', 'n/a')))))) AS [Type of Person]
FROM [Person].[Person]
ORDER BY NEWID()


Just a reminder, as you can see, the query sample is randomly selecting records on the [Person].[Person] table to see different results every time we execute the query. So your results will be further from the output shown below.

Output

5. SQL IIF and NULL Value
When dealing with the IIF function and passing a NULL value within both the true and false expressions/parameters, it will throw an exception. But before we see an example, we’ll be using the [Production].[Product] table as our example and let’s try to see the number of days to manufacture a certain product.
USE [AdventureWorks2019]
SELECT MIN(DaysToManufacture), Max (DaysToManufacture) FROM [Production].[Product]


If you will execute the query above, this will show us that the minimum number of days to manufacture a product is 0, and the maximum number of days to manufacture a product is 4 days.

Now, let’s try to use the IIF function and check if the [DaysOfManufacture] is zero and pass the value NULL to both parameters.
USE [AdventureWorks2019]
SELECT IIF(DaysToManufacture = 0, NULL, NULL) FROM [Production].[Product]


Output

It’s clearly saying that we need to have at least one true or false argument and be mindful next time not to encounter this exception.

Let’s see an example below.
USE [AdventureWorks2019]
SELECT DaysToManufacture,
         IIF(DaysToManufacture = 0, 'Fast to manufacture.', NULL) FROM [Production].[Product]


Output

Summary
In this article, we have discussed the following:
    What’s IIF Function
    IIF Syntax
    Examples
        Compare numbers
        Compare numbers within a table column
        Compare strings within a table column
        Nested SQL IIF Statement
        SQL IIF and NULL Value

Once again, I hope you have enjoyed reading this article/tutorial as much as I have enjoyed writing it.

Stay tuned for more. Until next time, happy programming!

Please don't forget to bookmark, like, and comment. Cheers! And Thank you!

HostForLIFEASP.NET SQL Server 2021 Hosting



European SQL Server Hosting :: How to Take SQL Server Database Backup?

clock August 8, 2022 09:05 by author Peter

In this article, I will guide you in how to take SQL Server Database backup to a local folder. There are two ways to take a database backup.

Method 1
Open SQL Server Management Studio (SSMS) and follow the below steps
Select the Database that you want to take backup.
For example, here I am using the EmployeeDB database.
Select Database. Right click on database -> select Task -> Back Up.

Once we click on Back up, a pop-up window will open.
This window will show the Database name from which we are taking a backup. Select the backup type as Full, and back up to Disk.

Now click on the remove button and then click on Add. This will open one more popup window, which will allow us to choose our specific path. Now once we navigate to our path, we need to provide the database file name. In my case, I have given EmployeeDB.bak. and click on OK.

Note: ".bak" is an extension for backup.

Once we click Ok, our backup path will be set. Now click Ok.

Once we click on OK our database backup will be created to our provided path.

Now we can verify whether our database backup is created or not.

Method 2
Using SQL Query.
declare @backuppath as nvarchar(max)
set @backuppath  = N'C:\WorkingProjects\Practice\DataBase\Employee\EmployeeDB_'
+ CONVERT(nvarchar,YEAR(getdate()))
+ CONVERT(nvarchar,Month(getdate())) +
+ CONVERT(nvarchar,DAY(getdate())) + '.bak'
Backup Database [EmployeeDB] to DISK = @backuppath WITH NOFORMAT, NOINIT, NAME=N'EmployeeDB-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO


Now execute the query

Once the query is executed, it will create a database backup to the specified path.
Eg. In my case path is "C:\WorkingProjects\Practice\DataBase\Employee".

Now, we can verify whether our database backup is created or not.

HostForLIFEASP.NET SQL Server 2019 Hosting

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in