European Windows 2012 Hosting BLOG

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

European SQL 2016 Hosting - :: Multiple SQL Operation In Single Procedure

clock June 30, 2020 13:10 by author Peter

In this blog, I will show you how to write multiple SQL Statements in one procedure. Instead of writing separate procedures for Select, Insert, Delete and Update operations into the table, I am going to show you how to combine all operations into one single Stored Procedure.

This Table is called tblEmployee with the below structure:
We want to write a procedure for this table for Select, Insert, Delete and Update records.

Instead of writing separate a stored procedure for each operation we are going to write only one stored procedure to perform Select, Insert, Delete and Update records.

How To Achieve It?
Are you wondering how to accomplish this? It is simple -- just add a parameter to the stored procedure. Depending on this parameter we are going to execute the appropriate operations.

Here is the stored procedure:
Createprocedure [dbo].[USP_Employee] @empid asint=0, @empname asvarchar(50)=NULL, @age asint=0, @salary asint=0, @dob asvarchar(20)=NULL, @designation asvarchar(50)=NULL, @Reqtype asvarchar(10)=NULL AS  
BEGINIF @Reqtype='SELECT'   
SELECT empid,   
FROM   tblemployee   
ENDIF @Reqtype='INSERT'   
insertinto tblemployee VALUES(@empid,@empname,@age,@salary,@dob,@designation)   
ENDIF @Reqtype='DELETE'   
deletefrom tblemployee WHERE [email protected]   
ENDIF @Reqtype='UPDATE'   
UPDATE tblemployee   
SET    [email protected],   
       [email protected],   
       [email protected],   
       [email protected],   
       [email protected]   
WHERE  [email protected]   

In the above example, based on the @Reqtype column the corresponding sql command will execute. For example, if the @Reqtype is select then select statement will execute. If the @Reqtype is inserted then Insert statement will execute.

In this blog, we have learned how to write multiple SQL operations into a single SQL procedure.

European SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

SQL Server 2016 Hosting - :: Subqueries And Correlated Subqueries

clock June 24, 2020 12:53 by author Peter

Subqueries In SQL Server
Subqueries are enclosed in parentheses. Subquery is also called an inner query and the query which encloses that inner query is called an outer query. Many times subqueries can be replaced with joins.
    select * from Employee where DepartmentID not in (select distinct DepartmentID from Department) 

Another example:
    select Department_Name,(select count(*) from Employee where DepartmentID=d.DepartmentID) from Department as d; 

The above query is an example of using subquery in the select list. The above result can be achieved using join also; see the below query
    select d.Department_Name,COUNT(e.empid) as empcount from Department d 
    join Employee e on e.DepartmentID=d.DepartmentID 
    group by d.Department_Name 
    order by empcount; 

According to MSDN, you can nest up to 32 levels.
Columns present in subqueries cannot be used in the outer select list of a query.
Correlated Subqueries
If our subquery depends on the outer query for its value then it is called a Correlated Subquery. It means subquery depends on outer subquery. Correlated subqueries are executed for every single row executed by outer subqueries.
A correlated subquery can be executed independently,
select distinct Department_Name,(select count(*) from Employee where DepartmentID=d.DepartmentID group by DepartmentID) as empcount from Department as d order by empcount; 

What to choose for performance --  Subquery or Join?
According to MSDN, there is no big difference between queries that use sub-queries and joins.
But in some cases, we need to check the performance, and Join produces better performance because the nested query must be processed for each result of the outer query. In such cases, JOIN will perform better.
In general, JOIN works faster as compared to subqueries but in reality, it will depend on the execution plan generated by the SQL Server. If the SQL server generates the same execution plan then you will get the same result.

SQL Server 2016 Hosting - :: 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!
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’ 

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’ 

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 - :: What Is Batch Mode On Rowstore In SQL Server

clock June 17, 2020 13:24 by author Peter

Under compatibility level 150, in both SQL Server 2019 and Azure SQL Database, you now can use batch mode for CPU-bound analytic type workloads without requiring columnstore indexes. There is no action needed to turn on batch mode aside from being on the proper compatibility mode. You also have the ability to enable it as a database scoped configuration option (as shown below), and you can hint individual queries to either use or not use batch mode (also shown below). If you recall in my earlier blogs on columnstore, it is batch mode in conjunction with page compression that drastically increases query performance. This feature, Batch Mode on Rowstore, allows all operators enabled for batch mode to operate as such in SQL Server.

