SlideShare uma empresa Scribd logo
1 de 4
Baixar para ler offline
Using Object Dependencies in SQL Server 2008 | TechRepublic



   ZDNet Asia    SmartPlanet    TechRepublic                                                                                 Log In   Join TechRepublic   FAQ   Go Pro!




                                                   Blogs      Downloads      Newsletters        Galleries     Q&A     Discussions     News
                                               Research Library


     IT Management             Development         IT Support        Data Center         Networks         Security




     Home / Blogs / The Enterprise Cloud                                                  Follow this blog:

     The Enterprise Cloud


     Using Object Dependencies in
     SQL Server 2008
     By John Sheesley
     October 9, 2008, 10:20 AM PDT

     Takeaway: Tracking object dependencies has always been difficult with SQL Server. SQL
     Server 2008 makes it easier because it tracks dependencies by the object’s name rather than ID.
     Here’s how it works.

      Previous versions of SQL Server were not that great at keeping track of object dependencies.
     The reason for this was due to the fact that all object dependencies were tracked by the ID of the
     object, which meant that the object had to exist first. SQL Server 2008 greatly expands on this
     capability by tracking objects by the name of the object, rather than relying upon the ID.
     Advantages of this approach are that object dependencies remain tracked even after some objects
     have been removed from the database, as well as are tracked even if an object has yet to be
     created.

     New Management Objects
     SQL Server 2008 introduces two new dynamic management functions and a new system view for
     keeping track of object dependencies. These new objects hold information stored by the Database
     Engine for dependencies created when objects are created, altered, or dropped. A dependency is
     created between two objects when one object appears by name inside a SQL expression stored in
     another object. The object that appears inside the expression is known as the referenced entity,
     while the object that houses the SQL expression is known as the referencing entity.

     sys.sql_expression_dependencies
     This view holds one record for each dependency on a user-defined object in the current
     database. These user-defined objects can be objects stored in the current database, objects
     stored in a different database and referenced using a three part naming convention
     (databasename.schemaname.objectname), objects on a different server and referenced via a
     linked server using a four part naming convention
     (servername.databasename.schemaname.objectname), and objects that do not exist at the time
     the object is created (known as deferred objects).

     sys.dm_sql_referenced_entities
     This function returns one row for each user defined object referenced by name in the definition of
     the specified referencing entity. For example, if the view vw_SampleView references Field1,
     Field2, and Field3 of the table Table1, then four rows will be returned; three for the referenced
     fields and one for the table reference.




