2. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Working with System Tables
â˘System Views are predefined Microsoft created views for extracting SQL Server metadata.
â˘Expand Database => Views => System Views
3. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Information Schema
â˘The first group of System Views belongs to the Information Schema set.
â˘Information Schema is an ANSI specification for obtaining metadata.
CREATE TABLE MyTable
(
Col1 int,
Col2 varchar(10),
Col3 datetime
)
GO
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'MyTable' ;
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'MyTable'
4. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Catalog Views
â˘New in SQL 2005 are Catalog Views. Microsoft recommends them as the most general interface to the catalog metadata.
SELECT *
FROM sys.tables
SELECT *
FROM sys.columns INNER JOIN sys.tables ON
sys.tables.object_id = sys.columns.object_id
WHERE sys.tables.name = 'MyTable'
5. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Dynamic Management Views
â˘The last groups of views are called Dynamic Management views, or DM.
â˘They are used to gather statistics stored in memory but not persistent on disk such as thread information, memory usage, and connection details.
6. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
SQL Server Schema
â˘Schemas are used to logically group tables, procs, views together, all employee related objects in the employee schema etc.independent entity- a container of objects distinct from the user who created those objects.
â˘Previously (2000), the terms âuserâ and âdatabase object ownerâ meant one and the same thing, but now the two are separate.
CREATE SCHEMA MySchema
7. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Object Name Resolution
â˘Users can have a default schema assigned
â˘Users with no defined default schema will have dbo as their default schema
â˘If the schema name is omitted, rules apply to how the name will be resolved by the following sequence :
â˘First search is in the user's default schema
â˘If not found, the dbo schema will be searched also
⢠Every schema has an owner (user) As long as a user own some schema he cannot be deleted.
8. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Temporary Tables
â˘Session Temporary Tables
â˘Session temporary tables are only visible to their creators in the same session and same scope or sub-scope
â˘Created with a # prefix
â˘Dropped when the user disconnects or when out of scope
â˘Global Temporary Tables
â˘Global temporary tables are visible to all users
â˘Created with a ## prefix
â˘Deleted when all users referencing the table disconnect
9. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Temporary Tables
-- Create sample table and populate it with values
CREATE TABLE #temp_tbl
( Number int PRIMARY KEY,
Name varchar(25));
INSERT INTO #temp_tbl
VALUES (1, 'Ram')
INSERT INTO #temp_tbl
VALUES (2, 'Kedem')
-- Query the table
SELECT * FROM #temp_tbl;
GO
-- Disconnect and reconnect, then try to re execute query
SELECT * FROM #temp_tbl;
GO
11. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Working with IDENTITY
â˘Property of a column
â˘Specify a seed and an increment (Default seed and increment are both 1)
CREATE TABLE employees
(employeeID int identity(1,1) PRIMARY KEY,
lastName varchar(25),
hireDate date default getdate(),
salary decimal(8,2) default 15000)
-- Populate the table with 2 rows
INSERT INTO employees
VALUES ('David' , default, default)
-- Check the identity values added
SELECT * FROM employees;
-- Try to insert a specific value for employeeID. This will fail
INSERT INTO employees
VALUES (1, 'Tamar' , '1995-07-20' , default)
12. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
SET IDENTITY_INSERT ON
â˘Having the IDENTITY property on a column does not in itself ensure that the column is unique.
â˘SET IDENTITY_INSERT ON can be used to allow the user to insert values into the column with the IDENTITY property instead of having it autogenerated.
DROP TABLE emps ;
GO
CREATE TABLE emps
(emp_id int IDENTITY(1,1) ,
emp_name varchar(25))
GO
INSERT INTO emps
VALUES ('Yossi' )
13. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
SET IDENTITY_INSERT ON
â˘SET IDENTITY_INSERT emps ON
â˘INSERT INTO emps (emp_id , emp_name)
â˘VALUES (1,'Moshe' )
â˘-- Error : An explicit value for the identity -- column in table possible only when
â˘-- Specified when a column list is used
â˘-- and IDENTITY_INSERT is ON.
â˘INSERT INTO emps
â˘VALUES (2,'Avi' )
â˘SET IDENTITY_INSERT emps OFF
â˘
â˘INSERT INTO emps (emp_id , emp_name)
â˘VALUES (2,'Tomer' )
â˘SELECT * FROM emps ;
14. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Unique Identifiers
â˘NEWID() randomly generates a guaranteed unique value based on the identification number of the server's network card plus a unique number from the CPU clock
â˘Each process involved can create its own values and know that they will not clash with the values created by another process.
â˘The major advantage of using GUIDs is that they are unique across all space and time.
â˘This comes in handy if you're consolidating records from multiple SQL Servers into one table, as in a data warehousing situation.
â˘GUIDs are also used heavily by SQL Server replication to keep track of rows when they're spread out among multiple SQL Servers.
15. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Unique Identifiers
â˘The main disadvantage to using GUIDs as key values is that they are BIG. At 16 bytes a pop, they are one of the largest datatypes in SQL Server.
â˘Indexes built on GUIDs are going to be larger and slower than indexes built on IDENTITY columns, which are usually ints (4 bytes).
16. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Unique Identifiers
DROP TABLE uniqueid_tab
CREATE TABLE uniqueid_tab
(product_id UNIQUEIDENTIFIER ,
product_name varchar(25))
INSERT INTO uniqueid_tab
VALUES ( NEWID() , 'Windows-7')
INSERT INTO uniqueid_tab
VALUES ( NEWID() , 'Windows-XP')
INSERT INTO uniqueid_tab
VALUES ( NEWID() , 'Windows Server 2003')
SELECT * FROM uniqueid_tab ;
17. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Unique Identifiers
â˘NEWID() randomly generates a guaranteed unique value based on the identification number of the server's network card plus a unique number from the CPU clock
â˘Each process involved can create its own values and know that they will not clash with the values created by another process.
â˘The major advantage of using GUIDs is that they are unique across all space and time.
â˘This comes in handy if you're consolidating records from multiple SQL Servers into one table, as in a data warehousing situation. GUIDs are also used heavily by SQL Server replication to keep track of rows when they're spread out among multiple SQL Servers.
â˘The main disadvantage to using GUIDs as key values is that they are BIG. At 16 bytes a pop, they are one of the largest datatypes in SQL Server.
â˘Indexes built on GUIDs are going to be larger and slower than indexes built on IDENTITY columns, which are usually ints (4 bytes).
â˘=, <>, <, >, <=, >= are supported along with NULL and NOT NULL checking
â˘IDENTITY cannot be used
â˘New values from NEWID() function
18. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Sequences
CREATE SEQUENCE dbo.BookingID AS INT
START WITH 1000
INCREMENT BY 1;
GO
/*
CREATE SEQUENCE [schema_name . ] sequence_name
[ AS [ built_in_integer_type | user-defined_integer_type ] ]
[ START WITH <constant> ]
[ INCREMENT BY <constant> ]
[ { MINVALUE [ <constant> ] } | { NO MINVALUE } ]
[ { MAXVALUE [ <constant> ] } | { NO MAXVALUE } ]
[ CYCLE | { NO CYCLE } ]
[ { CACHE [ <constant> ] } | { NO CACHE } ]
[ ; ]
*/
19. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Sequences
CREATE TABLE usa_booking
(booking_id int
CONSTRAINT usa_booking_id DEFAULT (NEXT VALUE FOR dbo.BookingID),
booking_description varchar(25))
CREATE TABLE europe_booking
(booking_id int
CONSTRAINT europe_booking_id DEFAULT (NEXT VALUE FOR dbo.BookingID),
booking_description varchar(25))
CREATE TABLE china_booking
(book_id int
CONSTRAINT china_booking_id DEFAULT (NEXT VALUE FOR dbo.BookingID),
booking_description varchar(25))
20. Copyright 2014 Š Ram Kedem. All rights reserved. Not to be reproduced without written consent
Sequences
INSERT INTO usa_booking (booking_description)
VALUES ('Booking 1')
INSERT INTO europe_booking (booking_description)
VALUES ('Booking 2')
INSERT INTO china_booking (booking_description)
VALUES ('Booking 3')
SELECT * , 'USA' as 'BookingLocation'FROM usa_booking
UNION ALL
SELECT * , 'Europe' as 'BookingLocation'FROM europe_booking
UNION ALL
SELECT * , 'China' as 'BookingLocation'FROM china_booking