Sunday, March 22, 2015

Insert Multiple record with different data using ABS,CheckSum,NEWID SQL

we always need  tricky solutions in sql server to make our business more easier
in this tutorial we will use SQL server 2012

first we will explain meaning of of some words may be functions,we will use

A-  we have Created database called "AnasTest" which contains table with name "employees" and another table "EmployeeType"

"EmployeeType" table contains four records



Employees Table Columns
   .EmployeeId
   .EmployeeName
   .Email
   .EmployeeGuid
   .EmployeeTypeID
   .Phone


  1. if we need to insert 5000 record for testing and need each employee guid is different and randomly set employee type to one of the predefined in "EmployeeType" table 



simply we need to know use of some functions 

  • NEWID() this function generated guid will not be duplicated ever because it uses machine mac address and apply some equations on it so don't worry it will be unique  

             example: select NEWID()

         

  • CHECKSUM('') functions is to build a hash index based on an expression or a column list                    example select CHECKSUM('12') you will get result of 2262
  • ABS () function is used to get the positive value of number                                                              example select abs(-120) you will get 120

2- now we need yo insert employees with employee type (1,2,3,4) and with unique guid

   WE USED combination of function abs(CHECKSUM(NEWID())%4)+1
to getting  random guid and hashing it's  number will generate number from -2 billion to +2 billion .
and use % operator "Modulus - Divides left hand operand by right hand operand and returns remainder" and got positive reminders but we don't need 0 so we added 1 and

now if we select from "employee" table we  will got 5000 record with different data

Enjoy
Anas Saad
Senior Software Engineer