http://www.techrepublic.com/blog/datacenter/using-object-dependencies-in-sql-server-2008/460[08/29/2012 3:42:43 PM]
Using Object Dependencies in SQL Server 2008 | TechRepublic


     sys.dm_sql_referencing_entities
     This function returns one record for each user defined object in the current database that
     references another user defined object by name. For example, if the view vw_SampleView
     references Table1 and Table2, then two records will be returned by this function; one for each
     table reference.

     An Example
     Let’s look at an example of how dependencies are tracked inside the database by creating some
     objects and querying the new DMVs. Use the script below to create a table named SalesHistory.

     CREATE TABLE [dbo].[SalesHistory](

          [SaleID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,

          [Product] [char](150) NULL,

          [SaleDate] [datetime] NULL,

          [SalePrice] [money] NULL

     )

     In the following script, I create a stored procedure named dbo.usp_GetSales. This procedure
     references the SalesHistory table created in the above script.



     CREATE PROCEDURE dbo.usp_GetSales

     (

     @Product VARCHAR(10)

     )

     AS

     BEGIN

          SELECT COUNT(SaleID) AS SalesCount, SUM(SalePrice) AS SalesAmount

          FROM dbo.SalesHistory sh

     END

     The following script uses the table-valued function sys.dm_sql_referenced_returns function to find
     all objects that reference the SalesHistory table. This query will not only return references to the
     SalesHistory table, but also includes the fields from the SalesHistory table that are referenced.
     Note the use of the CROSS APPLY operator. This is due to the fact that entities is a table-valued
     function and the APPLY operator is required when passing field values to table-valued functions.
     Note that a call to the sys.dm_referenced_entities function will error if it encounters a reference to
     an entity field that does not exist.

     SELECT ReferencedEntityName = o.name, g.referenced_entity_name, referenced_minor_name

     FROM sys.objects o

     JOIN sys.schemas s on o.schema_id = s.schema_id

     CROSS APPLY sys.dm_sql_referenced_entities(s.name + ‘.’ + o.name, ‘OBJECT’) g

     WHERE referenced_entity_name = ‘SalesHistory’

     The following script queries the new dynamic management view sys.dm_sql_referencing_entities
     to find any objects referenced by the procedure usp_GetSales.




http://www.techrepublic.com/blog/datacenter/using-object-dependencies-in-sql-server-2008/460[08/29/2012 3:42:43 PM]
Using Object Dependencies in SQL Server 2008 | TechRepublic


     SELECT

     ReferencingObject = referencing_entity_name,

     ReferencedObject = o.name

     FROM sys.objects o

     JOIN sys.schemas s on o.schema_id = s.schema_id

     CROSS APPLY sys.dm_sql_referencing_entities(s.name + ‘.’ + o.name, ‘OBJECT’) g

     WHERE

          referencing_entity_name = ‘usp_GetSales’

     In the following script, I create a new stored procedure named usp_GetSalesFromArchive, which
     references the nonexistent SalesHistoryArchive table.

     CREATE PROCEDURE usp_GetSalesFromArchive

     (

     @Product VARCHAR(10)

     )

     AS

     BEGIN

     SELECT COUNT(SaleArchiveID) AS SalesCount, SUM(SaleArchivePrice) AS SalesAmount

          FROM dbo.SalesHistoryArchive sh

     END

     I can now use the sys.sql_expression_dependencies system view to find any objects that
     reference the SalesHistoryArchive table.

     Alternatively, I can alter this same query just a bit to find the tables referenced by the
     usp_GetSalesFromArchive stored procedure.



     SELECT ReferencingObject = o.name ,

     ReferencedObject = d.referenced_entity_name

     FROM sys.sql_expression_dependencies d

     join sys.objects o on d.referencing_id = o.object_id

     WHERE o.name = ‘usp_GetSalesFromArchive’

     Conclusion
     There are certainly advantages to tracking dependencies via object name rather than object ID.
     My favorite aspect is the ability to find stored procedures that reference objects that do not exist.
     This is great because it allows me to find any stored procedures that may not longer be used or
     perhaps need to be updated.


     Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free
     newsletters.




http://www.techrepublic.com/blog/datacenter/using-object-dependencies-in-sql-server-2008/460[08/29/2012 3:42:43 PM]
Using Object Dependencies in SQL Server 2008 | TechRepublic


                   VMware and Microsoft go                       iSCSI is the future of storage
                   head to head


      People who read this...
          Using Object Dependencies in SQL Server 2008
          Moving the Tempdb and Master Database in SQL Server
          Moving the Tempdb and Master Database in SQL Server




         3            Join the conversation!                                              Add Your Opinion
      Comments        Follow via:



      Staff Picks      Top Rated      Most Recent       My Contacts                             See All Comments




                       RE: Using Object Dependencies in SQL Server 2008                               0
                       aspemail@... 21st Oct 2008                                                    Votes


             If the Stored Procedure code was "Select * From ..." then these DMFs/DMVs are
             smart enough to resolve that from "Select * .." to "Select Col1, col2, col3,....", which I
             found very interesting. Thought... Read Whole Comment +


                 View in thread




                       RE: Using Object Dependencies in SQL Server 2008                               0
                       aspemail@... 21st Oct 2008                                                    Votes



             If you could have added screen shots of what the result would have looked like, that
             would have been great


                 View in thread




                       Parameter Usage                                                                0
                       aspemail@... 21st Oct 2008                                                    Votes



             You created 2 SP's in this sample code which passes parameter. Not sure if it was
             required.


                 View in thread




                                                    See all comments



     Join the TechRepublic Community and join the conversation! Signing-up is
     free and quick, Do it now, we want to hear your opinion.

      Join         Login




http://www.techrepublic.com/blog/datacenter/using-object-dependencies-in-sql-server-2008/460[08/29/2012 3:42:43 PM]

Mais conteúdo relacionado

Mais procurados

cPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven FeaturescPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven FeaturesDave Stokes
 
Preethi apex-basics-jan19
Preethi apex-basics-jan19Preethi apex-basics-jan19
Preethi apex-basics-jan19Preethi Harris
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
Playing With (B)Sqli
Playing With (B)SqliPlaying With (B)Sqli
Playing With (B)SqliChema Alonso
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentalsMadhuri Kavade
 
Object Relational model for SQLIite in android
Object Relational model for SQLIite  in android Object Relational model for SQLIite  in android
Object Relational model for SQLIite in android yugandhar vadlamudi
 
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptJavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptDave Stokes
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationDave Stokes
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml datakendyhuu
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Salman Memon
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationRandy Connolly
 
PyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialPyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialjbellis
 
Controlling User Access -Data base
Controlling User Access -Data baseControlling User Access -Data base
Controlling User Access -Data baseSalman Memon
 

Mais procurados (20)

cPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven FeaturescPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven Features
 
Preethi apex-basics-jan19
Preethi apex-basics-jan19Preethi apex-basics-jan19
Preethi apex-basics-jan19
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Playing With (B)Sqli
Playing With (B)SqliPlaying With (B)Sqli
Playing With (B)Sqli
 
My sql102
My sql102My sql102
My sql102
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
Object Relational model for SQLIite in android
Object Relational model for SQLIite  in android Object Relational model for SQLIite  in android
Object Relational model for SQLIite in android
 
Schema webinar
Schema webinarSchema webinar
Schema webinar
 
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
 
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptJavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml data
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Oracle Database View
Oracle Database ViewOracle Database View
Oracle Database View
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Schema201 webinar
Schema201 webinarSchema201 webinar
Schema201 webinar
 
PyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialPyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorial
 
Controlling User Access -Data base
Controlling User Access -Data baseControlling User Access -Data base
Controlling User Access -Data base
 

Destaque

Project filem klasik dan moden
Project filem klasik dan modenProject filem klasik dan moden
Project filem klasik dan modenbmsiti10
 
Licencias creative commons
Licencias creative commonsLicencias creative commons
Licencias creative commonsLilianitabel
 
RMIA Master Class-July 06
RMIA Master Class-July 06RMIA Master Class-July 06
RMIA Master Class-July 06Gai Roper
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republicKaing Menglieng
 
Как перестать требовать от клиентов бумаги с государственными печатями
Как перестать требовать от клиентов бумаги с государственными печатямиКак перестать требовать от клиентов бумаги с государственными печатями
Как перестать требовать от клиентов бумаги с государственными печатямиInstitute of development of the Internet
 
Final report eia (kmc)
Final report   eia (kmc)Final report   eia (kmc)
Final report eia (kmc)zubeditufail
 
DERECHO CIVIL DE LAS PERSONAS
DERECHO CIVIL DE LAS PERSONASDERECHO CIVIL DE LAS PERSONAS
DERECHO CIVIL DE LAS PERSONASUNY
 

Destaque (14)

E-урегулирование
E-урегулированиеE-урегулирование
E-урегулирование
 
mdl2
mdl2mdl2
mdl2
 
Web.2.0
Web.2.0Web.2.0
Web.2.0
 
Project filem klasik dan moden
Project filem klasik dan modenProject filem klasik dan moden
Project filem klasik dan moden
 
Licencias creative commons
Licencias creative commonsLicencias creative commons
Licencias creative commons
 
Resume_Sandeep Tanwar
Resume_Sandeep TanwarResume_Sandeep Tanwar
Resume_Sandeep Tanwar
 
RMIA Master Class-July 06
RMIA Master Class-July 06RMIA Master Class-July 06
RMIA Master Class-July 06
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republic
 
Pwr
PwrPwr
Pwr
 
WEB 2.0
WEB 2.0WEB 2.0
WEB 2.0
 
Как перестать требовать от клиентов бумаги с государственными печатями
Как перестать требовать от клиентов бумаги с государственными печатямиКак перестать требовать от клиентов бумаги с государственными печатями
Как перестать требовать от клиентов бумаги с государственными печатями
 
C V L
C V LC V L
C V L
 
Final report eia (kmc)
Final report   eia (kmc)Final report   eia (kmc)
Final report eia (kmc)
 
DERECHO CIVIL DE LAS PERSONAS
DERECHO CIVIL DE LAS PERSONASDERECHO CIVIL DE LAS PERSONAS
DERECHO CIVIL DE LAS PERSONAS
 

Semelhante a Using object dependencies in sql server 2008 tech republic

Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Servicesukdpe
 
Get database properties using power shell in sql server 2008 techrepublic
Get database properties using power shell in sql server 2008   techrepublicGet database properties using power shell in sql server 2008   techrepublic
Get database properties using power shell in sql server 2008 techrepublicKaing Menglieng
 
Sql Injection and Entity Frameworks
Sql Injection and Entity FrameworksSql Injection and Entity Frameworks
Sql Injection and Entity FrameworksRich Helton
 
Using Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case StudyUsing Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case StudyDavid Keener
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?ukdpe
 
android sqlite
android sqliteandroid sqlite
android sqliteDeepa Rani
 
LINQ 2 SQL Presentation To Palmchip And Trg, Technology Resource Group
LINQ 2 SQL Presentation To Palmchip  And Trg, Technology Resource GroupLINQ 2 SQL Presentation To Palmchip  And Trg, Technology Resource Group
LINQ 2 SQL Presentation To Palmchip And Trg, Technology Resource GroupShahzad
 
BI 2008 Simple
BI 2008 SimpleBI 2008 Simple
BI 2008 Simplellangit
 
Tech Days09 Sqldev
Tech Days09 SqldevTech Days09 Sqldev
Tech Days09 Sqldevllangit
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developersllangit
 
SQL Server 2008 for .NET Developers
SQL Server 2008 for .NET DevelopersSQL Server 2008 for .NET Developers
SQL Server 2008 for .NET Developersllangit
 
Deploying data tier applications sql saturday dc
Deploying data tier applications sql saturday dcDeploying data tier applications sql saturday dc
Deploying data tier applications sql saturday dcJoseph D'Antoni
 
Secrets of Enterprise Data Mining 201305
Secrets of Enterprise Data Mining 201305Secrets of Enterprise Data Mining 201305
Secrets of Enterprise Data Mining 201305Mark Tabladillo
 
SQL Server 2008 Highlights
SQL Server 2008 HighlightsSQL Server 2008 Highlights
SQL Server 2008 HighlightsIntergen
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developersukdpe
 

Semelhante a Using object dependencies in sql server 2008 tech republic (20)

Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Services
 
Get database properties using power shell in sql server 2008 techrepublic
Get database properties using power shell in sql server 2008   techrepublicGet database properties using power shell in sql server 2008   techrepublic
Get database properties using power shell in sql server 2008 techrepublic
 
Sql Injection and Entity Frameworks
Sql Injection and Entity FrameworksSql Injection and Entity Frameworks
Sql Injection and Entity Frameworks
 
Using Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case StudyUsing Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case Study
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
android sqlite
android sqliteandroid sqlite
android sqlite
 
Data In Cloud
Data In CloudData In Cloud
Data In Cloud
 
LINQ 2 SQL Presentation To Palmchip And Trg, Technology Resource Group
LINQ 2 SQL Presentation To Palmchip  And Trg, Technology Resource GroupLINQ 2 SQL Presentation To Palmchip  And Trg, Technology Resource Group
LINQ 2 SQL Presentation To Palmchip And Trg, Technology Resource Group
 
BI 2008 Simple
BI 2008 SimpleBI 2008 Simple
BI 2008 Simple
 
Tech Days09 Sqldev
Tech Days09 SqldevTech Days09 Sqldev
Tech Days09 Sqldev
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developers
 
SQL Server 2008 for .NET Developers
SQL Server 2008 for .NET DevelopersSQL Server 2008 for .NET Developers
SQL Server 2008 for .NET Developers
 
Deploying data tier applications sql saturday dc
Deploying data tier applications sql saturday dcDeploying data tier applications sql saturday dc
Deploying data tier applications sql saturday dc
 
Secrets of Enterprise Data Mining 201305
Secrets of Enterprise Data Mining 201305Secrets of Enterprise Data Mining 201305
Secrets of Enterprise Data Mining 201305
 
SQL Server 2008 Highlights
SQL Server 2008 HighlightsSQL Server 2008 Highlights
SQL Server 2008 Highlights
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developers
 
Practical OData
Practical ODataPractical OData
Practical OData
 

Mais de Kaing Menglieng

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republicKaing Menglieng
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republicKaing Menglieng
 
Understand when to use user defined functions in sql server tech-republic
Understand when to use user defined functions in sql server   tech-republicUnderstand when to use user defined functions in sql server   tech-republic
Understand when to use user defined functions in sql server tech-republicKaing Menglieng
 
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server indexed views   speed up your select queries  part 1 - code-projecSql server indexed views   speed up your select queries  part 1 - code-projec
Sql server indexed views speed up your select queries part 1 - code-projecKaing Menglieng
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupKaing Menglieng
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answersKaing Menglieng
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6Kaing Menglieng
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5Kaing Menglieng
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4Kaing Menglieng
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2Kaing Menglieng
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seKaing Menglieng
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsKaing Menglieng
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazineKaing Menglieng
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republicKaing Menglieng
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -Kaing Menglieng
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repuKaing Menglieng
 
New date datatypes in sql server 2008 tech republic
New date datatypes in sql server 2008   tech republicNew date datatypes in sql server 2008   tech republic
New date datatypes in sql server 2008 tech republicKaing Menglieng
 
Introduction to policy based management in sql server 2008 tech-republic
Introduction to policy based management in sql server 2008   tech-republicIntroduction to policy based management in sql server 2008   tech-republic
Introduction to policy based management in sql server 2008 tech-republicKaing Menglieng
 
Introduction to change data capture in sql server 2008 tech republic
Introduction to change data capture in sql server 2008   tech republicIntroduction to change data capture in sql server 2008   tech republic
Introduction to change data capture in sql server 2008 tech republicKaing Menglieng
 

Mais de Kaing Menglieng (20)

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republic
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republic
 
Understand when to use user defined functions in sql server tech-republic
Understand when to use user defined functions in sql server   tech-republicUnderstand when to use user defined functions in sql server   tech-republic
Understand when to use user defined functions in sql server tech-republic
 
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server indexed views   speed up your select queries  part 1 - code-projecSql server indexed views   speed up your select queries  part 1 - code-projec
Sql server indexed views speed up your select queries part 1 - code-projec
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookup
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answers
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql se
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joins
 
Speed up sql
Speed up sqlSpeed up sql
Speed up sql
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazine
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republic
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repu
 
New date datatypes in sql server 2008 tech republic
New date datatypes in sql server 2008   tech republicNew date datatypes in sql server 2008   tech republic
New date datatypes in sql server 2008 tech republic
 
Introduction to policy based management in sql server 2008 tech-republic
Introduction to policy based management in sql server 2008   tech-republicIntroduction to policy based management in sql server 2008   tech-republic
Introduction to policy based management in sql server 2008 tech-republic
 
Introduction to change data capture in sql server 2008 tech republic
Introduction to change data capture in sql server 2008   tech republicIntroduction to change data capture in sql server 2008   tech republic
Introduction to change data capture in sql server 2008 tech republic
 

Using object dependencies in sql server 2008 tech republic

  • 1. Using Object Dependencies in SQL Server 2008 | TechRepublic ZDNet Asia SmartPlanet TechRepublic Log In Join TechRepublic FAQ Go Pro! Blogs Downloads Newsletters Galleries Q&A Discussions News Research Library IT Management Development IT Support Data Center Networks Security Home / Blogs / The Enterprise Cloud Follow this blog: The Enterprise Cloud Using Object Dependencies in SQL Server 2008 By John Sheesley October 9, 2008, 10:20 AM PDT Takeaway: Tracking object dependencies has always been difficult with SQL Server. SQL Server 2008 makes it easier because it tracks dependencies by the object’s name rather than ID. Here’s how it works. Previous versions of SQL Server were not that great at keeping track of object dependencies. The reason for this was due to the fact that all object dependencies were tracked by the ID of the object, which meant that the object had to exist first. SQL Server 2008 greatly expands on this capability by tracking objects by the name of the object, rather than relying upon the ID. Advantages of this approach are that object dependencies remain tracked even after some objects have been removed from the database, as well as are tracked even if an object has yet to be created. New Management Objects SQL Server 2008 introduces two new dynamic management functions and a new system view for keeping track of object dependencies. These new objects hold information stored by the Database Engine for dependencies created when objects are created, altered, or dropped. A dependency is created between two objects when one object appears by name inside a SQL expression stored in another object. The object that appears inside the expression is known as the referenced entity, while the object that houses the SQL expression is known as the referencing entity. sys.sql_expression_dependencies This view holds one record for each dependency on a user-defined object in the current database. These user-defined objects can be objects stored in the current database, objects stored in a different database and referenced using a three part naming convention (databasename.schemaname.objectname), objects on a different server and referenced via a linked server using a four part naming convention (servername.databasename.schemaname.objectname), and objects that do not exist at the time the object is created (known as deferred objects). sys.dm_sql_referenced_entities This function returns one row for each user defined object referenced by name in the definition of the specified referencing entity. For example, if the view vw_SampleView references Field1, Field2, and Field3 of the table Table1, then four rows will be returned; three for the referenced fields and one for the table reference. http://www.techrepublic.com/blog/datacenter/using-object-dependencies-in-sql-server-2008/460[08/29/2012 3:42:43 PM]
  • 2. Using Object Dependencies in SQL Server 2008 | TechRepublic sys.dm_sql_referencing_entities This function returns one record for each user defined object in the current database that references another user defined object by name. For example, if the view vw_SampleView references Table1 and Table2, then two records will be returned by this function; one for each table reference. An Example Let’s look at an example of how dependencies are tracked inside the database by creating some objects and querying the new DMVs. Use the script below to create a table named SalesHistory. CREATE TABLE [dbo].[SalesHistory]( [SaleID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED, [Product] [char](150) NULL, [SaleDate] [datetime] NULL, [SalePrice] [money] NULL ) In the following script, I create a stored procedure named dbo.usp_GetSales. This procedure references the SalesHistory table created in the above script. CREATE PROCEDURE dbo.usp_GetSales ( @Product VARCHAR(10) ) AS BEGIN SELECT COUNT(SaleID) AS SalesCount, SUM(SalePrice) AS SalesAmount FROM dbo.SalesHistory sh END The following script uses the table-valued function sys.dm_sql_referenced_returns function to find all objects that reference the SalesHistory table. This query will not only return references to the SalesHistory table, but also includes the fields from the SalesHistory table that are referenced. Note the use of the CROSS APPLY operator. This is due to the fact that entities is a table-valued function and the APPLY operator is required when passing field values to table-valued functions. Note that a call to the sys.dm_referenced_entities function will error if it encounters a reference to an entity field that does not exist. SELECT ReferencedEntityName = o.name, g.referenced_entity_name, referenced_minor_name FROM sys.objects o JOIN sys.schemas s on o.schema_id = s.schema_id CROSS APPLY sys.dm_sql_referenced_entities(s.name + ‘.’ + o.name, ‘OBJECT’) g WHERE referenced_entity_name = ‘SalesHistory’ The following script queries the new dynamic management view sys.dm_sql_referencing_entities to find any objects referenced by the procedure usp_GetSales. http://www.techrepublic.com/blog/datacenter/using-object-dependencies-in-sql-server-2008/460[08/29/2012 3:42:43 PM]
  • 3. Using Object Dependencies in SQL Server 2008 | TechRepublic SELECT ReferencingObject = referencing_entity_name, ReferencedObject = o.name FROM sys.objects o JOIN sys.schemas s on o.schema_id = s.schema_id CROSS APPLY sys.dm_sql_referencing_entities(s.name + ‘.’ + o.name, ‘OBJECT’) g WHERE referencing_entity_name = ‘usp_GetSales’ In the following script, I create a new stored procedure named usp_GetSalesFromArchive, which references the nonexistent SalesHistoryArchive table. CREATE PROCEDURE usp_GetSalesFromArchive ( @Product VARCHAR(10) ) AS BEGIN SELECT COUNT(SaleArchiveID) AS SalesCount, SUM(SaleArchivePrice) AS SalesAmount FROM dbo.SalesHistoryArchive sh END I can now use the sys.sql_expression_dependencies system view to find any objects that reference the SalesHistoryArchive table. Alternatively, I can alter this same query just a bit to find the tables referenced by the usp_GetSalesFromArchive stored procedure. SELECT ReferencingObject = o.name , ReferencedObject = d.referenced_entity_name FROM sys.sql_expression_dependencies d join sys.objects o on d.referencing_id = o.object_id WHERE o.name = ‘usp_GetSalesFromArchive’ Conclusion There are certainly advantages to tracking dependencies via object name rather than object ID. My favorite aspect is the ability to find stored procedures that reference objects that do not exist. This is great because it allows me to find any stored procedures that may not longer be used or perhaps need to be updated. Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free newsletters. http://www.techrepublic.com/blog/datacenter/using-object-dependencies-in-sql-server-2008/460[08/29/2012 3:42:43 PM]
  • 4. Using Object Dependencies in SQL Server 2008 | TechRepublic VMware and Microsoft go iSCSI is the future of storage head to head People who read this... Using Object Dependencies in SQL Server 2008 Moving the Tempdb and Master Database in SQL Server Moving the Tempdb and Master Database in SQL Server 3 Join the conversation! Add Your Opinion Comments Follow via: Staff Picks Top Rated Most Recent My Contacts See All Comments RE: Using Object Dependencies in SQL Server 2008 0 aspemail@... 21st Oct 2008 Votes If the Stored Procedure code was "Select * From ..." then these DMFs/DMVs are smart enough to resolve that from "Select * .." to "Select Col1, col2, col3,....", which I found very interesting. Thought... Read Whole Comment + View in thread RE: Using Object Dependencies in SQL Server 2008 0 aspemail@... 21st Oct 2008 Votes If you could have added screen shots of what the result would have looked like, that would have been great View in thread Parameter Usage 0 aspemail@... 21st Oct 2008 Votes You created 2 SP's in this sample code which passes parameter. Not sure if it was required. View in thread See all comments Join the TechRepublic Community and join the conversation! Signing-up is free and quick, Do it now, we want to hear your opinion. Join Login http://www.techrepublic.com/blog/datacenter/using-object-dependencies-in-sql-server-2008/460[08/29/2012 3:42:43 PM]