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 :: ANSI_NULLS In SQL Server

clock October 18, 2022 08:53 by author Peter

ANSI_NULLS define the comparison rule for NULL values in SQL Server.
 
When SET ANSI_NULLS is OFF, the Equals (=) and Not Equal To (<>) comparison operators do not follow the ISO standard. A SELECT statement that uses WHERE column_name = NULL returns the rows that have null values in column_name.
 
Example

But when SET ANSI_NULLS is ON, a SELECT statement that uses WHERE column_name = NULL returns zero rows even if there are null values in column_name.
 
Example

HostForLIFEASP.NET SQL Server 2019 Hosting

 



European SQL Server 2019 Hosting :: SQL Server Primary Keys

clock October 14, 2022 08:51 by author Peter

Introduction
Hope you're familiar with the concepts of what's a primary key in a relational database management system like SQL Server. But, you need more details to better understand it, or you need some review or refresher for yourself, you have come to the right place.

This article will discuss a primary key, entity integrity, primary key constraint, composite keys, and the benefits of a primary key.

Let's get started.

What's A Primary Key?

A primary key is a logical concept where a column or field uniquely identifies each record inside a database table. Moreover, it has multiple attributes: it must not be null, and it must be unique.

Easy to remember, right? But if you're curious, we'll test and see what will happen when we try to pass a NULL and duplicate value in a primary column in the latter part of the article.
What's Entity Integrity?

Entity integrity is a rule for practical database construction, and this practice is widely used. It is a process of enforcing the primary key for each table in a database.

Therefore, it is implemented to uniquely identify each row inside the table by specifying a primary key inside our database table.
What's a Primary Key Constraint?

A primary key constraint is a restriction that basically ensures entity integrity.

Note: Unique constraint also ensures entity integrity.
Benefits of Primary Key and Entity Integrity

Proper usage and selection of a primary key and maintaining entity integrity prevent duplicate records and other issues that would indirectly compromise the integrity of the database.

Things to Remember About Primary Keys
    A primary key column cannot have NULL values.
    A primary key column cannot have duplicate values.
    A table can have only one primary key constraint.
    When multiple columns are used as primary keys, they are called composite keys.
    It is good to remember that a primary key is the default clustered index if a clustered index on the table does not exist.

Composite Keys
Now, you might ask why I see multiple primary keys in one table? Those are called composite keys.

Composite keys use two or more fields from a table to create a unique value.

Therefore, it guarantees uniqueness only when combined columns, but they don't guarantee uniqueness individually.

Creating A Primary Key on A Table
Let's show how we can define a column as a primary key.
CREATE TABLE EMPLOYEE(
[Id] int NOT NULL IDENTITY(1,1),
[FirstName] nvarchar(50),
[LastName] nvarchar(50),
[Age] int,
PRIMARY KEY (Id))


In the code sample above, we have seen that using the PRIMARY KEY then passing the column Id, we have defined the primary key of the EMPLOYEE table.

Let's try to see the result below.

Add a Primary Key on A Table
Let's recreate the table from the previous example, but we will not create the primary key.
We will create a primary key after we have created the table.
Let's try to see the code sample below.
IF EXISTS (SELECT * FROM  [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_NAME] ='EMPLOYEE')
BEGIN
    DROP TABLE EMPLOYEE;
END
GO
BEGIN
CREATE TABLE EMPLOYEE(
    [Id] int NOT NULL IDENTITY(1,1),
    [FirstName] nvarchar(50),
    [LastName] nvarchar(50),
    [Age] int);
END
GO
BEGIN
ALTER TABLE EMPLOYEE ADD PRIMARY KEY(Id);
END

Just a note, if you have removed the IDENTITY (1,1), everything will still be good and have no errors because it's an auto-incrementing column.

Although these two are used together, there's no requirement when defining a primary key column that it needs to be an identity column.

Let's try to see an example below.
IF EXISTS (SELECT * FROM  [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_NAME] ='EMPLOYEE')
BEGIN
    DROP TABLE EMPLOYEE;
END
GO
BEGIN
CREATE TABLE EMPLOYEE(
    [Id] int NOT NULL,
    [FirstName] nvarchar(50),
    [LastName] nvarchar(50),
    [Age] int);
END
GO
BEGIN
ALTER TABLE EMPLOYEE ADD PRIMARY KEY(Id);
END

Again, another note, if we have forgotten the NOT NULL that makes the Id column nullable, it will give you an error.

You'll probably see an error like this
    "Cannot define a PRIMARY KEY constraint on nullable column in table 'EMPLOYEE.'"

Let's try to see an example below.
IF EXISTS (SELECT * FROM  [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_NAME] ='EMPLOYEE')
BEGIN
    DROP TABLE EMPLOYEE;
