European Windows 2012 Hosting BLOG

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

SQL Server 2016 Hosting - HostForLIFE.eu :: Restoring A SQL Server Database In Docker

clock June 23, 2020 13:27 by author Peter

Last month I blogged about using Docker to run SQL Server as a quick and easy way to get SQL Server up and running.  While it continues to be immensely useful, there aren’t any user databases  running on it.  The only databases present are the system databases. Yes, I could manually create a database, but it would be a lot easier to have a sample database available.

How do we do restore a sample database, in a container, that is running on a Mac laptop?  Let’s check it out!
 
Disclaimer
Not a container expert so there might be various ways of doing it.  This is just how I’ve figured out how to make the magic happen.
 
Also, if you have not read the first blog on how to get SQL Server running in Docker on your Mac, take a few minutes to read through it.
 
Here are the steps that we will take to make this work,
    Download one of the sample databases from I have a “mssql” directory in my local profile to make things easier
    Make sure the container is started.  You can issue a “docker ps” command terminal to see which containers are running
    Create a directory within the container
    Copy the sample database backup file into the directory you just created
    Restore the database onto the SQL instance that is running within the container

Sounds simple, right? Let’s see!
 
Create a directory
To create a directory within the container (remember that the container is running Linux), we can issue a command to the container that will create the directory.  Using Terminal (you can go to Spotlight to find the Terminal program or it is under Utilities in the Applications folder), execute the following command,
    Docker exec -it sql2019 mkdir /var/opt/mssql/backups  

Let us break that command down,
    Docker – this indicates that we are going to be doing something with Docker
    Exec – this tells the specified container to exec the command we pass into it
    -it – this basically allows for an interactive session with the container
    Sql2019 – this is the name of the container. You can specify the container name when you start the container or Docker will name it for you
    Mkdir – this is short for “make directory”
    /var/opt/mssql/backups – this is the directory path that is to be created.

    Restoring A SQL Server Database In Docker


Copy the Backup File
Now that the directory has been created, we need to get the backup file of the sample database into the container.  In my case, I am using AdventureWorks2017.bak
    Docker cp ./mssql/AdventureWorks2017.bak sql2019:/var/opt/mssql/backups 

Here is how that command breaks down,
    Docker – this indicates that we are going to be doing something with Docker
    cp – this is short for “copy”
    ./mssql/AdventureWorks2017.bak – this is the path of the source file that is being copied into the container. The “.” Indicates start with whatever working directory I am in, which is my profile directory as indicated by the “jmorehouse$”
    Sql2019 – this is the name of the container.
    :/var/opt/mssql/backups – this is the destination directory that is within the container.

Once the command is complete, we can check to make sure that the file was copied successfully.
    Docker exec -it sql2019 ls /var/opt/mssql/backups  

The “ls” refers to “list”.  This is equivalent to executing a “dir” command in DOS.
 
Restoring A SQL Server Database In Docker
 
Restore the Database
The backup file now resides within the container and we just need to tell SQL Server to restore it.  In this section, I will be using Azure Data Studio and native T-SQL commands.
 
Let us first check that SQL Server can see the file.
    RESTORE FILELISTONLY FROM DISK=N’/var/opt/mssql/backups/AdventureWorks2017.bak’ 
    GO 

Restoring A SQL Server Database In Docker
Excellent!  SQL Server can see the backup file which means that we can restore it.  Notice on the left-hand side, there are no user databases, just system databases. Also notice that the physical names of the database shown above are from the Windows Operating System.  Since SQL Server is running on Linux within the container, we will have to move the physical files to a different location.
    RESTORE DATABASE AdventureWorks2017 FROM DISK=N’/var/opt/mssql/backups/AdventureWorks2017.bak’ WITH 
    MOVE ‘AdventureWorks2017’ to ‘/var/opt/mssql/data/AdventureWorks2017.mdf’, 
    MOVE ‘AdventureWorks2017_log’ to ‘/var/opt/mssql/data/AdventureWorks2017_log.ldf’ 
    GO 

Restoring A SQL Server Database In Docker

