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 :: ORM Vs Stored Procedures In Programming

clock September 6, 2022 09:52 by author Peter

Today we will look at a very common debate that occurs while developing a data access layer. This debate is to decide if we want to use stored procedures and keep our logic in the database, or if we want to use an ORM like Entity Framework and keep all logic in our middle tier C# code, using the database only as a data store. I will not be detailing the different types of ORMs and samples on using them as this information is widely available on the web. I will also not detail how to write and use stored procedures, as this information is also widely available for almost all types of databases. I will simply try to explain the pros and cons of using each and which and why I think it is a better solution.

What are Stored Procedures?
Let us begin by identifying what stored procedures are. Stored procedures are commonly used artifacts of relational databases, like SQL Server, Oracle, etc. These can include code to manipulate the data and are efficient in selecting, processing, and sending back data to the front-end application. These are written using SQL language, which is easy to understand and learn. Some of the major advantages of using stored procedures are that these are compiled, optimized, and run by the database engine and so can perform very quickly. For this reason, I have seen some architects strongly push the use of stored procedures.

What is an ORM?
An ORM means object relational mapping. This method allows us to create classes to represent our database tables, and then use a context or communication class to join these classes to our database tables. Then, we can use the full power of the middle-tier programming language, like C#, to write queries to select and update the data in our tables. Of course, an ORM does not end there, and we can also create other artifacts for stored procedures, etc. We can also merge classes from multiple tables and break a single table into multiple classes. However, the main idea is to use the database mainly as a store and keep all processing logic in the middle-tier code.

What to use today? Stored Procedures vs ORM

These days we have a much-advanced landscape for both stored procedures in various databases, and also great ORMs. For example, Entity Framework Core gives us many options and is easy to understand and implement. So, what should we use? The answer is that it depends upon the particular scenario. However, I would prefer to use an ORM, as in this way we can better abstract all business and processing logic into proper classes inside our middle-tier, and use the power of all libraries, NuGet packages, etc. available at this level. This also saves us from being tied to a particular database, and in the future, we can move to another data store quite easily. However, if we need to do some heavy programming at a database level and want to fully utilize the power of the database engine, using stored procedures would be the way to go. However, in this case, we might need to commit to a particular database for a longer period, especially if we are using a SQL dialect for that particular database to write our stored procedures.

Summary
In this article we looked at what to choose to build, our data access or data process layer. The answer depends on the coder's needs, and different people will have different opinions on it. However, from my personal point of view, I prefer to keep all logic in the middle-tier. This way the logic is better abstracted, and we can use the vast number of libraries available to process the data. Also, we can retrieve data in chunks and process it using parallel programming techniques and utilize the extremely powerful hardware we have these days. This also does not tie us to any particular database.

HostForLIFEASP.NET SQL Server 2019 Hosting

 



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

 



SQL Server 2021 Hosting - HostForLIFE :: How To Delete SQL Server Old Databse Backup Files?

clock July 27, 2022 09:34 by author Peter

In this article, I will guide you on how to delete old backup files on an SQL Server Database. Though we have moved to the cloud, there are still some projects that have their own server machines, on which we do deployment, SQL Server Database backups, and other jobs.

There are two ways we can delete old database backup files:
    Using C# Code (delete files from location)
    Using SQL Script (master.sys.xp_delete_file)

Delete SQL Server Database backup files Using C# Code
Set a path in App.config file.
<appSettings>
        <add key="path" value="C:\WorkingProjects\Practice\DataBase\Employee\DBBackup"/>
</appSettings>


In Program.cs file.
In my case, I have set it to delete database backup files that are older than one week.

Note
    I have used CreationTime, which will return the date and time when the database backup was created.
    .bak is an extension of SQL Server backup file.

var directorypath = ConfigurationManager.AppSettings["path"].ToString();
var files = Directory.GetFiles(directorypath, "*.bak");

foreach (var file in files)
 {
   var _file = new FileInfo(file);
   if (_file.CreationTime < DateTime.Now.AddDays(-7)) // weekly
        _file.Delete(); // Delete File
 }


SQL Server DB backups which we want to delete.

Before Code execution (Before Old DB backup Delete)

After Code execution (After Old DB backup Delete).
Now, we can verify whether our old database backup is deleted or not.