END
GO
BEGIN
CREATE TABLE EMPLOYEE(
    [Id] int, -- NOT NULL REMOVED FOR YOU TO SEE THE ERROR MESSAGE
    [FirstName] nvarchar(50),
    [LastName] nvarchar(50),
    [Age] int);
END
GO
BEGIN
ALTER TABLE EMPLOYEE ADD PRIMARY KEY(Id);
END


Let's try to see the result below.


Delete Primary Key on A Table
In this section, let's try to recreate the table again, but after creating the table, let's make a primary key with the name of [PK_ON_EMPLOYEE_TABLE].
The reason for giving the primary key a custom name is so we won't have a hard time knowing its name when we need to drop the primary key.

Let's try to see the example below.

PRINT 'STEP 0. DROP EMPLOYEE TABLE IF EXISTS'

IF EXISTS (SELECT * FROM  [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_NAME] ='EMPLOYEE')
BEGIN
    PRINT 'STEP 0.1 DROPPING EMPLOYEE TABLE'
    DROP TABLE EMPLOYEE;
END
GO

PRINT 'STEP 1. CREATE THE TABLE'

BEGIN
CREATE TABLE EMPLOYEE(
    [Id] int NOT NULL IDENTITY(1,1),
    [FirstName] nvarchar(50),
    [LastName] nvarchar(50),
    [Age] int);
PRINT 'STEP 1.1 EMPLOYEE TABLE CREATED'
END
GO

BEGIN
PRINT 'STEP 2. EMPLOYEE TABLE ADDING PRIMARY KEY [PK_ON_EMPLOYEE_TABLE]'
ALTER TABLE EMPLOYEE ADD CONSTRAINT [PK_ON_EMPLOYEE_TABLE] PRIMARY KEY(Id);
END
GO

BEGIN
PRINT 'STEP 3. EMPLOYEE TABLE REMOVING THE PRIMARY KEY'
ALTER TABLE EMPLOYEE
DROP CONSTRAINT [PK_ON_EMPLOYEE_TABLE];
END

Inserting NULL values into Primary Key Column
This obviously will show an error because we're violating the primary key constraint.
Still, we'll see how the SQL Server will react when inserting NULL values out of curiosity.

Let's try to see an example below.
IF EXISTS (SELECT * FROM  [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_NAME] ='EMPLOYEE')
BEGIN
    DROP TABLE EMPLOYEE;
END
GO
BEGIN

CREATE TABLE EMPLOYEE(
    [Id] int NOT NULL,
    [FirstName] nvarchar(50),
    [LastName] nvarchar(50),
    [Age] int);
END
GO

BEGIN
ALTER TABLE EMPLOYEE ADD PRIMARY KEY(Id) ;
END
GO

BEGIN
--LET'S INSERT NULL value and expect an error
INSERT INTO [dbo].[EMPLOYEE] ([Id],[FirstName],[LastName],[Age])
VALUES
(NULL, 'Jin', 'Necesario', 100)
END
GO


Let's try to see the result below.

Inserting Duplicate Values into Primary Key Column
Again, this will obviously show an error because we're violating the primary key constraint. Still, we'll see how the SQL Server will react when inserting duplicate values out of curiosity.

Let's try to see an example below.
IF EXISTS (SELECT * FROM  [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_NAME] ='EMPLOYEE')
BEGIN
    DROP TABLE EMPLOYEE;
END
GO
BEGIN

CREATE TABLE EMPLOYEE(
    [Id] int NOT NULL,
    [FirstName] nvarchar(50),
    [LastName] nvarchar(50),
    [Age] int);
END
GO

BEGIN
ALTER TABLE EMPLOYEE ADD PRIMARY KEY(Id) ;
END
GO

BEGIN
--LET'S INSERT SAME Id value of 1 and expect an error
INSERT INTO [dbo].[EMPLOYEE] ([Id],[FirstName],[LastName],[Age])
VALUES
(1, 'Jin', 'Necesario', 100),
(2, 'Vincent','Necesario', 100),
(1, 'Jin Vincent','Necesario', 100)
END
GO


Let's try to see the result below.

HostForLIFEASP.NET SQL Server 2019 Hosting

 

 



European SQL Server 2019 Hosting :: Call Any Web API & Web Service From SQL Server

clock September 9, 2022 07:36 by author Peter

Enable configuration in SQL
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO

Sample API link

-- Sample API Link
http://sbankapi7.somee.com:80/api/Member/GetDataFromServerByMobile

Sample JSON Request
@Mobile varchar(max),
@Flag varchar(max)