Above we can see that the database was restored and then subsequently upgraded to the SQL Server 2019 database version.  If you refresh the Databases branch on the left-hand side, the AdventureWorks2017 database is now present!
 
Docker continues to be my current choice of “go to” when I need a quick and easy SQL Server solution to play around.  While I absolutely recommend Azure and its offerings, utilizing Docker on my local laptop is just faster, and frankly, fun to play around it.   Now that I can easily restore databases, it just makes it that much better of a solution for non-production uses.



SQL Server 2016 Hosting - HostForLIFE.eu :: Execute SQL Query In String Format

clock August 23, 2019 11:11 by author Peter

There are times when we need to pass a SQL query as a string that has been created dynamically and execute it on database or from the code. For this purpose, we can use a built-in stored procedure, sp_executesql.

Stored procedure, sp_executesql executes a SQL statement or batch that can be reused many times, or one that has been built dynamically.

Here is the syntax:
sp_executesql [ @stmt = ] statement 

{ , [ @params = ] N'@parameter_name data_type [ OUT | OUTPUT ][ ,...n ]' } 
{ , [ @param1 = ] 'value1' [ ,...n ] } 


Here is an example where SQL is compiled as a string, str1. The SELECT SQL statement is executed via the string parameter passed to the sp_executesql.
declare @str1 nvarchar(200) -----declare a variable 
set @str1='SELECT * FROM tablename' --- set your query to variable 
exec sp_executesql @str1 



SQL Server 2016 Hosting - HostForLIFE.eu :: SQL Server Important System Views and Tables

clock July 17, 2019 12:08 by author Peter

In this article I have listed few methods to know about the list of database, tables, views,etc.., It will be very useful when we trace the database objects in the query window. Even though it can be accessible in the sql server object explorer, but when we write the query it can be customized. That means it can filter the result set based on our requirement.

How to list out the available database in the SQL Server current connection?
Method 1
SP_DATABASES 

Method 2
SELECT name FROM SYS.DATABASES 

Method 3
SELECT name FROM SYS.MASTER_FILES 

Method 4
SELECT * FROM SYS.MASTER_FILES -- Type=0 for .mdf and type=1 for .ldf 
The sp_databases is a system stored procedure it can be listed the database with the size.
The sys.databases will list the databases, created date, modified date and database id along with the other information

The SYS.MASTER_FILES will query the database details like the database id, size, physical storage path and list both mdf and ldf.

How to list the user tables in the database?
The following method can be used to get the list of user tables in the SQL server.

Method 1
SELECT name FROM SYS.OBJECTS WHERE type='U' 

Method 2
SELECT NAME FROM SYSOBJECTS WHERE xtype='U' 

Method 3
SELECT name FROM SYS.TABLES 

Method 4
SELECT name FROM SYS.ALL_OBJECTS WHERE type='U' 

Method 5
SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' 

Method 6
SP_TABLES 

How to list out the Stored Procedures in the database?
Method 1

SELECT name FROM SYS.OBJECTS WHERE type='P' 

Method 2
SELECT name FROM SYS.PROCEDURES 

Method 3

SELECT name FROM SYS.ALL_OBJECTS WHERE type='P'

Method 4
SELECT NAME FROM SYSOBJECTS WHERE xtype='P'

Method 5
SELECT Routine_name FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='PROCEDURE' 

The SYS.OBJECTS table has the common table that has the list for all the procedure, table, triggers, views,etc.., Here procedure can be filtered using the type='p'.

The Information_schema.routines is a view that has used in the SQL server 7.0 version. Now exclusive table available for the stored procedure.

How to list all Views in the database?
Method 1
SELECT name FROM SYS.OBJECTS WHERE type='V' 

Method 2
SELECT name FROM SYS.ALL_OBJECTS WHERE type='V' 

Method 3
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS 

Method 4
SELECT name FROM SYS.VIEWS

How to list out the Functions in the database?
Method 1

SELECT name FROM SYS.OBJECTS WHERE type='IF' -- inline function 

Method 2
SELECT name FROM SYS.OBJECTS WHERE type='TF' -- table valued function 

