60 likes | 102 Views
Views. Views CREATE VIEW AS Uses for Views. Views. Views are definitions of queries that can be treated like tables Only the view definition is stored
E N D
Views • Views • CREATE VIEW AS • Uses for Views
Views • Views are definitions of queries that can be treated like tables • Only the view definition is stored • When the view is called the definition is applied against current data in the database and that data is fed into the query that calls the view • Views have several advantages • Serve as a security measure • Simplify complicated queries • Perform tasks difficult to perform in a query • Encapsulate frequently used query segments for reuse
CREATE VIEW • Use a CREATE VIEW Statement to create a view CREATE VIEW vw_SuppliersWithProducts AS SELECT Suppliers.SupplierID, CompanyName, Country, ProductID, ProductName FROM Suppliers INNER JOIN Products ON Suppliers.SupplierID = Products.SupplierID SELECT * FROM vw_SuppliersWithProducts
Using Views for Special Operations • Remember this UNION query? • How can we get the results sorted by CompanyName? SELECT CAST(SupplierID AS char(10)) AS 'ID', CompanyName, 'Supplier' AS 'Type' FROM Suppliers UNION SELECT CAST(CustomerID AS char(10)) AS 'ID', CompanyName, 'Customer' AS 'Type' FROM Customers
Using Views for Special Operations (cont.) • Define thequery as a View • Query theview with ORDER BY CREATE VIEW vw_Companies AS SELECT CAST(SupplierID AS char(10)) AS 'ID', CompanyName, 'Supplier' AS 'Type' FROM Suppliers UNION SELECT CAST(CustomerID AS char(10)) AS 'ID', CompanyName, 'Customer' AS 'Type' FROM Customers SELECT * FROM vw_Companies ORDER BY CompanyName
Managing Views • CREATE VIEW creates the view as a permanent object in the DB • You can delete it from the Views tree node or useDROP VIEW viewname • You cannot create two views with the same name • ALTER VIEW viewname followed by a view definition will replace the old view with the new definition