SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Designing Tables 
Ram Kedem
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
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'
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'
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.
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
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.
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
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
Data Integrity
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)
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' )
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 ;
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.
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).
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 ;
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
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 } ] 
[ ; ] 
*/
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))
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

Weitere ähnliche Inhalte

Was ist angesagt?

Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)
Achmad Solichin
 
MDI Training DB2 Course
MDI Training DB2 CourseMDI Training DB2 Course
MDI Training DB2 Course
Marcus Davage
 

Was ist angesagt? (20)

My Sql concepts
My Sql conceptsMy Sql concepts
My Sql concepts
 
Sql views
Sql viewsSql views
Sql views
 
Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle Sql
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)
 
Les10
Les10Les10
Les10
 
Les08
Les08Les08
Les08
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
Oracle Database View
Oracle Database ViewOracle Database View
Oracle Database View
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
Data Modeling with Cassandra
Data Modeling with CassandraData Modeling with Cassandra
Data Modeling with Cassandra
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)
 
Cassandra Data Modeling
Cassandra Data ModelingCassandra Data Modeling
Cassandra Data Modeling
 
Les09
Les09Les09
Les09
 
MySQL partitions tutorial
MySQL partitions tutorialMySQL partitions tutorial
MySQL partitions tutorial
 
Creating other schema objects
Creating other schema objectsCreating other schema objects
Creating other schema objects
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Sql
SqlSql
Sql
 
MDI Training DB2 Course
MDI Training DB2 CourseMDI Training DB2 Course
MDI Training DB2 Course
 
Custom Star Creation for Ellucain's Enterprise Data Warehouse
Custom Star Creation for Ellucain's Enterprise Data WarehouseCustom Star Creation for Ellucain's Enterprise Data Warehouse
Custom Star Creation for Ellucain's Enterprise Data Warehouse
 

Andere mochten auch (7)

Module 3 design and implementing tables
Module 3 design and implementing tablesModule 3 design and implementing tables
Module 3 design and implementing tables
 
Operating Systems & Applications
Operating Systems & ApplicationsOperating Systems & Applications
Operating Systems & Applications
 
MS PowerPoint for Begninners
MS PowerPoint for BegninnersMS PowerPoint for Begninners
MS PowerPoint for Begninners
 
How to create MS PowerPoint
How to create MS PowerPointHow to create MS PowerPoint
How to create MS PowerPoint
 
MS powerpoint 2007 complete
MS powerpoint 2007 completeMS powerpoint 2007 complete
MS powerpoint 2007 complete
 
Operating Systems 1: Introduction
Operating Systems 1: IntroductionOperating Systems 1: Introduction
Operating Systems 1: Introduction
 
Ms word 2010 by sachin sharma
Ms word 2010 by sachin sharmaMs word 2010 by sachin sharma
Ms word 2010 by sachin sharma
 

Ähnlich wie 2 designing tables

plsql Les09
 plsql Les09 plsql Les09
plsql Les09
sasa_eldoby
 
ETL With Cassandra Streaming Bulk Loading
ETL With Cassandra Streaming Bulk LoadingETL With Cassandra Streaming Bulk Loading
ETL With Cassandra Streaming Bulk Loading
alex_araujo
 
Lesson09
Lesson09Lesson09
Lesson09
renguzi
 

Ähnlich wie 2 designing tables (20)

Dbms oracle
Dbms oracle Dbms oracle
Dbms oracle
 
plsql Les09
 plsql Les09 plsql Les09
plsql Les09
 
Introduction to data modeling with apache cassandra
Introduction to data modeling with apache cassandraIntroduction to data modeling with apache cassandra
Introduction to data modeling with apache cassandra
 
Cassandra Day Chicago 2015: Apache Cassandra Data Modeling 101
Cassandra Day Chicago 2015: Apache Cassandra Data Modeling 101Cassandra Day Chicago 2015: Apache Cassandra Data Modeling 101
Cassandra Day Chicago 2015: Apache Cassandra Data Modeling 101
 
Cassandra Day London 2015: Data Modeling 101
Cassandra Day London 2015: Data Modeling 101Cassandra Day London 2015: Data Modeling 101
Cassandra Day London 2015: Data Modeling 101
 