Method 3
SELECT name FROM SYS.OBJECTS WHERE type='FN' -- scalar function 

Method 4
SELECT name FROM SYS.ALL_OBJECTS WHERE type='IF' -- inline function 

Method 5
SELECT name FROM SYS.ALL_OBJECTS WHERE type='TF' -- table valued function 

Method 6
SELECT name FROM SYS.ALL_OBJECTS WHERE type='FN' -- scalar function

Method 7
SELECT Routine_name FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='FUNCTION'

Note: IF - Inlined Function, TF- Table valued function, FN- Scalar Function

How to get the Triggers in the database?
Method 1

SELECT * FROM SYS.TRIGGERS

Method 2
SELECT * FROM SYS.OBJECTS WHERE type='TR'

How to get the triggers in a table?
Method 1

SP_HELPTRIGGER Products

Method 2
SELECT * FROM SYS.TRIGGERS WHERE parent_id = object_id('products')

How to get the columns in a table?
Method 1

SP_HELP Products

Method 2
SP_COLUMNS Products

Method 3
SELECT * FROM SYS.COLUMNS WHERE object_id = object_id('Products')

Method 4
SELECT COLUMN_NAME,Ordinal_position,Data_Type,character_maximum_length 
FROM INFORMATION_SCHEMA.COLUMNS  
WHERE TABLE_NAME='Products'

How to find the Columns in the table?
Method 1

SELECT O.name FROM SYS.OBJECTS O INNER JOIN SYS.COLUMNS C  
ON C.Object_ID =O.Object_ID  
WHERE C.name LIKE '%ShipName%'

Method 2

SELECT OBJECT_NAME(object_id) AS [Table Name]  
FROM SYS.COLUMNS  
WHERE name LIKE '%ShipName%'

Method 3
SELECT TABLE_NAME  
FROM INFORMATION_SCHEMA.COLUMNS  
WHERE COLUMN_NAME LIKE '%ShipName%'

How to get the Total rows in the table?
Method 1

SELECT COUNT(@@ROWCOUNT) FROM Products

Method 2
SELECT COUNT (ProductID) FROM Products

Method 3
SELECT OBJECT_NAME(id) AS [Table Name],rowcnt  
FROM SYSINDEXES  
WHERE OBJECTPROPERTY(id,'isUserTable')=1 AND indid < 2  
ORDER BY rowcnt DESC

Method 4
SELECT rowcnt FROM sysindexes  
WHERE id = OBJECT_ID('Products') AND indid < 2

Method 5
SELECT OBJECT_NAME(OBJECT_ID) TableName,row_count  
FROM sys.dm_db_partition_stats  
WHERE object_id = object_id('Products') AND index_id < 2

How to get the Check Constraints in the database?
Method 1

SELECT * FROM SYS.OBJECTS WHERE type='C'

Method 2
SELECT * FROM sys.check_constraints

How to find the Indexes in the table?
Method 1

sp_helpindex Products

Method 2
SELECT * FROM sys.indexes  
WHERE object_id = object_id('products')

How to view the View schema definition?
Method 1

SELECT OBJECT_NAME(id) AS [View Name],text  
FROM SYSCOMMENTS  
WHERE id IN (SELECT object_id FROM SYS.VIEWS)

Method 2
SELECT * FROM sys.all_sql_modules  
WHERE object_id IN (SELECT object_id FROM SYS.VIEWS)

Method 3
SP_HELPTEXT ViewName

How to find the table used in the stored procedure?
Method 1

SELECT OBJECT_NAME(id) FROM SYSCOMMENTS S INNER JOIN SYS.OBJECTS O ON O.Object_Id = S.id 
WHERE S.text LIKE '%Products%' 
AND O.type='P'

I hope that the above methods will help you more when you work the query window to find the database objects. Please post your feedback and corrections about this article.



SQL Server 2016 Hosting - HostForLIFE.eu :: SQL Interview Questions And Answers

clock May 22, 2019 06:40 by author Peter

In this post we are going to share the interview questions or the information which you must know as a programmer or a developer, especially if you are a Dot Net developer. I hope you will like this article.

Background