What does this mean? It means that query operations can process data faster, more efficiently and mimic what makes columnstore so fast. Instead of reading row by row (row store mode) it can read in chunks i.e. batches of 900 rows at a time. The performance impact of this can be tremendous which effectively uses CPU more efficiently.
Just like columnstore this only benefits analytic type workloads or data warehouses, as mentioned above. This is meant for aggregations and joins that process thousands of rows. It will not benefit you when processing singleton lookups. If where clause that does not look up a range of values and is just satisfying predicates, then batch mode does not provide a benefit.
How does the engine know when to use batch mode? According to the query processor uses heuristics and will make decision based on three checks. An initial check on tables sizes, operators used and cardinality estimates. Then the optimize checks to see if there are cheaper plans it can use. If no alternative better plans are available, the optimizer will choose batch mode. There are some limitations that will prevent the use of batch mode such as, in-memory OLTP tables or for any index other than B-Trees or on-disk heaps. It will also not work for LOB columns including sparse and XML columns.
You can easily decipher when batch mode is used to run query inside the operator’s properties. Let’s see a demo.
To demo I want to first show you a plan NOT using Batch Mode on Row Store, so let’s turn the feature off because as I mentioned earlier it is already enabled for compatibility mode 150 by default. Run the below database scope configuration script to turn it off.
    USE AdventureworksDW2016CTP3 

Now let’s run this query and make sure we capture the execution plan.
    SELECT FS.[ProductKey], 
    FROM [dbo].[FactResellerSalesXL] FS 
        JOIN dbo.DimProduct DP 
            ON DP.ProductKey = FS.ProductKey 
    GROUP BY FS.[ProductKey], 

Note the Table Scan. By hovering over it you can see the operator’s properties and see the Actual Execution Mode says ROW and it processed 11,669,653 rows.

Now let’s run it again in Batch. Instead of changing compatibility lets just turn on the feature with an OPTION HINT.

SELECT FS.[ProductKey], 
FROM [dbo].[FactResellerSalesXL] FS 
    JOIN dbo.DimProduct DP 
        ON DP.ProductKey = FS.ProductKey 
GROUP BY FS.[ProductKey], 

You can clearly see the optimizer chose to use BATCH mode based on our HINT. In addition, you can see it ran significantly faster at only 405 ms versus 1.119s using row mode. In general, we’ve seen queries that benefit from batch mode running in almost half of what row mode performance is and columnstore in batch mode performance.

Let’s go ahead and change back to the default Batch Mode again for our database just to prove it would have used batch mode without the use of our hint. Run the below and look at the plan.

    SELECT FS.[ProductKey], 
    FROM [dbo].[FactResellerSalesXL] FS 
        JOIN dbo.DimProduct DP 
            ON DP.ProductKey = FS.ProductKey 
    GROUP BY FS.[ProductKey], 

BINGO! There you have it!

If you are already using compatibility mode 150 you are already taking advantage of this feature and may not even realized. For those that have not made the leap to 2019 I highly recommend it, if only for this little gem which is one of the many reasons why you should upgrade.

SQL Server 2016 Hosting - :: Max Degree Of Parallelism Vs Cost Threshold For Parallelism

clock May 8, 2020 10:09 by author Peter

The title sounds like something that you would see for a boxing match. However, in reality it is a misleading title. The Max Degree of Parallelism and the Cost Threshold for Parallelism SQL Server settings actually work more together than they do against each other.

These two settings actually define the how many and the when in regards to parallel execution plans. The Max Degree of Parallelism (MDop) simply defines the number of processors/cores that SQL Server will use when the optimizer determines parallelism is needed. The Cost Threshold for Parallelism is cost threshold of when the SQL Server will use parallelism. The cost is the overall cost the optimizer determines for each query and SQL Server will use parallelism if the cost is above the threshold value.

The recommended settings for MDop is the number of cores not to exceed 8. However, when setting this, it is important to continue to monitor the system to see if the change has caused an improvement. The default value is 0.
The recommended setting for the Cost Threshold for Parallelism is 25 to 50 and has a default value of 5. Yes, the default setting is too low. By changing this, SQL Server will reduce the number of smaller queries that may use parallelism. Just like the MDop setting, it is important to monitor the server after making a change to see if an improvement is make. There have been many times where simply changing this setting from the default, I have seen the CPU utilization drop from close to 100% to less than 10%. This in no way means you will see the same improvement, just what I have seen.
Neither one of these settings require a reboot of the service when changing. It is also important to keep in mind that if the MDop is set to 1, SQL Server will ignore the Cost Threshold for Parallelism setting.
This snippet of code can be used to query server configuration settings
    SELECT CONVERT(VARCHAR(60), name) AS 'Name' 
    , value 
    , description 
    FROM sys.configurations