Delete SQL Server Database backup files Using SQL Query (xp_delete_file)
DECLARE @name NVARCHAR(500); -- Database name
DECLARE @path NVARCHAR(500); -- Path for backup files
DECLARE @fileName VARCHAR(500); -- Filename for backup
DECLARE @fileDate VARCHAR(20) = CONVERT(VARCHAR(20),GETDATE(),112); -- Used for file name
DECLARE @FileExtension nvarchar(4) = N'.BAK' -- file extension
DECLARE @DeleteDate DATETIME = DATEADD(wk,-1,GETDATE()); -- last week date

-- Path to backups.
SET @path = 'C:\WorkingProjects\Practice\DataBase\Employee\DBBackup'

-- Dynamically get each database on the server.
DECLARE db_cursor CURSOR FOR

SELECT NAME
FROM master.sys.databases
WHERE name NOT IN ('master','model','msdb','tempdb','ReportServer','ReportServerTempDB');

OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @name;

-- Loop through the list to backup each database.
    WHILE @@FETCH_STATUS = 0
    BEGIN
          -- Build the path and file name.
          SET @fileName = @path + @name + '_' + @fileDate + @FileExtension;
          --select @fileName

          -- Loop to the next database.
          FETCH NEXT FROM db_cursor INTO @name;
    END

--Delete backup files
EXEC master.sys.xp_delete_file 0,@path,'BAK',@DeleteDate,0;

CLOSE db_cursor;
DEALLOCATE db_cursor;
GO

xp_delete_file takes five parameters:
    File Type - 0 for backup files or 1 for report files.
    Folder Path - The folder to delete files.
    File Extension - This could be ‘BAK’.
    Date - Cutoff date for what files need to be deleted.
    Subfolder - 0 to ignore subfolders, 1 to delete files in subfolders.

Before Query execution (Before Old DB backup Delete)

After Query execution (After Old DB backup Delete).
Now we can verify whether our old database backup has been deleted or not.

Note
We can add our .exe file in the task scheduler and script in the SQL Job, which we can automate to execute as per our choice (weekly/monthly).



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

clock July 25, 2022 10:39 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 2021 Hosting



SQL Server 2021 Hosting - HostForLIFE :: T-SQL Subqueries In Practice

clock July 22, 2022 08:26 by author Peter

T-SQL provides different ways of “gathering” information from tables. Usually in our practice, we use joins, unions, table expression, etc. But, one of the most interesting ways of getting information from tables is done using Subquery.

Preparation
The below examples require using AdventureWorks2019 from Microsoft. You can download it from here.

Let's get started.

First, what is Subquery?
- Subqueries in T-SQL provide a way for retrieving data which relies on some “statistical” information. In case of using subqueries, looking at a query from a building block perspective, it has two main parts:

    Main/Outer query (what will be filtered)
    Secondary query (subquery, the filtering side)

We use subquery in the WHERE clause. Depending on the subquery, we do some filtering on the main query. Subqueries can return single, multiple or table-based data. For a single response, we will use **WHERE colx = ( response from subquery )** pattern. On the other hand, for multiple responses, our pattern would be WHERE colx IN ( response from subquery).

There are two types of subqueries in T-SQL:
    Self-contained subqueries
    Correlated subqueries

Self-contained subqueries
This type of subquery has no dependency on the outer/main query. They can be easily executed in isolated context.

Here are some use cases on how to use self-contained subqueries:
USE AdventureWorks2019;
Go
--Retrieve all SalesOrderDetail info WHERE :
-- 1)unitprice is greater than average unit price in the same table.

SELECT * FROM Sales.SalesOrderDetail AS SOD
WHERE SOD.UnitPrice > (SELECT AVG(SOD1.UnitPrice) FROM Sales.SalesOrderDetail AS SOD1)

--2)unitprice is less than or equal to minimum lineTotal's and maximum linetotal's sum dividing to 33;
SELECT * FROM Sales.SalesOrderDetail AS SOD
WHERE SOd.UnitPrice <= (SELECT min(SOD1.LineTotal)+max(SOd1.linetotal)/33 FROM Sales.SalesOrderDetail AS SOD1)

--3) DiscountPct for SpecialOffer is less than or equal to 0.30
SELECT * FROM Sales.SalesOrderDetail AS SOD
WHERE SOD.SpecialOfferID IN (SELECT SO.SpecialOfferID FROM Sales.SpecialOffer AS SO
WHERE So.DiscountPct <=0.30)