I am a dot net developer. As a dot net developer, there are so many things that I must be aware of. I am sharing those in the form of articles, you can always read my other interview questions here in the following links.

So shall we now discuss about SQL interview questions.

SQL Interview Questions
Question: What are the types of Joins in SQL. Explain?

INNER JOIN: Returns all rows when there is at least one match in BOTH the tables.
LEFT JOIN: Returns all rows from the left table, and the matched rows from the right table.
RIGHT JOIN: Returns all rows from the right table, and the matched rows from the left table.
FULL JOIN: Returns all rows when there is a match in ONE of the table.

Question: What is the default join in SQL? Give an example query?
The default join is INNER JOIN.

Example

SELECT column_name(s)  
FROM table1  
INNER JOIN table2  
ON table1.column_name=table2.column_name;  

Question: Describe all the joins with examples in SQL?
SQL LEFT JOIN
The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.
    SQL LEFT JOIN Syntax  
    SELECT column_name(s)  
    FROM table1  
    LEFT JOIN table2  
    ON table1.column_name=table2.column_name;  


SQL RIGHT JOIN

The right join returns all the rows in the right table i.e. table 2 with the matching ones on the left table (table1).
    SELECT column_name(s)  
    FROM table1  
    RIGHT JOIN table2  
    ON table1.column_name=table2.column_name;  


SQL FULL OUTER
The full join returns all rows from the left table (table1) and from the right table (table2).
    SELECT column_name(s)  
    FROM table1  
    FULL OUTER JOIN table2  
    ON table1.column_name=table2.column_name;  


Question: What is Union and Union All ? Explain the differences?
SQL UNION
The UNION operator is used to combine the result-set of two or more SELECT statements.

Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.

Note: The UNION operator selects only distinct values by default.
    SELECT column_name(s) FROM table1  
    UNION  
    SELECT column_name(s) FROM table2;  
SQL UNION ALL
    SQL UNION ALL Syntax  
    SELECT column_name(s) FROM table1  
    UNION ALL  
    SELECT column_name(s) FROM table2;  

Allows duplicate values.

Question: Differentiate Clustered and Non clustered Index in SQL?
A clustered index is one in which the index’s order is arranged according to the physical order of rows in the table. Due to this reason there can only be one clustered index per table, usually this is the primary key.

A non clustered index is one in which the order of index is not in accordance with the physical order of rows in the table.

Create Index Syntax
CREATE INDEX [ CLUSTERED | NONCLUSTERED ] PIndex ON Persons (LastName,FirstName)

Question: Explain the difference between Stored Procedure and User Defined Function?

Stored Procedure

Stored procedures are reusable code in database which is compiled for first time and its execution plan saved. The compiled code is executed when every time it is called.

Function

Function is a database object in SQL Server. Basically it is a set of SQL statements that accepts only input parameters, perform actions and return the result. Function can return only a single value or a table. We can’t use functions  to Insert, Update, Delete records in the database table(s). It is compiled every time it is invoked.

Basic Difference
Function must return a value but in Stored Procedure it is optional (Procedure can return zero or n values).
Functions can have only input parameters for it whereas procedures can have input/output parameters.

Functions can be called from Procedure whereas Procedures cannot be called from Function.

Advanced Differences

Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it,  whereas Function allows only SELECT statement in it. Procedures cannot be utilized in a SELECT statement, whereas function can be embedded in a SELECT statement. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section, whereas function can be.

The most important feature of stored procedures over function is retention and reusing the execution plan while in case of function it will be compiled every time.
Functions that return tables can be treated as another rowset. This can be used in JOINS with other tables.
Inline Function can be though of as views that take parameters and can be used in JOINS and other Rowset operations.
Exception can be handled by try-catch block in a procedure, whereas try-catch block cannot be used in a Function.
We can use transactions in stored procedure but not in functions.

Conclusion
Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

 



SQL Server 2016 Hosting - HostForLIFE.eu :: How To Check Current Installation Mode In SSAS

clock May 15, 2019 12:36 by author Peter

In this blog, we will learn how we can check which mode of SSAS is installed on our machine. SSAS is available with three modes of installation.

  • Tabular
  • Multidimensional
  • SharePoint