SQL Server 2016 Hosting - :: Could Not Find Server 'Server Name' In sys.servers In SQL Server

clock April 29, 2020 07:39 by author Peter

I was working with a client and they had set up one sql server for an ETL process. When we tried to get the data from  the database we got the error:
"Could not find server 'server name' in sys.servers in SQL Server"

How to resolve this
First you need to check if the server exists in sys servers,
select name from sys.servers 

You will get the servers list here, if the server does not exist in the list, then add it using the command,
EXEC sp_addlinkedserver @server = 'New_Server_Name' 

Once the server is added to the linked server, then you can log in like this,
EXEC sp_addlinkedsrvlogin 'New_Server_Name','false',NULL,'USERNAME','PASSWORD' 

Now you can do whatever you want to do, you can use your local server now,
exec [New_Server_Name].[Database_Name].dbo.Procedure_NAME

Finally, you can drop this server from the linked server list using this command,
sp_dropserver 'New_Server_Name', 'droplogins' 

SQL Server 2016 Hosting - :: Apply a Single Script for Multiple Databases Using Database Name

clock April 17, 2020 07:12 by author Peter

Hi all, In this blog, I will explain to you how to apply a script or a query to multiple databases in a single execution using a database name. I get all database names, create a loop, and execute a command that I want to do.

Here I am using 2 databases, EnterpriseGL and GR8. I get all database names using a loop, and after that, I get database names one by one, put a script with a name, and execute the script.
        [NAME] NVARCHAR(255) NULL, 
        --unomment which database use want to apply 
       --SELECT NAME FROM master.dbo.sysdatabases WHERE name like '%EnterpriseGL%'  -- get all GL databases 
        --SELECT NAME FROM master.dbo.sysdatabases WHERE name like '%GR8%' --get all GR8 databases 
           DECLARE @Flag INT = 1 
        DECLARE @ABC NVARCHAR(50), @query NVARCHAR(max) 
        SET @query = 'USE '+ @ABC +' select top 1 * from SystemConfiguration' 
     EXECUTE( @query ) 
     SET @Flag = @Flag + 1 
  ROLLBACK TRAN SQL Server 2016 Hosting 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 - :: SQL 'Is Null' Statement Explained

clock April 8, 2020 07:41 by author Peter

The SQL 'Is Null' statement returns the specified value if the expression is NULL, otherwise, it returns the expression. If the expression is NOT NULL, then this function returns the expression.

    SELECT ISNULL(NULL, 'Csharpcorner');   

This replaces Null with the specified replacement value. 
A null statement doesn't specify that the Boolean result is negated. The predicate reverses its return values, returning True if the value is not Null, and False if the value is a Null statement.

    ISNULL ( check_expression , replacement_value ) 

This is the expression returned if the check_expression is NULL. The replacement_value must be of a type that is implicitly convertible to the type of check_expression.
Using IsNull with Avg in SQL statement
The following example finds the average of the OrderDetails.  It substitutes the value 8 for all NULL entries in the orderId column of theOrderDetails table.
    USE sample ;     
    SELECT AVG(ISNULL(OrderId, 8))     
    FROM OrderDetails ;     


The following example selects the description, discount percentage, minimum quantity, and maximum quantity for all special offers in the sample. If the maximum quantity for a particular special offer is NULL, the MaxQty shown in the result set is 0.00. 
    USE sample ;     
    SELECT OrderId , OrderName, Orderaddress , ISNULL(OrderId, 0.00) AS 'Max Quantity'     
    FROM OrderDetails;     

Testing for NULL in a Where clause
Do not use ISNULL to find NULL values; use IS NULL instead. The following example finds all OrderDetails that have NULL in the ordername, orderAddress, OrderDate  column. Note the space between IS and NULL.
    -- Uses sample     
    SELECT OrderName, orderAddress, OrderDate     
    FROM  OrderDetails     
    WHERE OrderId  IS NULL;  

SQL Server 2016 Hosting - :: Cursors In SQL Server

clock April 1, 2020 10:28 by author Peter

A SQL cursor is a database object that is used to retrieve data from a result set one row at a time. A SQL cursor is used when the data needs to be updated row by row. This article explains everything about SQL cursors. In this article, we will learn the following:

  •     Introduction to SQL cursor
  •     Cursor life cycle
  •     Why and when use a cursor
  •     How to implement cursors
  •     What are the limitation of SQL cursor
  •     How can we replace a SQL Cursor