--4) StartDate is 2011-04-01 and EndDate is 2014-01-01 for SpecialOffer
SELECT * FROM Sales.SalesOrderDetail AS SOD
WHERE SOD.SpecialOfferID IN (SELECT SO.SpecialOfferID FROM Sales.SpecialOffer AS SO
WHERE So.StartDate >='20110401' AND SO.EndDate <'20140101')

--5) Groupped category's average maxQTY is not null
SELECT * FROM Sales.SalesOrderDetail AS SOD
WHERE SOD.SpecialOfferID IN
(
 SELECT So.SpecialOfferID FROM Sales.SpecialOffer AS SO
 WHERE So.Category IN
 (
  SELECT Category FROM Sales.SpecialOffer AS SO1
  GROUP BY Category
  HAVING AVG(So1.maxQTY) IS NOT NULL))


As you can see from the queries, it is possible to select and execute subquery part of query and get response easily.

Correlated subqueries
This type of subquery has direct dependency on the outer query. So, at least one column from the outer query should participate in the subquery. This will allow us to get “statistical” information related to a given column from the main query.

Here are some use cases on how to use correlated subqueries:
/*
   Retrieve all SpecialOffer information where MinQty is not empty  PER SPECIALOFFERID column
*/
SELECT * FROM Sales.SpecialOffer AS SOD
WHERE SOD.SpecialOfferID IN
(SELECT SO.SpecialOfferId FROM Sales.SpecialOffer AS SO
WHERE SO.SpecialOfferID = SOD.SpecialOfferID AND SO.MinQty IS NOT NULL)

/*
    Show all PurchaseOrderDetail info PER product WHERE listprice is greater than 100
*/
SELECT * FROM Purchasing.PurchaseOrderDetail AS POD
WHERE POD.ProductID IN
(SELECT P.ProductId FROM Production.Product AS P
WHERE P.ProductID = POD.ProductID AND P.ListPrice > 100)


Understanding Subqueries is essential when we need to glean "statistical" information from given or related tables. Self-contained subqueries can be executed in isolated context, meanwhile correlated subqueries depend on the main/outer query.

HostForLIFEASP.NET SQL Server 2021 Hosting



SQL Server 2021 Hosting - HostForLIFE :: XML Shredding In T-SQL

clock July 21, 2022 06:53 by author Peter

T-SQL provides different ways to work, not just with tables, but also with other data containers, such as XML, JSON, etc. In this article, we will talk about two different ways of XML shredding in T-SQL.

What is “shredding XML”?

XML shredding is a specific term for "transforming” XML content into table representation.

Preparation
First of all, we need some XML data. This can be any data (loaded from the internet, custom defined, etc.).

Also, you can store the XML in your drive, directly insert it into your table, or at least define an XML variable and store it inside.

Loading XML
I stored my XML in drive C:/ and using OPENROWSET, and stored it in the @xmlContent variable.

Shredding using OPENXML
The first way of shredding XML is using the OPENXML command. It needs some additional preparation, but we can load big XML content at one time and do any number of manipulations between the scope. Before “parsing” XML to a table, we must prepare XML for parsing. sp_xml_preparedocument is a stored procedure that helps to load XML content into SQL SERVER’s memory (cache). This procedure also provides a way to access already loaded xml using a user-defined handler. This handler is a “pointer” to the memory where we loaded our XML file. This means that there is no need to use the XML variable after retrieving the handler.

After finishing our operations, we need to clear the cache. For that, we have the sp_xml_removeddocument stored procedure.

Shredding using XQuery
XQuery is also a powerful tool when it comes to shredding XML. It is more flexible and relevant for parsing small XML content. As opposed to OpenXml, XQuery doesn’t require any preparation. So, there is no need to build in any procedures to shred the content. XQuery provides special methods to work with XML . In most case we use nodes() and value() to read data.

Using XQuery and OpenXML, we can “convert” XML to table. In technical literature, we call it “shredding”. OpenXML allows you to work with big XML content, but it requires XML to be loaded into memory entirely. On the other hand, XQuery doesn’t load anything into memory and is faster with working small XML data.

HostForLIFEASP.NET SQL Server 2021 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