To check which mode of SSAS is installed on your machine, follow the below steps.

  • Open SSMS.
  • Right-click on SSAS Properties.

 

The Mode of Server Name is available in the property window. In our case, SSAS is installed with the Multidimensional mode, so it is showing “Multidimensional”.

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu 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.

 



SQL Server 2016 Hosting - HostForLIFE.eu :: Key Lookups In SQL Server

clock April 10, 2019 10:57 by author Peter

What is a Key Lookup?
One of the easiest things to fix when performance tuning queries are Key Lookups or RID Lookups. The key lookup operator occurs when the query optimizer performs an index seek against a specific table and that index does not have all of the columns needed to fulfill the result set. SQL Server is forced to go back to the clustered index using the Primary Key and retrieve the remaining columns it needs to fulfill the request. A RID lookup is the same operation but is performed on a table with no clustered index, otherwise known as a heap. It uses a row id instead of a primary key to do the lookup.

As you can see these can be very expensive and can result in substantial performance hits in both I/O and CPU. Imagine a query that runs thousands of times per minute that includes one or more key look ups. This can result in tremendous overhead which is generated by these extra reads and it effects the overall engine performance.

Let’s look at an example.
    SELECT [SalesOrderID],[CarrierTrackingNumber],[OrderQty],[ProductID], 
    [UnitPrice],[ModifiedDate]   
    FROM [AdventureWorks2014].[Sales].[SalesOrderDetail]   
    Where [ModifiedDate]> 2014/01/01  and [ProductID]=772
 

The cost of the key lookup operator is 99% of the query. You can see it did an Index Seek to the IX_SalesOrderDetail_ProductID which is very effective, but that index did not have all the columns needed to satisfy the query. The optimizer then went out to the clustered index PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID to retrieve the additional columns it needed. You can see what it got by hovering over the key lookup in the query plan window.

The good thing about Key and RID look ups is that they are super easy to fix. With a little modification to the non-clustered Index IX_SalesOrderDetail_ProductID we can change to query plan from an Index Seek and a Key Lookup to a very small index seek. All we have to do is recreate that index and add the Output List fields as Included columns on that index.
    CREATE NONCLUSTERED INDEX [IX_SalesOrderDetail_ProductID]  
    ON [Sales].[SalesOrderDetail]([ProductID] ASC) 
    INCLUDE ([CarrierTrackingNumber],[UnitPrice], [ModifiedDate], [OrderQty]) 
    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = ON, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)  
    ON [PRIMARY] 


And as you can see, we now have an Index Seek only and a more efficient plan.

Key Lookups can cause performance headaches, especially for queries that run many times a day. Do yourself and your environment a favor and start hunting these down and get them fixed.

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu 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.

 



SQL Server 2016 Hosting - HostForLIFE.eu :: DBCC CLONEDATABASE And Query Store

clock March 27, 2019 09:23 by author Peter

Anyway, by now, you probably have seen documentation on Query Store and DBCC CloneDatabase. Query Store, introduced in SQL Server 2016, is considered the “black box” or “flight recorder” of queries. It retains a history of executed queries, including run-time statistics as well as execution plans from query store enabled databases. This flight recorder helps to diagnosis and pinpoint query performance issues. Another useful tool is DBCC CloneDatabase. This command was released in older versions via service packs before being fully released in 2016. This tool allows you to make a “schema” only copy of a database which will reside on the same server as the source database. The schema includes both user and system schema, as well as any corresponding statistical data.

Why is this useful?
Let’s say you have a 1 terabyte database and wanted to perform query tuning on it. Storage is usually a premium commodity in most organizations and there isn’t a spare terabyte of storage just laying around. DBCC CloneDatabase would allow you to make a schema only copy, including statistics. Once the new database has been created, you could move the new database onto another server without having the requirement of large amounts of storage. Since the database is really a schema-only copy, the footprint of the database is pretty small. After moving the database, queries ran against it would utilize the statistics contained within to execute the query. True, there isn’t any data in the database, but you can account for that when performing query performance analysis.