SQL Cursor Life Cycle
The following steps are involced in a SQL cursor life cycle.

    Declaring Cursor
    A cursor is declared by defining the SQL statement.

    Opening Cursor
    A cursor is opened for storing data retrieved from the result set.

    Fetching Cursor
    When a cursor is opened, rows can be fetched from the cursor one by one or in a block to do data manipulation.

    Closing Cursor
    The cursor should be closed explicitly after data manipulation.

    Deallocating Cursor
    Cursors should be deallocated to delete cursor definition and release all the system resources associated with the cursor.

Why use a SQL Cursor?
In relational databases, operations are made on a set of rows. For example, a SELECT statement returns a set of rows which is called a result set. Sometimes the application logic needs to work with one row at a time rather than the entire result set at once. This can be done using cursors.

In programming, we use a loop like FOR or WHILE to iterate through one item at a time, the cursor follows the same approach and might be preferred because it follows the same logic.
SQL Cursor Syntax
    DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ]  
    [ TYPE_WARNING ] FOR select_statement 
     [ FOR UPDATE [ OF column_name [ ,...n ] ] ] [;] 

Cursor Example

The following cursor is defined for retrieving employee_id and  employee_name from Employee table.The FETCH_STATUS value is 0 until there are rows.when all rows are fetched then  FETCH_STATUS becomes 1.
    use Product_Database 
    DECLARE @emp_id int ,@emp_name varchar(20),   
        @message varchar(max);   
    PRINT '-------- EMPLOYEE DETAILS --------';   
    DECLARE emp_cursor CURSOR FOR    
    SELECT emp_id,emp_name   
    FROM Employee 
    order by emp_id;   
    OPEN emp_cursor   
    FETCH NEXT FROM emp_cursor    
    INTO @emp_id,@emp_name   
    print 'Employee_ID  Employee_Name'      
        print '   ' + CAST(@emp_id as varchar(10)) +'           '+ 
            cast(@emp_name as varchar(20)) 
        FETCH NEXT FROM emp_cursor    
    INTO @emp_id,@emp_name   
    CLOSE emp_cursor;   
    DEALLOCATE emp_cursor;   

The Output of the above program will be as follows

SQL Server

What are the limitations of a SQL Cursor

A cursor is a memory resident set of pointers -- meaning it occupies memory from your system that may be available for other processes.

Cursors can be faster than a while loop but they do have more overhead.

Another factor affecting cursor speed is the number of rows and columns brought into the cursor. Time how long it takes to open your cursor and fetch statements.

Too many columns being dragged around in memory, which are never referenced in the subsequent cursor operations, can slow things down.

The cursors are slower because they update tables row by row.
How can we replace SQL Cursors
There's one replacement for cursors in SQL server joins.

Suppose we have to retrieve data from two tables simultaneously by comparing primary keys and foreign keys. In these types of problems, the cursor gives very poor performance as it processes through each and every column. On the other hand using joins in those conditions is feasible because it processes only those columns which meet the condition. So here joins are faster than cursors.

The following example explains the replacement of cursors through joins.

Suppose, we have two tables, ProductTable and Brand Table. The primary key of BrandTable is brand_id which is stored in ProductTable as foreign key brand_id. Now suppose, I have to retrieve brand_name from BrandTable using foreign key brand_id from ProductTable. In these situations cursor programs will be as follows,
    use Product_Database 
    DECLARE @brand_id int    
    DECLARE @brand_name varchar(20)  
    PRINT '--------Brand Details --------';   
    DECLARE brand_cursor CURSOR FOR    
    SELECT distinct(brand_id) 
    FROM ProductTable;  
    OPEN brand_cursor   
    FETCH NEXT FROM brand_cursor    
    INTO @brand_id   
        select brand_id,brand_name from BrandTable where [email protected]_id 
    --(@brand_id is of ProductTable) 
        FETCH NEXT FROM brand_cursor    
    INTO @brand_id  
    CLOSE brand_cursor;   
    DEALLOCATE brand_cursor;   

The Output of the above program will be as follows

SQL Server

The same program can be done using joins as follows,
Select distinct b.brand_id,b.brand_name from BrandTable b inner join
ProductTable p on b.brand_id=p.brand_id

The Output of the above program will be as follows

SQL Server

As we can see from the above example, using joins reduces the lines of code and gives faster performance in case huge records need to be processed.

