{"id":3840,"date":"2013-01-07T21:48:10","date_gmt":"2013-01-07T21:48:10","guid":{"rendered":"http:\/\/craftydba.com\/?p=3840"},"modified":"2013-01-08T21:00:57","modified_gmt":"2013-01-08T21:00:57","slug":"user-defined-views-part-2","status":"publish","type":"post","link":"https:\/\/craftydba.com\/?p=3840","title":{"rendered":"User Defined Views &#8211; Part 2"},"content":{"rendered":"<p><a href=\"https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/green-binary-data.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"alignleft size-thumbnail wp-image-3817\" title=\"green-binary-data\" src=\"https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/green-binary-data-150x128.jpg\" alt=\"\" width=\"150\" height=\"128\" \/><\/a>Today, I want to continue talking about database objects that are associated with stored (compiled) code.<\/p>\n<p>A view can be though as a virtual table whose contents are defined by a TSQL query based on one or more tables in the database.<\/p>\n<p>&nbsp;<\/p>\n<p>Typical uses of a view are the following:<\/p>\n<ol>\n<li>To simplify or customize the perception each user has of the database.<\/li>\n<li>Security mechanism to grant users access to the view, not the underlying base tables.<\/li>\n<li>To provide a backward compatible interface to emulate a table whose schema has changed.<\/li>\n<\/ol>\n<p>Like most Data Definition Language (<a href=\"http:\/\/en.wikipedia.org\/wiki\/Data_definition_language\">DDL<\/a>) constructs, a user defined view has three operations associated with it: <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms187956.aspx\">CREATE VIEW<\/a>, <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms173846.aspx\">ALTER VIEW<\/a> and <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms173492.aspx\">DROP VIEW<\/a>.<\/p>\n<p>I will be using the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/aa992075.aspx\">Adventure Works<\/a> 2012 sample database supplied by Microsoft during this talk.<\/p>\n<p>The TSQL snippet drops the  [HumanResources].[vHireDate] view if it exists.  <\/p>\n<pre><span style=\"color: #008000;\">-- Use the correct database\r\nUSE [AdventureWorks2012]\r\nGO\r\n\r\n-- Delete existing view\r\nIF  EXISTS (\r\n    SELECT * FROM sys.objects\r\n    WHERE object_id = OBJECT_ID(N'[HumanResources].[vHireDate]') AND [type] in (N'V')\r\n)\r\nDROP VIEW [HumanResources].[vHireDate]\r\nGO\r\n\r\n<\/span><\/pre>\n<p>The first lesson is that views are based upon a single simple or complex TSQL statement and to use the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms188385.aspx\">ORDER BY<\/a> clause in a view, we need to specify a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms189463.aspx\">TOP<\/a> 100 filter.  Otherwise, the algebraic parser will stop the statement execution with an error.<\/p>\n<pre><span style=\"color: #008000;\">--\r\n-- Lesson A - use top 100 with order by\r\n--\r\n\r\n-- Alter view, order by clause\r\nCREATE VIEW [HumanResources].[vHireDate] \r\nAS \r\n    SELECT \r\n\tTOP 100 \r\n\tp.FirstName\r\n      , p.LastName\r\n      , e.BusinessEntityID\r\n      , e.HireDate\r\n    FROM \r\n\tHumanResources.Employee e \r\n        JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID\r\n    ORDER BY\r\n\tp.FirstName;\r\nGO\r\n\r\n-- Show the data\r\nSELECT * FROM [HumanResources].[vHireDate]\r\nGO\r\n\r\n<\/span><\/pre>\n<p><a href=\"https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/exploring-views-part2a.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/exploring-views-part2a-1024x270.jpg\" alt=\"\" title=\"Views - Order By Requires Top \" width=\"665\" height=\"175\" class=\"aligncenter size-large wp-image-3849\" srcset=\"https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/exploring-views-part2a-1024x270.jpg 1024w, https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/exploring-views-part2a-300x79.jpg 300w, https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/exploring-views-part2a.jpg 1383w\" sizes=\"auto, (max-width: 665px) 100vw, 665px\" \/><\/a><\/p>\n<p>The second lesson is that view can not contain the following:  reference to <a href=\"http:\/\/www.simple-talk.com\/sql\/t-sql-programming\/temporary-tables-in-sql-server\/\">temporary tables<\/a>, the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms188029.aspx\">INTO<\/a> clause for table creation or the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms190322.aspx\">OPTION <\/a>clause for query hints.  The example below tries to break all three restrictions.  This results in a error produced by the algebraic parser.<\/p>\n<pre><span style=\"color: #008000;\">--\r\n-- Lesson B - Certain constructs not allowed with views.\r\n--\r\n\r\n-- Save employee table as local temp table\r\nSELECT * INTO #tmpEmployee FROM HumanResources.Employee;\r\nGO\r\n\r\n-- Alter view, [into], [option], [#tmp] are syntax errors\r\nALTER VIEW [HumanResources].[vHireDate] \r\nAS \r\n    SELECT \t   \r\n        p.FirstName\r\n      , p.LastName\r\n      , e.BusinessEntityID\r\n      , e.HireDate\r\n--  INTO #tmpBadIdea\r\n    FROM \r\n--      #tmpEmployee e\r\n        HumanResources.Employee e \r\n        JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID\r\n--\tOPTION (MERGE JOIN);\r\nGO\r\n\r\n<\/span><\/pre>\n<p><a href=\"https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/exploring-views-part2b.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/exploring-views-part2b-1024x584.jpg\" alt=\"\" title=\"Views - Restricted Key Words &amp; Objects\" width=\"665\" height=\"379\" class=\"aligncenter size-large wp-image-3853\" srcset=\"https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/exploring-views-part2b-1024x584.jpg 1024w, https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/exploring-views-part2b-300x171.jpg 300w, https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/exploring-views-part2b.jpg 1066w\" sizes=\"auto, (max-width: 665px) 100vw, 665px\" \/><\/a><\/p>\n<p>The third lesson is that the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms180026.aspx\">UNION<\/a> key word should be used to join multiple result sets.  The example below returns all people who&#8217;s first name starts with D or J.<\/p>\n<pre><span style=\"color: #008000;\">--\r\n-- Lesson C - Use union to join result sets\r\n--\r\n\r\n-- Alter view, just people whos names start with D or J\r\nALTER VIEW [HumanResources].[vHireDate] \r\nAS \r\n    -- J names\r\n    SELECT \r\n        p.FirstName\r\n      , p.LastName\r\n      , e.BusinessEntityID\r\n      , e.HireDate\r\n    FROM \r\n        HumanResources.Employee e \r\n        JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID\r\n    WHERE\r\n        P.FirstName LIKE 'J%'\r\n\r\n    UNION ALL\r\n\r\n    -- D names\r\n    SELECT \r\n        p.FirstName\r\n      , p.LastName\r\n      , e.BusinessEntityID\r\n      , e.HireDate\r\n    FROM \r\n        HumanResources.Employee e \r\n        JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID\r\n    WHERE\r\n        P.FirstName LIKE 'D%'\r\nGO\r\n\r\n\r\n-- Show the data\r\nSELECT * FROM [HumanResources].[vHireDate]\r\nGO\r\n\r\n<\/span><\/pre>\n<p>Last but not least, we should restore the user defined view before leaving for the day.<\/p>\n<pre><span style=\"color: #008000;\">-- Restore the definition\r\nALTER VIEW [HumanResources].[vHireDate] \r\nAS \r\n    SELECT \r\n\tp.FirstName\r\n      , p.LastName\r\n      , e.BusinessEntityID\r\n      , e.HireDate\r\n    FROM \r\n\tHumanResources.Employee e \r\n        JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID;\r\nGO\r\n\r\n-- Show the data\r\nSELECT * FROM [HumanResources].[vHireDate]\r\nGO\r\n\r\n<\/span><\/pre>\n<p>To recap today&#8217;s talk, views can be defined by one simple or complex TSQL statement.  To join result sets in the view, use the UNION key word.  Certain keywords and objects are restricted from usage when defining a view.  Please look at the Books On Line (BOL) or MSDN articles for more information.<\/p>\n<p>Next time, I will be discussing options that can used when creating a view.  For each option, I will show an example that will demonstrate why to use it in the first place.<\/p>\n<p><a href='https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/exploring-views-part2.csv'>Views &#8211; Union All Output<\/a><\/p>\n<p><a href='https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/exploring-views-part2.sql_.txt'>Views &#8211; Do&#8217;s and Don&#8217;ts Examples<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Today, I want to continue talking about database objects that are associated with stored (compiled) code. A view can be though as a virtual table whose contents are defined by a TSQL query based on one or more tables in the database. &nbsp; Typical uses of a view are the following: To simplify or customize the perception each user has of the database. Security mechanism to grant users access to the view, not the underlying base tables. To provide a backward compatible interface to emulate a table whose schema has&hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[707,316,31,563,12,712,15,711,40,709,28,713,710,29,88,708],"class_list":["post-3840","post","type-post","status-publish","format-standard","hentry","category-db-dev","tag-alter-view","tag-create-view","tag-database-developer","tag-drop-view","tag-free-code","tag-into","tag-john-f-miner-iii","tag-option","tag-order-by","tag-schema-abstraction","tag-sql-server","tag-temporary-tables","tag-top-100","tag-tsql","tag-union","tag-user-defined-view"],"_links":{"self":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/posts\/3840","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=3840"}],"version-history":[{"count":0,"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/posts\/3840\/revisions"}],"wp:attachment":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3840"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3840"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3840"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}