DBCC CLONEDATABASE (source_database_name, target_database_name) WITH [NO_STATISTICS],[NO_QUERYSTORE],[VERIFY_CLONEDB],[BACKUP_CLONEDB]

  • NO_STATISTICS
    This option specifies that table/index statistics are excluded. Available with SQL Server 2014 SP2 CU3 & SQL Server 2016 SP1

  • NO_QUERYSTORE
    This option specifies that query store data is excluded. Available with SQL Server 2016 SP1

  • VERIFY_CLONEDB
    Verifies the consistency of the new cloned database. Available starting with SQL Server 2016 SP2

  • BACKUP_CLONEDB
    Creates and verifies a backup of the newly cloned database. Available starting with SQL Server 2016 SP2

The command works in this order,

  1. Creates a new destination database. Same file layout as the source database however with the default file sizes from Model.
  2. Generates a snapshot of the source database.
  3. Copies the system metadata from the source to the target database created in step 1.
  4. All object schema is copied from the source to the target.
  5. Index statistics are copied from the source to the target.

Fairly easy and straightforward. But wait! There’s more!

You will notice the “WITH NO_QUERYSTORE” option in the command. If you are running SQL Server 2016 SP1 or higher and utilizing the Query Store for the source database, DBCC CloneDatabase will also bring over the query store data! This is enabled by default so if you do not want the query store data, you have to explicitly define using NO_QUERYSTORE. This means, by default, if you clone a database you will get the flight recorder data from the query store as well.

These two tools, query store and DBCC CloneDatabase, are just another means to help troubleshoot performance issues.

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu 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.



SQL Server 2016 Hosting - HostForLIFE.eu :: Encrypt And Decrypt Column Data In SQL Server

clock March 13, 2019 09:26 by author Peter

Recently, I worked on a project to hide sensitive data. Basically, the client wanted sensitive data to be encrypted, then accessed and decrypted by the application only. In case a hacker or an employee or a DBA accesses data directly, they can't read the field. Some perfect examples are customer's credit card number, date of birth, social security, or even medical records.

SQL Server provides a feature that allows DBAs and data developers to encrypt and save encrypted data on a column level. Once a column is encrypted, it's not readable by humans.

In this blog, let's see how this can be acheieved.
In the below example, I have used the Credit Card Number column to be encrypted.

You need to write a stored procedure to execute a set of statements and queries. Though it is not a foolproof way to encrypt or decrypt at the database level, while working on this task, I learned some good techniques and features of SQL Server.

There are 3 major factors to encrypt data at the column level, as below.

  • Master Key -  a key which is used to protect the keys of certificates and symmetric keys in the database
  • Certificates - used to encrypt the data in the database
  • Symmetric Key - can be encrypted by using many options, like certificate, password, symmetric key. There are different algorithms available for encrypting a key. The supported algorithms are DES, TRIPLE_DES, RC2, RC4, RC4_128, DESX, AES_128, AES_192, and AES_256.

So, let's start step by step and achieve the encryption and decryption.

Step 1
Create a Master Key first with the help of the below script.
use TestingDB; //This is the Test Database created.  
Create master key encryption by password ='abc123' 


Step 2
Once the Master Key is created, now it's time to create a Certificate.
Create certificate C1 with subject = 'Credit Card Data'

Step 3
Now with the help of certificate and master key create SYMMETRIC KEY.
Create symmetric key SK1 with algorithm = AES_256 encryption by certificate C1.
Once all these KEYs are created in the database, we can use those for encrypting and decrypting data.

Below is the script to encrypt the data in the column. Here I have created one TABLE named TestEncryption having 3 columns with its datatype as below. Note that the column in which we want to insert or update encrypted data should have VARBINARY as the datatype.

Id - INT
EncryptedCCNumber - varbinary (256)
CCNumber - Numeric(18,0)


Let's insert data in the column of the table,
Open symmetric key SK1
Decryption by certificate C1
insert into TestEncryption(Id, EncryptedCCNumber, CCNumber) values (1, ENCRYPTBYKEY(key_guid('SK1'),'5000'), '5000')

