Sunday, 18 March 2018

SQL Training - 07



Create function

CREATE FUNCTION GetAge
(
-- Add the parameters for the function here
@DoB as datetime
)
RETURNS int
AS
begin

declare @Age int
select @Age = DATEDIFF(day, @DoB, getdate())
Return @Age
end

to use the function do as the following
select [dbo].[GetAge](convert(date,'19870516'))


Create Stored Procedure

why to use?

  • Compiled 
  • parsed 
  • Security (You don't see the table)

CREATE PROCEDURE getPersonData
-- Add the parameters for the stored procedure here
@id as int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

    -- Insert statements for procedure here
select * from Person
where id=@id
END
GO

[dbo].[getPersonData] 360
or exec [dbo].[getPersonData] 360 



Create delete trigger 

CREATE TRIGGER logDeleteTransact
   ON [dbo].[Person]
  for delete
AS 
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

    -- Insert statements for trigger here
insert into deleted_person(ID, fName, LName)
select deleted.ID, deleted.fName, deleted.LName from deleted
END
GO




SQL Training - 06










create Partition Function fnDOB(DateTime)
AS Range LEFT 
for values ('20091231','20101231','20111231','20121231')



create partition scheme schDOB as partition fnDOB
to(D_LT2010, D_2010, D_2011, D_2012, D_GT2012)









If you use partitioning in your DB, we recommend to use field not change periodically 




Fetch

select * from Person
order by Id
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY

Row Number

SELECT top 10 *
FROM    (
        SELECT  *, ROW_NUMBER() OVER (ORDER BY id) AS rn
        FROM    Person
        ) p
WHERE   rn > 0
ORDER BY  id

Create table from select

Select * into new_table  from  old_table 

Logging Delete records in another table

delete from Person_Old 
output deleted.id, deleted.FName, deleted.LName
Into deleted_person(ID, fName, LName)
where ID=350


DateDiff the date different 
select  DATEDIFF(day,'19870516',getdate())/365.24 as age


End of month 
select  EOMONTH(getdate())

Check if date or not(1,0)

select  isdate(getdate())


Concatenate and Convert

select top 10 'Name: '+ fname +'  '+lname +', DOB= '+convert(nvarchar, dob) + '  Gender: '+
case
when Gender=1
then 'Male'
when Gender=0
then 'Female'
end
as userDesc
from Person



Sunday, 11 March 2018

Sum Data in Tables

SELECT
    t.NAME AS TableName,
    i.name as indexName,
    sum(p.rows) as RowCounts,
    sum(a.total_pages) as TotalPages,
    sum(a.used_pages) as UsedPages,
    sum(a.data_pages) as DataPages,
    (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB,
    (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB,
    (sum(a.data_pages) * 8) / 1024 as DataSpaceMB
FROM
    sys.tables t
INNER JOIN     
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE
    t.NAME NOT LIKE 'dt%' AND
    i.OBJECT_ID > 255 AND 
    i.index_id <= 1
GROUP BY
    t.NAME, i.object_id, i.index_id, i.name
ORDER BY
    DataSpaceMB desc

SQL Training - 05

Clustered and Non-Clustered Indexes:

  • Each table can have one Clustered Index and many columns in this clustered Index.
  • Each page can have 8.1KB
  • When you add more than one column in the clustered the pages will increase and the access time will increase.
  • Recommended to Add a clustered indexes on each table.
  • You can remove the primary key from the clustered index and add any other columns.
  • Each primary key is a clustered index and a clustered could contains non-primary key.
  • Each table doesn't have a clustered index called heap.
  • Phone book is clustered; the pages already contains the data.
  • Non-clustered index is pointer; like book Index.

Sunday, 4 March 2018

SQL Training - 04



  • after 255 hit at the same time it will be put in the queue
  • Data loss in simple backup is very high
  • Unique key may allow null
  • De-normalization: using joining 
  • Don't delete cascade
  • Cluster Indexing: Like Phone book (restructuring pages)
  • Non Clustered Indexing: Like Book Index (فهرس الكتاب)(no restructuring for the pages just create index for the newly pages or edited pages)

--select [name], recovery_model_desc from sys.databases;

--alter database one set recovery simple;

--backup log one to disk = N'c:\tmp\one.trn';
--backup database one to disk = N'c:\temp\one.bak';
--alter database one set recovery full;
backup log one to disk = N'c:\temp\one.trn'; --you cannot make backup for log file before creating full backup
backup database one to disk  = N'c:\temp\one.bak';


Case Study: Fleet Management Systems
  • Main Entities
    • Car (Detailed Data on each vehicle)
    • Make(This is a description of all vehicle)
    • Shape(This contains the possible shapes)
    • Vendor(These are approved vendors which can be used to supply parts)
    • Maintenance (his data contains description of all the maintenance operations performed  )
    • Parts(This table represents parts that have been take out of inventory)

Sunday, 25 February 2018

SQL Training - 03

Identity Field:

  • Indexed 
  • No duplicate 
  • Auto Increment 
  • sorted
  • Indexed 

Side Effect of Identity Field:
  • Values cannot be changed 
  • Gaps 
Normalization:
  • we need it to prevent redundancy (Place are repeated)
  • To avoid repeated columns (Address, 2 , 3)
  • To avoid repeated rows 
  • Referential integrity (Relations to make full record)
  • Unity: each table must contains all related data
  • Atomic: each cell must be one value 
  • Dependency
  • To prevent orphan rows (customer without address or addresses without customers)
  • No Transitive 
- Use begin transaction and end transaction to execute more-than one sql statement 
- In One to many relations; you add in many table and after that you add in one table.
- In Addresses table; you can add email1, email2, phone1, phone2, telephone1, telephone2, fax1, fax2

SW Engineering:
  • Gathering info
    • Structured 
    • OO
      • Noun: classes
      • Verbs: functions
      • Each property in class is a field in DB
    • Structred
      • Verbs only 
  • UML classes
  • Class contains 
    • Class Members
      • Properties (Name, Age)
      • Methods  (Add, Delete)
      • Events(WhenDeleted, WhenAdded)
PrimMinister, Manager, Employee, Driver, Heads of Units, Drivers, Cleaners are Persons 
so the initial table is Person, 



Sunday, 11 February 2018

SQL Training - 02

SQL Server Features:


  • BI: Business Inelegance; Which means Transforming Data to Knowledge  


to help decision maker to make right decisions



  • DB Engine: Takes care of exciting transact SQL statements,
    •  security(Data is the most Valuable Asset, 
    • by default it encrypt the data and you can encrypt it by key), Audit(Logging every transaction), Roles and Authentications(users)
    • indexing
it contains Transact SQL (T-SQL) programming Interface -- Reaching Data anytime anywhere--  , Handel errors
How? using every techniques to access data 
SQL Server 2012 : T-SQL is a set bases more efficient  (One loop to retrieve data)
T-SQL was before 2012 T-SQL is Cursor base (Slow, not Up-todate, more IO )


  • Replication: Distributing data to different locations using FTP(Push and Pull), Publisher(Master Database) and Subscriber
  • SQL Agent: 
    • Scheduling Tasks and Jobs
    • Rebuilding Index
    • Backups
    • Alert Fail 
  • High Availability (H.A): through 
    • Mirroring(Server 1 and Server 2 and Witness)
    • always on (replications)
    • fail over clustering (stand by)
    • Log shipping: Distributing log files on replicas 
** ADO.Net library it contains everything to access database (Offline and Classified)

During installation set the Default Collation to Arabic_100

to overcome on hamza you have to use Arabic collation 



------------
Backups 3 Models :

  • Simple: no log backups so you can't recover the data at point of time, , 
  • Full Model: no lose of data, you can restore to any point of time
  • Bulk-logged Model: you can restore only to the end of any backup 
SQL Server Browser:
  • List all available servers
  • Connect to any available server 
Datatypes:
  • Use the specific datatype for fields
  • Use specific length for varchar, char
  • The datatype varchar(max) not indexable 
  • varchar reserves the needed space and not the value which you supplied but the char reserves the value you supplied, for example :varchar(100) and you have entered 10 digits, only 10 digits will reserved from the space, char(100) it reserves 100 digits even you didn't added any values 
  • Use date when you don't need the time, use YYYY-MM-DD or DD-MM-YYYY
Why default values are recommended ??
to avoid Nulls, when binding values to web controls the null makes a problem


Table Properties:

  • Name
  • Schema 
  • Constraints
  • File Group 
  • Number of Fields
Field Properties:
  • Name
  • Datatype
  • Idexing
  • Null-able 
Why to use allow null and set default value?
it allows the data-insert to insert null for some reason