{
  "CID": 0,
  "CName": "",
  "AC_Balance": "",
  "AC_No": "",
  "AC_ID": "",
  "CDOB": {},
  "CEmail": "",
  "ReciverEmail": "",
  "CMObile": "'+@Mobile+'",
  "CGender": "",
  "CPan": "",
  "CAdhaar": "",
  "CNationality": "",
  "CAddress": "",
  "City": "",
  "State": "",
  "Country": "",
  "PinCode": "",
  "Cisdelete": 0,
  "CreatedBy": 0,
  "CreatedDate": {},
  "ModifiedBy": 0,
  "ModifiedDate": {},
  "UID": 0,
  "CustImgPath": "",
  "CustAdaarPath": "",
  "CustPanPath": "",
  "Flag": "'+@Flag+'",
  "OpMsg": "",
  "Pass": ""
} '

Content Type
application/json

Create Store Procedure for Calling Web API.
--//========================
    -- if you learn more please visit my blog

  -- https://saipathrikar.blogspot.com/
--//========================
--================ execute this 1st for 1st time use only

Create Proc Proc_CallApiFromSQL
(
@Mobile varchar(max),
@Flag varchar(max)
)
as
Declare @Object as Int;
Declare @ResponseText as Varchar(8000);
 declare @json table (Json_Table nvarchar(max))
 declare @body varchar(max)
 declare @Apilink varchar(max)
 set @Apilink='http://sbankapi7.somee.com:80/api/Member/GetDataFromServerByMobile';
 set @body='

 {
  "CID": 0,
  "CName": "",
  "AC_Balance": "",
  "AC_No": "",
  "AC_ID": "",
  "CDOB": {},
  "CEmail": "",
  "ReciverEmail": "",
  "CMObile": "'+@Mobile+'",
  "CGender": "",
  "CPan": "",
  "CAdhaar": "",
  "CNationality": "",
  "CAddress": "",
  "City": "",
  "State": "",
  "Country": "",
  "PinCode": "",
  "Cisdelete": 0,
  "CreatedBy": 0,
  "CreatedDate": {},
  "ModifiedBy": 0,
  "ModifiedDate": {},
  "UID": 0,
  "CustImgPath": "",
  "CustAdaarPath": "",
  "CustPanPath": "",
  "Flag": "'+@Flag+'",
  "OpMsg": "",
  "Pass": ""
} '

Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'post',@Apilink,'false'
EXEC sp_OAMethod @Object, 'setRequestHeader', null, 'Content-Type', 'application/json'
Exec sp_OAMethod @Object, 'send', null, @body
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT

  INSERT into @json (Json_Table) exec sp_OAGetProperty @Object, 'responseText'
-- select the JSON string
--select * from @json
-- Parse the JSON string
SELECT * FROM OPENJSON((select * from @json))
WITH (
CID bigint,CName varchar(max),AC_Balance varchar(max),AC_No varchar(max),AC_ID bigint,CDOB datetime,
CEmail varchar(max),ReciverEmail varchar(max),CMObile varchar(max),CGender varchar(max),CPan varchar(max),
CAdhaar varchar(max),CNationality varchar(max),CAddress varchar(max),City varchar(max),State varchar(max),
Country  varchar(max),PinCode varchar(max),Cisdelete bit,CreatedBy varchar(max),CreatedDate datetime,ModifiedBy varchar(max),
ModifiedDate datetime,UID bigint,CustImgPath varchar(max),CustAdaarPath varchar(max),CustPanPath varchar(max),
Flag varchar(max),OpMsg varchar(max),Pass varchar(max)
)
return

Execute Stored Procedure

EXEC  Proc_CallApiFromSQL '8541254874','SE'

Output

HostForLIFEASP.NET SQL Server 2019 Hosting



European SQL Server 2019 Hosting :: Create Sequence In SQL

clock September 7, 2022 10:45 by author Peter

Create Sequence in SQL
CREATE SEQUENCE Seq_AccountNumber As BigInt
Start with 100001
INCREMENT BY 1
MINVALUE 1
MAXVALUE 999999999999999999
CYCLE
CACHE;


Use Sequence in Procedure for generating numbers Like "Sbank_10001".
CREATE Proc Proc_GenerateAccountNumber
as
Declare @BnkName varchar(100)='Sbank_';
Declare @AccountNumber varchar(max);

SELECT @AccountNumber =CONCAT(@BnkName ,
 next value for dbo.Seq_AccountNumber
)
SELECT @AccountNumber as AccountNumber
Return


Now execute procedure "Proc_GenerateAccountNumber" & check output

If you want to restart Sequence Alter Sequence,
alter sequence dbo.Seq_AccountNumber Restart with 10001

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 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