Close symmetric key SK1
Now it's time to check if the data is encrypted or not so when you execute a simple query you will get the data from the Table as it is.
select * from TestEncryption 

IF you want to DECRYPT the data you can use the below script
Open symmetric key SK1
Decryption by certificate C1
select *, convert(varchar, DECRYPTBYKEY(EncryptedCCNumber)) as 'Decrypted CC Number' from TestEncryption

Close symmetric key SK1
You will get an extra column named "Decrypted CC Number". This way we can insert/update and select the encrypted data from the table in SQL Server.

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu 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.



SQL Server 2016 Hosting - HostForLIFE.eu :: About Views in SQL Server

clock March 6, 2019 10:06 by author Peter

What a View is
A view is a virtual table in the database whose contents are defined by a query.
A view appears just like a real table, with a set of named columns and rows of data. Unlike a real table, a view does not exist in the database as a stored set of data values. Instead, the rows and columns of data are generated from the query results defined by the View.

Types of Views in SQL Server
System Views

  • Information Schema View.
  • Catalog view
  • Dynamic Management View (DMV)

User Defined Views

  • Simple View
  • Complex View

create table Authors 

AuthordId int, 
AuthorName varchar(Max), 
Article varchar (Max), 
AuthorRank int 

-------Inserting Data into Authors Table---- 
Insert into Authors values (1,'Mahesh Chand','C# fundamentals',1) 
Insert into Authors values (2,'PraveenKumar','Wpf',20) 
Insert into Authors values (3,'Dhananjaykumar','windowsApplication',3) 
Insert into Authors values (4,'PinalDeve','SqlTrace',4) 
Insert into Authors values (5,'Abhinav','oops',2) 
Insert into Authors values (6,'Abhijit','WCF',5) 
Insert into Authors values (7,'Amit','DatabaseMirroring',7) 
Insert into Authors values (8,'Karthik','ssis',8) 
Insert into Authors values (9,'Divya','WebApi',9) 

(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)


System Views

System Views are predefined Views that already exist in the Master database of SQL Server. These System Views are used as template Views for all newly created databases. These system Views will be automatically created for any user defined database.

Information Schema View
The Information Schema Views are used to display information of a database, such as tables and columns. In SQL Server there are nearly twenty different Information Schema Views.
Example: To determine the complete information of an Authors table using an Information Schema View:
---To see the detail information of Authors Table 
Select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Authors' 

TABLE_CATALOG TABLE_SCHEMA TABLE_NAME COLUMN_NAME
C#Corner dbo Authors AuthordId
C#Corner dbo Authors AuthorName
C#Corner dbo Authors Article
C#Corner dbo Authors AuthorRank

Catalog view
Catalog Views are used to show database self-describing information.
Catalog views are also used to return information that is used by the SQL Database Engine like objects, logins permissions and so on.

Example:

  1. --For list of all Views in a Database  
  2. select * from sys.all_views  
  3. ---For list of tables in a database  
  4. select * from sys.tables 

Dynamic Management View (DMV)
DMVs are introduced in SQL Server 2005.
DMVs gives the database administration information about the current state of SQL Server machine on various aspects.
DMVs are easier to detect the health of SQL Server using these views.
DMVs replace many of the DBCC Commands.
All Dynamic Management Views (DMVs) exist in the sys schema and follow this naming convention dm_*.
There are two types of DMVs.

1. Server-scoped DMV
Server-scoped DMVs are Stored in Master Database.
Server-scoped DMVs are used to for the state of an entire SQL Server instance.
Server-scoped DMVs require VIEW SERVER STATE PERMISSION on the server.

2. Database-scoped DMV
Database-scoped DMVs are stored specific to each database.
Database-scoped DMVs require DATABASE STATE PERMISSION on the database.

The following are some of the Dynamic Management Views:
Sys.dm_exec_Cached_plans: Returns the information about query Execution Plans that are cached by SQL-SERVER for faster query execution.
Sys.dm_exec_Query_plan: Returns the show plan in XML format for a T-SQL batch.
Sys.dm_exec_Query_stats: Returns aggregate performance statistics for Cached Query Plans.
Sys.dm_exec_requests: Returns information about each request that is executing within SQL Server.