SQL Server 2016 Hosting - :: SQL UNIQUE Constraint

clock March 18, 2020 12:55 by author Peter

The Unique constraint statement ensures that all values in a column are different. Both the Unique and Primary Key constraints provide a guarantee for uniqueness for a column or set of columns. A Primary key constraint automatically has a unique constraint in SQL. However, you can have many unique constraints per table, but only one primary key constraint per table.

We can create a unique constraint in SQL Server 2019 (15.x) by using SQL server management studio or SQL to ensure no duplicate values are entered in specific columns that do not participate in a primary key. Creating a unique constraint automatically creates a corresponding unique index in SQL.  
SQL Server Unique constraints allow you to ensure that the data stored in a column, or a group of columns, is unique among the rows in a table. 
    CREATE TABLE EmployeeName  (       
     EmpID int NOT NULL UNIQUE,       
      EmpName varchar(255) NOT NULL,        

The above query creates a table with the name "EmployeeName"  and column name EmpID which is both Not Null and Unique(i.e we cannot have empty or duplicate data) and EmpName
Using Unique constraint on create table statement
    CREATE TABLE Employee  (     
     EmpID int NOT NULL UNIQUE,     
      EmpName varchar(255) NOT NULL,     
      EmpFirstName varchar(255),     
      EmpLastname varchar(255),     
      EmpAge int     

The above query created a table with the name "Employee" and the first column name EmpId is Not NULL and UNIQUE, other column name EmpName,EmpFirstName,EmpLastname, EmpAge
Using Unique constraint on alter table
    ALTER TABLE Employee      
    ADD UNIQUE (EmpID);    

 The above query with add a column EmpID and make it UNIQUE.
"Unique" is used to signify a Unique constraint, and also to define a unique name a Unique constraint,on multiple columns.
    ALTER TABLE Employee      
    ADD CONSTRAINT UC_Employee UNIQUE (EmpID,EmpLastName);    

The above query will add EmpID and EmpLastName columns into the UC_Employee table, with the Unique Constraint
Using Drop a Unique constraint statement
Use the following example to drop a Unique constraint:
    ALTER TABLE Employee      
    DROP CONSTRAINT UC_Employee;    

The above query will remove the "Unique" Constrain from the Employee table.
Using SQL Server Management Studio in Unique Constraint
To create a unique constraint statement:
    In Object Explorer, right-click the table to which you want to add a unique constraint, and click Design.
    On the Table Designer menu, click Indexes/Keys.
    In the Indexes/Keys dialog box, click Add.
    In the grid under General, click Type and choose Unique Key from the drop-down list box to the right of the property.
    On the File menu, click Save table name.

Using unique constraint in SQL
To create a unique constraint,

    In Object Explorer, connect to an instance of Database Engine.
    On the Standard bar, click New Query.
    Copy and paste the following example into the query window and click Execute. This example creates the table SampleDetails and creates a unique constraint on the column TransactionID.

    USE sample ;       
    CREATE TABLE SampleDetails       
       TransactionID int NOT NULL,        
       CONSTRAINT AK_TransactionID UNIQUE(TransactionID)        

The above query will create a table SampleDetails in the sample database, with TransactionID and the AK_TransactionID constraint which makes TransactionID unique
To create a unique constraint on an existing table
    In Object Explorer, connect to an instance of Database Engine.
    On the Standard bar, click New Query.
    Copy and paste the following example into the query window and click Execute. The example creates a unique constraint on the columns PasswordHash and PasswordSalt in the table Person.Password. 

    USE sample         
    ALTER TABLE Person.Password        
    ADD CONSTRAINT AK_Password UNIQUE (PasswordHash, PasswordSalt);        

The above query appends the table Person.Password in the sample database , with the AK_Password CONSTRAINT which makes PasswordHash amd PasswordSalt unique.
To create a unique constraint in a new table
    In Object Explorer, connect to an instance of Database Engine.
    On the Standard bar, click New Query.
    Copy and paste the following example into the query window and click Execute. The example creates a table and defines a unique constraint on the column TransactionID.

    USE sample;       
    CREATE TABLE Production.TransactionHistoryArchive2       
       TransactionID int NOT NULL,       
       CONSTRAINT AK_TransactionID UNIQUE(TransactionID)       

The above query uses the sample database and creates a table with the name "Production.TransactionHistoryArchive2" and column name TransactionID and CONSTRAINT AK_TransactionID UNIQUE column name is TransactionID. SQL Server 2016 Hosting 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 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