Cassandra Day Atlanta 2015: Data Modeling 101
Cassandra Day Atlanta 2015: Data Modeling 101Cassandra Day Atlanta 2015: Data Modeling 101
Cassandra Day Atlanta 2015: Data Modeling 101
 
Don't Do This [FOSDEM 2023]
Don't Do This [FOSDEM 2023]Don't Do This [FOSDEM 2023]
Don't Do This [FOSDEM 2023]
 
Data Warehouse Design Considerations
Data Warehouse Design ConsiderationsData Warehouse Design Considerations
Data Warehouse Design Considerations
 
Constraints constraints of oracle data base management systems
Constraints  constraints of oracle data base management systemsConstraints  constraints of oracle data base management systems
Constraints constraints of oracle data base management systems
 
plsql les06
 plsql les06 plsql les06
plsql les06
 
IR SQLite Session #1
IR SQLite Session #1IR SQLite Session #1
IR SQLite Session #1
 
SQL LECTURE.pptx
SQL LECTURE.pptxSQL LECTURE.pptx
SQL LECTURE.pptx
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
ETL With Cassandra Streaming Bulk Loading
ETL With Cassandra Streaming Bulk LoadingETL With Cassandra Streaming Bulk Loading
ETL With Cassandra Streaming Bulk Loading
 
Lesson09
Lesson09Lesson09
Lesson09
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
Introduction to mysql part 3
Introduction to mysql part 3Introduction to mysql part 3
Introduction to mysql part 3
 
Sql analytic queries tips
Sql analytic queries tipsSql analytic queries tips
Sql analytic queries tips
 
Unit 4
Unit 4Unit 4
Unit 4
 

Mehr von Ram Kedem

Mehr von Ram Kedem (20)

Impala use case @ edge
Impala use case @ edgeImpala use case @ edge
Impala use case @ edge
 
Advanced SQL Webinar
Advanced SQL WebinarAdvanced SQL Webinar
Advanced SQL Webinar
 
Managing oracle Database Instance
Managing oracle Database InstanceManaging oracle Database Instance
Managing oracle Database Instance
 
Power Pivot and Power View
Power Pivot and Power ViewPower Pivot and Power View
Power Pivot and Power View
 
Data Mining in SSAS
Data Mining in SSASData Mining in SSAS
Data Mining in SSAS
 
Data mining In SSAS
Data mining In SSASData mining In SSAS
Data mining In SSAS
 
SQL Injections - Oracle
SQL Injections - OracleSQL Injections - Oracle
SQL Injections - Oracle
 
SSAS Attributes
SSAS AttributesSSAS Attributes
SSAS Attributes
 
SSRS Matrix
SSRS MatrixSSRS Matrix
SSRS Matrix
 
DDL Practice (Hebrew)
DDL Practice (Hebrew)DDL Practice (Hebrew)
DDL Practice (Hebrew)
 
DML Practice (Hebrew)
DML Practice (Hebrew)DML Practice (Hebrew)
DML Practice (Hebrew)
 
Exploring Oracle Database Architecture (Hebrew)
Exploring Oracle Database Architecture (Hebrew)Exploring Oracle Database Architecture (Hebrew)
Exploring Oracle Database Architecture (Hebrew)
 
Introduction to Databases
Introduction to DatabasesIntroduction to Databases
Introduction to Databases
 
Deploy SSRS Project - SQL Server 2014
Deploy SSRS Project - SQL Server 2014Deploy SSRS Project - SQL Server 2014
Deploy SSRS Project - SQL Server 2014
 
Pig - Processing XML data
Pig - Processing XML dataPig - Processing XML data
Pig - Processing XML data
 
SSAS Cubes & Hierarchies
SSAS Cubes & HierarchiesSSAS Cubes & Hierarchies
SSAS Cubes & Hierarchies
 
SSRS Basic Parameters
SSRS Basic ParametersSSRS Basic Parameters
SSRS Basic Parameters
 
SSRS Gauges
SSRS GaugesSSRS Gauges
SSRS Gauges
 
SSRS Conditional Formatting
SSRS Conditional FormattingSSRS Conditional Formatting
SSRS Conditional Formatting
 
SSRS Calculated Fields
SSRS Calculated FieldsSSRS Calculated Fields
SSRS Calculated Fields
 

KĂźrzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

KĂźrzlich hochgeladen (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

2 designing tables

  • 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