User Defined Views
These are the views that are defined by the user as per the their requirements.

Simple view
A simple view is one that can be addressed by DML statements as well as SELECT. As might be expected, simple views are based on relatively simple SELECT statements.
It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted data in the table the view was created with. It should also be noted that as data in the original table data changes.
A simple view can be created from a single table.
A simple view does not contain functions.
A simple view does not contain a group of data.

Complex View
We use Complex Views when we want to display data from two or more tables, using a group cluase or a grouping of aggregate functions.
A Complex View can be created from one or more table.
A Complex View contains functions.
A Complex View contains a group of data,

Creating Views
We can create views in 2 ways.

  1. Through Query Designer.
  2. Through Database

Through Query Designer
Database views are created using the CREATE VIEW statement. Views can be created from a single table, multiple tables, or another view.
Syntax:
Create view view_Name
As
....Ur Query.....

Example:
Create view Authors Info

As
Select AuthorName,Article,Rank from Authors

Using SQL Server Management Studio

To create a view using the Query and View Designers:

  1. In Object Explorer, expand the database where you want to create your new view.
  2. Right-click the Views folder, then click New View.
  3. In the Add Table dialog box, select the table that you want to include in your new view from one of the following tabs: Tables, Views, Functions, and Synonyms.
  4. Click Add, then click Close.
  5. In the Query Design Pane, select the columns or other elements to include in the new view.
  6. In the Criteria Pane, select additional sort or filter criteria for the columns.
  7. On the File menu, click Save view name.
  8. In the Choose Name dialog box, enter a name for the new view and click OK.

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu 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.



SQL Server 2016 Hosting - HostForLIFE.eu :: Difference Between TRUNCATE, DELETE, And DROP In SQL Server

clock February 27, 2019 11:25 by author Peter

The difference between TRUNCATE, DELETE, and DROP is one of the most common interview question. Here are some of the common differences between them.

TRUNCATE

TRUNCATE SQL query removes all rows from a table, without logging the individual row deletions.

The following example removes all data from the Customers table.

TRUNCATE TABLE Customers;  
TRUNCATE is a DDL command
TRUNCATE is executed using a table lock and whole table is locked for remove all records.
We cannot use WHERE clause with TRUNCATE.
TRUNCATE removes all rows from a table.
Minimal logging in transaction log, so it is performance wise faster.
TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.
Identify column is reset to its seed value if table contains any identity column.
To use Truncate on a table you need at least ALTER permission on the table.
Truncate uses the less transaction space than Delete statement.
Truncate cannot be used with indexed views.
TRUNCATE is faster than DELETE.

DELETE
To execute a DELETE queue, delete permissions are required on the target table. If you need to use a WHERE clause in a DELETE, select permissions are required as well.

The following query deletes all rows from the Customers table. 
DELETE FROM Customers; 
GO


The following SQL query deletes all rows from the Customers table where OrderID is greater than 1000.

DELETE FROM Customers WHERE OrderId > 1000; 
GO 


DELETE is a DML command.
DELETE is executed using a row lock, each row in the table is locked for deletion.
We can use where clause with DELETE to filter & delete specific records.
The DELETE command is used to remove rows from a table based on WHERE condition.
It maintain the log, so it slower than TRUNCATE.
The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row.
Identity of column keep DELETE retain the identity.
To use Delete you need DELETE permission on the table.
Delete uses the more transaction space than Truncate statement.
Delete can be used with indexed views.

DROP
DROP table query removes one or more table definitions and all data, indexes, triggers, constraints, and permission specifications for those tables. DROP command requires ALTER permission on the schema to which the table belongs, CONTROL permission on the table, or membership in the db_ddladmin fixed database role.

The following SQL query drops the Customers table and its data and indexes from the current database.
DROP TABLE Customers ; 

The DROP command removes a table from the database.
All the tables' rows, indexes and privileges will also be removed.
No DML triggers will be fired.
The operation cannot be rolled back.
DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command.
DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu 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.

 



About HostForLIFE.eu

HostForLIFE.eu 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in