What is GUID in sql server?


  • The GUID stands for a global unique identifier.
  • It is a binary data type (16 bit).
  • To create the GUID in SQL server we will use the NEWID () function.
  • The advantage of a GUID is that unique across servers, tables, databases also.

Just follow the below tables to understand.



Create Database infosysdb
Go

Use infosysdb
Go

Create Table Infosysemployees
(
     ID int primary key identity,
     Name nvarchar(100)
)
Go

Insert Into Infosysemployees Values ('sai')
Insert Into Infosysemployees Values ('kalyan')

In the above table, we have used identity to generate the automatic id values. If you perform the below query you will get the result as follows.

Select * From infosysdb.dbo.Infosysemployees


Now we have create anothe table with different database.

Use wipro
Go

Create Table wiproemployees
(
     ID int primary key identity,
     Name nvarchar(100)
)
Go

Insert Into wiproemployees Values ('vijendhar')
Insert Into wiproemployees Values ('sundeep')

In the above table, we have used identity to generate the automatic id values. If you perform the below query you will get the result as follows.

Select * From wipro.dbo.wiproemployees




Now within the Wipro database, we gonna create another table called employees and we have inserted values in employees tables by using above created two tables as follows.

Create Database wipro
Go

create table employees
(
id int primary key, name varchar(100)
)

insert into employees
Select * From wipro.dbo.wiproemployees
union all
Select * From infosysdb.dbo.Infosysemployees


If you execute the above query you will get an error as follows.

Msg 1801, Level 16, State 3, Line 1
Database 'wipro' already exists. Choose a different database name.
Msg 2627, Level 14, State 1, Line 7
Violation of PRIMARY KEY constraint 'PK__employee__3213E83FA68E7852'. Cannot insert duplicate key in object 'dbo.employees'. The duplicate key value is (1).
The statement has been terminated.


The reason for above error is that if you execute the tables with union all it allows duplicate values, but not between the tables and databases and servers.



                                          GUID IN SQL SERVER PART -2



No comments:

Post a Comment

What is Normalization?

Database normalization is a data design and organization process applied to data structures based on rules that help building relational dat...