SQL Servers
Database Questions and Answers Concepts Part2

Q.  What's the main difference between ACCESS and SQL SERVER?

Ans:  As said before access fulfill all of the CODD rules and behaves as a true RDBMS.  But there's a huge difference from architecture perspective, due to which many developers prefer to use SQL SERVER as a major rather than access.  Following is a list of architecture difference between them:

Access uses file server design and SQL SERVER uses the Client/Server model.   The major difference between SQL SERVER and ACCESS.

NOTES: Just to clarify what is client server and file server.   I will make a quick description of widely accepted architectures.  There are three types of architecture:

  • Mainframe architecture(This is not related to the above explaination but just mentioned it as it can be useful during interview and also for comparing with other architectures)
  • File sharing architecture (Followed ACCESS)
  • Client Server architecture (Followed SQL SERVER)

In Mainframe architecture all the processing happens on central host server.   User interacts through dump terminals which only send keystrokes and information to host.  All the main processing happens on the central host server.  So advantage in such type of architecture is that you need least configuration clients.  But the disavantage is that you need robust central host server like mainframe.

In file sharing architecture which is followed by access database, all the data is sent to the client terminal and then processed.  For instance you want to see customers who stay in VietNam, in File Sharing architecture all customer records will be send to the client PC regardless whether the customer belong to Vietnam or not.  On the client PC customer records from Vietnam is sorted/filted out and displayed, in short all processing logic happens on the client PC.  So in this architecture the client PC should have heavy configuration and also it increases network traffic as lot of data is sent to the client PC.  But advantage of this architecture is that your server can be of low configurations.

  1. Client sends request for data to access with certain criteria.
  2. Access Database streams data to client regarless of the criteria.
  3. Criteria is applied on the access streamed data and displayed to the client.

In the client server architecture the above limitation of the file server architecture is removed.  In client server architecture you have two entities client and the database server.  File server is now replaced by the database server.  Database server takes up the load of processing.  Anydatabase related activity and the client any validation aspect of database.  As the work is distributed between the entities, is increases scability and reliability.  Second the network traffic also comes down in compared to file server.  For example if you are requesting customers from Vietnam, database server will sort/filter and send only vietnam customer detail to the client, thus briging down the network traffic tremendously.  SQL SERVER follows the client server architecture.

Client Sends requeste for data to SQL Server with certain criteria

Example IBM Compatible  roundtrip to SQL SERVER Database.

Client Server Architecture of SQL Server

Second issue comes in terms of reliability.  In Access the client directly interacts with the access file, in case there is some problem in middle of transaction there are chances that access file can get corrupt.  But in SQL Server the engine sits in between the client and the database, so in case of any problems in middle of the transaction it can revert back to its original state.

NOTE: SQL SERVER maintain a transaction log by which you can rever back to your original state in case of any crash.

When your application has to cater to huge load demand, highly transactional environment and high concurrency then its better go for SQL SERVER or MSDE.

But when it comes to cost and support then access stand better than SQL SERVER.  In case of SQL Server you have to pay per client license, but access runtime is free.

Summarizing: SQL SERVER gains points in term of network traffic, reliability and scalability vice-versa access gains points in term of cost factor.

Q.  What's the difference between MSDE and SQL SERVER 2000?

Ans:  MSDE is a royalty free, redistributable and cut short version of the giant SQL SERVER databae.  It's primarity provided as low cost option for developers who need database server which can easily be shipped and installed.  It can serve as good alternative for Microsoft Access Database as it over comes a lot of problemss which Access has

Size of database:-

  • MS Access and MSDE have limitation of 2GB, SQL Server has 1,048,516 TB1. 
  • Performance degrades in MSDE 2000 when maximum number of concurrent operations goes above 8 or equal to 8.  It does not mean that you can not have more then eight concurrent operation but the performance degrades.  Eight connection performance degradation is implemented by using SQL SERVER 2000 work load governor (we will have to looking into to more detail of how it works).  As compared to SQL SERVER 2000 you can have 32, 767 concurrent connections.
  • MSDE does not provide OLAP and Data ware housing capabilities.
  • MSDE does not have support facility for SQL mail.
  • MSDE does not have GUI administrative tool such as enterprise manager, query analyzer or profiler.  But there are round about ways by which you can manage MSDE 2000.
  •   Old command line utility OSQL.EXE,
  •   VS.NET  IDE server explore: Inside VS.NET IDE you can have a functionality which can give youa nice GUI administrater tool to manage IDE
  • SQL SERVER WEB Database administrator installs a web based GUI which you can use to manage your database.   For any details refer http://www.microsoft.com/downloads/details.asp?familyid=c039a798-c57a-419e-acbc-2a332cb7f959&displaylang=en
  • SQL-DMO objects can be used to build your custom UI.
  • There are a lot of third party tools which provide administrative capability GUI, which is out of scope of the book as it's meant for interview questions.
  • MSDE does not support Full text search.

Please note: There are two major differences first is the size limitation (2GB) of database and second are the concurrent connections (eight concurrent connections) Which are limited by using load govenor .  During interview this answer will suffice if he is really testing your knowledge.

Q.  What is SQL SERVER 2005 Edition?

Ans:

Twist: What's difference between SQL SERVER Express 2005 and MSDE 2000

NOTE:  Normaly conmparison  is when the product is migrating from one version to other version.  When SQL SERVER 7.0 was migrating  to SQL Server 2000, asking differences was one of the favorite questions.

SQL SERVER Express edition is a scaled down version of SQL SERVER 2005 and next evolution of MSDE.

Listed are some major difference between them:

  • IN term of programming language support MSDE has only TSQL, but SQL SERVER Express has TSQL and .NET.  In SQL SERVER Express 2005 you can write your stored procedures using ,NET
  • SQL SERVER Express does not have connection limitation which MSDE had and was controlled through the work load govenor.
  • There was no XCOPY support for MSDE, SQL SERVER Express has it.
  • DTS is not present in SQL SERVER Express while MSDE has it.
  • SQL SERVER Express has reporting services while MSDE does not.
  • SQL SEVER Express has native XML support while MSDE does not.

NOTE: Native XML support mean now in SQL SERVER 2005

  • You can create a field with data type"XML".
  • You can provide new XML manipulation technique like "XQUERY" also called as "XML QUERY".

There is complete chapter on SQL SERVER XML support so till then this will suffice.

Sumarizing:  Major difference is database size (2GB and 4GB), support .NET support in stored procedures and native support for XML.  This is much can convince the interviewer that you are clear about the differences.

Q. What is SQL SERVER 2000 Workload Govenor?

Ans:  Workload governor limits performance of SQL SERVER Desktop engine (MSDE) if the SQL engine receives more  load than what is mean for MSDE.  MSDE was always meant for trial purpose and non-critical projects.  Microsoft always wanted companies to buy there full blown version of SQL SERVER so in order that they can put limitation on MSDE performance and number of connections they introduced workload governor.

Worload governor sits between client and database engine and counts number of connection per database instance.  If workload governor finds that the number of connection exceeds eight connections, it starts stalling the connections and slowing down the database engine.

NOTE:  It does not limit the number of connections but makes connections request go slow.  By defaul 32, 767 connections are allowed bith SQL SERVER and MSDE.  But it makes the database engine go slow above eight connections.

Q.  What's the difference between SQL SERVER 2000 and 2005?

Ans:

Twist: What's the difference between Yokon and SQL SERVER 2000?

NOTE:  This question will be one of the favorites during SQL SERVER interview.  I have marked the points which should be said by developers as PG and DBA for Database Administrator.

Following are the some major differences between the two versions:

  • (PG) the most significant change is the .NET integration with SQL SERVER 2005. Stored procedures, User-defined functions, triggers, aggregates, and user-defined types can now be written using your own favorite .NET language(VB.NET, C#, J# etc.).  This supportwas not there in SQL SERVER 2000 where only language was in TSQL.  In SQL SERVER 2005 you have support for two languages T-SQL and ,NET.
  • (PG) SQL SERVER 2005 has reporting services for reports which is a newly added feature and does not exist for SQL SERVER 2000.  It was a seperate installation for SQL SERVER 2000.
  • (PG) SQL SERVER 2005 has introduced tow new data types virbinary (max) and XML.  If you remember in SQL SERVER 2000 we had image and text data types.  Problem with image and text datatypes is that they assign same amount of storage irrespective of what the actual data size is.  This problem is solved using varbinary (max) which arts depending on amount of data.  One more new data type is included "XML" which enables you to store XML documents and also does schema vertification.  In SQL SERVER 2000
  • developers used varchar or text data type and all validation had to be done programmatically.
  • (PG)SQL SERVER 2005 now can process direct incoming HTTP request with out ISS web server.  Also stored procedure invocation is enabled using SOAP protocol.
  • (PG) Asynchronous mechanism is introduced using server events.  In Server event model the server post an event to the SQL Broker Service, later the client can come and retrieve the status by querying the broker.
  • For huge database SQL SERVER has provided a cool feature called as "Data partitioning".  In data partitioning you break a single database object such as a table or an index into multiple pieces.  But for the clientapplication accessing the single database object "partitioning" is transparent.
  • In SQL SERVER 2000 if you rebuilt clustered indexes even the non-clustered indexes where rebuilt.  But in SQL SERVER 2005 building the clustered indexes does not buil the non-clustered indexes.
  • Bulk data uploading in SQL SERVER 2000 was done using BCP(Bulk copy program's) format files.  But now in SQL SERVER 2005 bulk data uploading uses XML format.
  • In SQL SERVER 2000 there where maximum 16 instances, but in SQL 2005 you can have up to 50 instances.
  • SQL SERVER 2005 has support of "Multiple Active Result Sets" also called as "MARS".   In previous version of SQL Server 2000 in one connection you can only have one result set.  But now one SQL connection you can query and have multiple result set.
  • In previous version of SQL SERVER 2000, system catalog was stored in master database.  In SQL SERVER 2005 it's stored in resource database which is stored as sys object, you cannot access the sys object as in older version we were accessing master database.
  • This is one of the hardware benifits which SQL SERVER 2005 has over SQL SERVER 2000- support of hyper threading.  WINDOWS 2003 supports hyper threading; SQL SERVER 2005 can take the advantage of the feature unlike SQL SERVER 2000 which did not support hyper threading.

NOTE:  Hyper threading is a technology developed by INTEL which creates two logical processors on a single physical hardware processor.

  • SMO will be used for SQL Server Management.
  • AMO(Analysis Management Objects) to manage Analysis services server, data sources, cubes, dimensions, measures, and data mining models.  You can map AMO in old SQL SERVER with DSO(Description Support Objects). NOTE: SMO, AMO, And RMO are all using .NET Framework.
  • SQL SERVER 2005 uses current user execution context to check rights rather than ownership link chain, which was done in SQL SERVER 2000.
  • In previous versions of SQL SERVER the schema and the user name was the same, but in current the schema is seperated from the user.   Now the user own schema.
  • Query analyzer is now replaced by query editor
  • Business Intelligent development studio will be used to create Business Intelligent Solution.
  • OSQL and ISQL command line utility is replaced by SQLCMD utility.
  • SQL SERVER Enterprise manager is now replaced by SQL SERVER Management Studio.
  • Server Manager which was running in system tray is now replaced by SQL Computer Manager.
  • Database mirror concept supported in SQL SERVER 2005 which was not present in SQL SERVER 2000.
  • In SQL SERVER 2005 Indexes can be rebuild online when the databaase is in actual production.  If you look back in SQL SERVER 2000 you cannot do insert, update, and delete operations when you are building indexes.
  • (PG) Other than Serialiable, Repeatable Read, Read Committed and Read Uncommitted isolation level there is one more new isolation level "snapshot Isolation level".

Summarizing:  The major significant difference between SQL SERVER 2000 and SQL SERVER 2005 is in term of support of .NET Intergration, snapshot isolation level, Native XML support, Handling HTTP request, Web Service support and Data partitioning.  You do not have to really say all the above points during interview, a sweet summary and you will rock.

Continuing in Database Questions and Answers Concepts Part3.  and don't forget check out my personal website: http://m.aatechsources.com Article and Forum

 


                                  

 

Database Questions and Answers Concepts Part1

Q.  What is database or database management systems (DBMS)?

TWIST: - What's the different between file and database? Can files qualify as a database?

NOTE:   Probably these questions are too basic for experienced SQL Server guys.   But from freshers point of view it can be a difference between getting a job and to be jobless.

Ans:  Database provides a systematic and organized ways of storing, managing and retrieving from collection of logically related information.   Secondly the information has to be persistent, that means even after the application is closed the information should be persisted.

OK, let me spend a few sentence more on explaining the third aspect.  A simple figure of text file which has personal detail information.   The first column of the information is Name, second address and finally the phone number.  If you picture a non-Uniform text file which was designed by a programmer for a specific application.

Its work fine in the boundary of the application.  Now some years down the line a third party application has to be intergrated with this file, so in order the third party application intergrates properly it has the following option:-

-Use Interface of the original application.

-Understand the complete detail of how the text file is organized, example the first column is Name, then address and finally phone number.  After analyzing write a code which can read the file, parse it etc...Hmm lot of work right.

That's what the main difference between a simple file and database; database has independent way (SQL) of accessing information while simple files do not (That answers my twisted question defined above).  File meets the storing, managing and retrieving part of a database but not the independent way of accessing data.

NOTE:  Many experienced programmers think that the main different is that the file can not provide multi-user capabilities which a DBMS provides.   But if you look at some old COBOL and C programs where file where the only means of storing data, you can see functionalities like locking, multi-user etc provided very efficiently.   So it's matter of debate if some interviewers think this is a main difference betwwen files and database accept it...going into debate is probably loosing a job.

(Just a note for fresher's multi-user capabilities means that at one moment of time more than one user should be able to add, update, view and delete data.  All DBMS provides this as built funtionalities but if you are storing information in files it's up to the application to write logic to achieve these fuctionalities)

Q.  What's difference between DBMS and RDBMS?

Ans:  OK as said before DBMS provides a systematic and organized way of storing, managing, and retrieving from collection of logically related information.  RDBMS also provides what DBMS provides but above that it provides relationship integrity.  So in short we can say

RDBMS = DBMS + REFERENTIAL INTEGRITY

Example above is that every person should have an address this is referential integrity between "Name" and "Address".  If we break this referential integrity in DBMS and File's it will no complain, but RDBMS will not allow you to save this data if you have defined the relation intergrity between person and address.  These relations are defined by using "foreign Keys" in any RDBMS.

NOTE: One of the biggest debate, is Microsoft Access a RDBMS? We will answer this question in later section.

Q. (DB) What are CODD rules?

TWIST: Does SQL Server support all the twelve CODD rules?

NOTE:  This question can only be asked on two conditions when the interviewer is expecting you to be a DBA job or you are complete fresher, yes and not to mention the last one he treats CODD rules as a religion.  We will try to answer this question from perspective of SQL Server.

Rule 1: Information rule.

"All information in a relational data base is represented explicity at the logical level and in exactly one way - by values in tables.

Rule 2: Guaranteed access rule.

"Each and every datum(atomic value) in a relational database is guranteed to be logically accessible by resorting to a combination of table name, primary key value and column name."

In flat files we have to parse and know exact location of field values.  But if a DBMS is truly RDBMS you can access the value by specifying the table name, field name, for instance Customer.fields ['Customer Name']

SQL Server also sastisies this rule in ADO.NET we can access field information using table name and field names.

Rule 3: Systematic treatment of null values.

"Null values (distinct from the empty character string or a string of blank characters and distinct from zero or any other number) are supported in fully relational DBMS for representing missing information and inapplicable information in a systematic way, independent of data type."

Rule 4. Dynamic on-line catalog based on the relational model.

"The database description is represented at the logical level in the same way as ordinary data, so that authorized users can apply the same relational language to its interrogation as they apply to the regular data."

The Data Dictionary is held within the RDBMS, thus there is no-need for off-line volumes to tell you the structure od the database.

Rule 5. Comprehensive data sub-language Rule.

"A relational system may support several languages and various modes of terminal use (for example, the fill-in-blanks mode).  However, there must be at least one language whose statements are expressible, per some well-defined sysntax, as character strings and that is someprehensive in supporting all the following items

Data Definition

View Definition

Data Manipulation (interactive and by program)

Integrity Constrainst

Authorization

Transaction boundaries (Begin, commit, and roll back)

SQL Server uses SQL to query and manipulate data which has well-defined syntax and is being accepted as an international standard for RDBMS.

NOTE: According to this rule CODD has only mentioned that some language should be present to support it, but not neccessary that it should be SQL.  Before 80's different database vendors where providing there own flavor of sysntaxes until 80 ANSI- SQL came into standardlize this variation between vendors.  As ANSI-SQL is quiet limited, every vendor including Microsoft introduced there additional SQL syntaxes in addition to the support of ANSI-SQL.  You can see SQL syntaxes varying from vendor to vendor.

Rule 6. View updating Rule.

"All views that are theoritically updatable are also updateable by the system."

In SQL Server not only views can be updated by user, but also by SQL Server itselt.

Rule 7. High-level insert, update, and delete.

"The capablility of handling a base relation or a derived relation as a single operand appliesnot only to the retrieval of data but also to the insertion, update and deletion of data."

SQL Server allows you to update views which in turn affect the base tables.

Rule 8. Physical data independence.

"Apllication programs and terminal activities remain logically unimpaired whenever any changes made in either storage representations or access methods."

Any application program(C#, VB.NET, Vb6, VC ++ etc) Does not need to be aware of where the SQL Server is physically stored or what type of protocal it's using, database connection string encapsulates everything.

Rule 9. Logical data independence.

"Application programs and terminal activities remain logically unimpaired when information-preserving changes of any kind that theoretically permit un-impairment are made to these tables.

Application programm written in C# or VB.NET does not need to know about any structure changes in SQL Server database example:- adding of new field etc.

Rule 10. Integrity independence.

"Integrity constraints specific to a particular relational database must defineable in the relational data sub-langage and storeable in the catalog, not in the application programs."

In SQL Server you can specify data types data types (integer, nvarchar, boolean etc) which puts in data type checks in SQL Server rather than through application programs.

Rule 11. Distribution independence.

"A relational DBMS has distribution independence."

SQL Server can spread across more than one physical computer and across several networks; but from application program point of view it is not a big difference but just specifying the SQL Server name and the computer on which located.

Rule 12. Non-Subversion Rule.

"If a relational system has a low-level(single-record-at-a-time) language, that low level cannot be used to subver or bypass the integrity Rules and constraints expressed in the higher level relational language (multiple-records-at-a-time)."

In SQL Server whatever integrity rules are applied on every record are also applicable when you process a group of records using application program in any other language (C#, VB.NET, J# etc...)

Q.  Is Access database a RDBMS?

Ans:  Access fullfills all rules of CODD, so from this point of views yes it's truly RDBMS.  But many people can contradict it as a large community of Microsoft professional thinks that ACCESS is not.

See Database Questions and Answers Concepts Part2,  and don't forget check out my personal website: http://m.aatechsources.com Article and Forum

 

 

 

 

 

 

View in SQL Sever 2005
 

 

 

USE Northwind;

-----------------------------------

-- Create a view to format data for

-- mailing labels

-----------------------------------

CREATE

VIEW dbo.vwEmployeeAddressLabels

AS

SELECT

 

Address

FirstName + SPACE(1) + LastName + Char(13) + Char(10) + + Char(13) + Char(10) +

City

+

 

 

 

 

CASE WHEN Region IS NULL THEN ' ' + PostalCodeELSE ', ' + Region + ' ' + PostalCodeEND

 

 

+ Char(13) + Char(10) + CountryAS Address

FROM

dbo.Employees;

GO

-- Select from the view:

-- (best viewed with results to text)

SELECT

* FROM dbo.vwEmployeeAddressLabels;

-----------------------------------

-- Create a view to show

-- customers with the most orders

-----------------------------------

CREATE

 

SELECT

VIEW dbo.vwCustomersTopTen AS TOP (10) WITH TIES

c

.CustomerID,

c

.CompanyName,

 

COUNT(*) AS NumOrders

FROM

 

 

dbo.Customers AS cINNER JOIN dbo.Orders AS oON c.CustomerID=o.CustomerID

GROUP

BY c.CustomerID,

c

.CompanyName

ORDER

BY NumOrders DESC;

GO

-- Select from the view:

SELECT

CustomerID, CompanyName, NumOrders

FROM

dbo.vwCustomersTopTen

ORDER

BY NumOrders DESC;

--------------------------------------

-- Create a view that checks to see

-- if any Orders have details

-- with prices under 3 dollars.

-- Includes an example of using

-- a correlated subquery.

--------------------------------------

CREATE

VIEW dbo.vwOrderLowPrices

AS

 

 

 

SELECT OrderID, OrderDateFROM dbo.Orders AS OWHERE EXISTS

 

 

 

 

(SELECT OD.OrderID FROM dbo.[Order Details] AS OD WHERE O.OrderID = OD.OrderIDAND OD.UnitPrice < 3)

-- Select from the view:

SELECT

OrderID, OrderDate

FROM

GO

dbo.vwOrderLowPrices

--------------------------

-- The same query using

-- a JOIN instead of a subquery

--------------------------

CREATE

VIEW dbo.vwOrderLowPricesJoin

AS

 

 

 

 

 

GO

SELECT O.OrderID, O.OrderDateFROM dbo.Orders AS O INNER JOIN dbo.[Order Details] AS OD ON O.OrderID = OD.OrderIDWHERE OD.UnitPrice < 1

-- Select from the view:

SELECT

OrderID, OrderDate

FROM

dbo.vwOrderLowPricesJoin;

-------------------------------------

-- Derived tables and nesting views

-------------------------------------

SELECT

Derived

P.ProductName, P.UnitPrice, .AvgPrice, C.CategoryName

FROM

dbo.Products AS P

INNER

JOIN

 

 

 

 

(SELECT CategoryID, AVG(UnitPrice) AS AvgPriceFROM dbo.ProductsGROUP BY CategoryID)

 

Derived

AS Derived ON .CategoryID = P.CategoryID

INNER

JOIN

dbo

P

.Categories AS C ON .CategoryID = C.CategoryID

ORDER

BY P.UnitPrice DESC

-- Here are 2 views to replace the derived table

CREATE

VIEW dbo.vwAvgByCategory

AS

 

 

 

GO

SELECT CategoryID, AVG(UnitPrice) AS AvgPriceFROM dbo.ProductsGROUP BY CategoryID

CREATE

VIEW dbo.vwPriceListWithAvg

AS

 

V

SELECT P.ProductName, P.UnitPrice, .AvgPrice,

C

 

 

.CategoryNameFROM dbo.Products AS PINNER JOIN

dbo

 

 

.vwAvgByCategory AS VON V.CategoryID = P.CategoryIDINNER JOIN

dbo

P

GO

.Categories AS C ON .CategoryID = C.CategoryID

--Select from the outer view

SELECT

* FROM dbo.vwPriceListWithAvg

ORDER

BY UnitPRice DESC;

----------------------------------------

-- Using a Common Table Expression (CTE)

----------------------------------------

WITH

CategoryAverages(CategoryID, AvgPrice)

AS

(

 

 

 

 

SELECT CategoryID, AVG(UnitPrice) AS AvgPriceFROM dbo.ProductsGROUP BY CategoryID

)

SELECT

CA

P.ProductName, P.UnitPrice, .AvgPrice, C.CategoryName

FROM

dbo.Products AS P

INNER

JOIN

CategoryAverages

AS CA ON CA.CategoryID = P.CategoryID

INNER

JOIN

dbo

P

.Categories AS C ON .CategoryID = C.CategoryID

ORDER

BY P.UnitPrice DESC;

------------------------------

-- Encrypting view definitions

------------------------------

CREATE

VIEW dbo.vwEncrypted

WITH

ENCRYPTION

AS

SELECT

CustomerID, CompanyName

FROM

dbo.Customers

WHERE

City='Paris';

GO

SELECT

* FROM vwEncrypted;

-- Try getting the T-SQL back

EXEC

sp_helptext 'dbo.vwEncrypted';

-- But it works on an unencrypted view

EXEC

sp_helptext 'dbo.vwEmployeeAddressLabels';

-- Same for the new OBJECT_DEFINITION function

SELECT

OBJECT_DEFINITION(OBJECT_ID('dbo.vwEncrypted'));

SELECT

OBJECT_DEFINITION(OBJECT_ID('dbo.vwEmployeeAddressLabels'));

------------------------------

-- Using WITH CHECK OPTION

------------------------------

CREATE

VIEW dbo.vwOrdersWithCheck

AS

SELECT

OrderID, OrderDate, EmployeeID

FROM

dbo.Orders

WHERE

EmployeeID = 5

WITH

CHECK OPTION;

GO

UPDATE

dbo.vwOrdersWithCheck

SET

EmployeeID = 6;

------------------------------

-- Updating limitations

------------------------------

CREATE

VIEW dbo.vwCustomerAddresses

AS

SELECT

CustomerID, ContactName,

CompanyName

 

Address

+ Char(13) + Char(10) + + Char(13) + Char(10) +

City

+

 

 

 

 

CASE WHEN Region IS NULL THEN ' ' + PostalCodeELSE ', ' + Region + ' ' + PostalCodeEND

 

 

+ Char(13) + Char(10) + CountryAS Address

FROM

GO

dbo.Customers

SELECT

* FROM dbo.vwCustomerAddresses

WHERE

CustomerID='GREAL';

-- This update works

UPDATE

dbo.vwCustomerAddresses

SET

ContactName = 'Gomer Snyder'

WHERE

CustomerID = 'GREAL';

-- This update will fail, because

-- Address is a calculated column.

UPDATE

 

 

dbo.vwCustomerAddresses SET Address = 'Test Address' WHERE CustomerID = 'GREAL';

----------------------------

-- Updating views with joins

----------------------------

CREATE

VIEW dbo.vwProductByCategory

AS

 

SELECT C.CategoryName,

P

 

.ProductID, P.ProductNameFROM dbo.Products AS P INNER JOIN

dbo

.Categories AS C ON

P

GO

.CategoryID = C.CategoryID

-- Both of these will work:

UPDATE

 

dbo.vwProductByCategorySET ProductName = 'Tofu'

 

WHERE ProductID = 14

UPDATE

 

dbo.vwProductByCategorySET CategoryName = 'Produce'

 

WHERE ProductID = 14

-- But not this:

UPDATE

 

dbo.vwProductByCategorySET ProductName = 'Tofu', CategoryName = 'Produce'

 

WHERE ProductID = 14

----------------------------

-- Creating computed columns

----------------------------

-- Create the table with the expression

CREATE

TABLE dbo.LineItems

(

LineID

int IDENTITY(1,1) NOT NULL,

Price

money NOT NULL,

Quantity

smallint NOT NULL,

Total

 

)

AS (Price * Quantity) CONSTRAINT PK PRIMARY KEY CLUSTERED (LineID ASC)

GO

--Insert some data into the table

INSERT

INTO dbo.LineItems VALUES(35.95, 4);

INSERT

INTO dbo.LineItems VALUES(7.99, 12);

INSERT

INTO dbo.LineItems VALUES(12.5, 70);

--View the result set

SELECT

* FROM dbo.LineItems;

--------------------------------------

-- Creating and using an Indexed View

--------------------------------------

--Set the options to support indexed views.

SET

NUMERIC_ROUNDABORT OFF;

SET

ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT,

 

QUOTED_IDENTIFIER, ANSI_NULLS ON;

GO

--Create the view with schema binding.

CREATE

VIEW dbo.vwSalesByDateByProduct

WITH

SCHEMABINDING

AS

 

 

SELECT OrderDate, ProductID, SUM(UnitPrice*Quantity*(1.00-Discount)) AS Sales,

 

 

 

 

GO

COUNT_BIG(*) AS LineItemCountFROM dbo.[Order Details] OD JOIN dbo.Orders O ON OD.OrderID=O.OrderID GROUP BY OrderDate, ProductID

--Get the data

SELECT

GO

* FROM dbo.vwSalesByDateByProduct

--Create the index on the view.

CREATE

UNIQUE CLUSTERED INDEX idx_vwdSalesByDateByProduct

ON

dbo.vwSalesByDateByProduct (OrderDate, ProductID)

GO

--This query will use the view index.

SELECT

SUM(UnitPrice*Quantity*(1.00-Discount)) AS Sales, OrderDate, ProductID

FROM

dbo.[Order Details] OD JOIN dbo.Orders O

ON

OD.OrderID = O.OrderID

WHERE

ProductID in (7, 89, 22, 34)

 

AND OrderDate >= '05/01/1998'

GROUP

BY OrderDate, ProductID

ORDER

BY Sales DESC;

--This query will use the view index too.

SELECT

OrderDate, SUM(UnitPrice*Quantity*(1.00-Discount)) AS Mar98Sales

FROM

dbo.[Order Details] OD JOIN dbo.Orders O

ON

OD.OrderID = O.OrderID

WHERE

 

DATEPART(mm,OrderDate)= 3AND DATEPART(yy,OrderDate) = 1998

GROUP

BY OrderDate

ORDER

BY OrderDate;

----------

--Cleanup

----------

DROP

TABLE dbo.LineItems;

DROP

VIEW dbo.vwEmployeeAddressLabels;

DROP

VIEW dbo.vwCustomersTopTen;

DROP

VIEW dbo.vwOrderLowPrices;

DROP

VIEW dbo.vwOrderLowPricesJoin;

DROP

VIEW dbo.vwAvgByCategory;

DROP

VIEW dbo.vwPriceListWithAvg;

DROP

VIEW dbo.vwEncrypted;

DROP

VIEW dbo.vwOrdersWithCheck;

DROP

VIEW dbo.vwCustomerAddresses;

DROP

VIEW dbo.vwProductByCategory;

DROP

VIEW dbo.vwSalesByD

Created Sample database SQL Server 2005

 

 

USE master
GO
if exists (select * from sysdatabases where name='Northwind')
  drop database Northwind
go

DECLARE @device_directory NVARCHAR(520)
SELECT @device_directory = SUBSTRING(filename, 1, CHARINDEX(N'master.mdf', LOWER(filename)) - 1)
FROM master.dbo.sysaltfiles WHERE dbid = 1 AND fileid = 1

EXECUTE (N'CREATE DATABASE Northwind
  ON PRIMARY (NAME = N''Northwind'', FILENAME = N''' + @device_directory + N'northwnd.mdf'')
  LOG ON (NAME = N''Northwind_log'',  FILENAME = N''' + @device_directory + N'northwnd.ldf'')')
go

exec sp_dboption 'Northwind','trunc. log on chkpt.','true'
exec sp_dboption 'Northwind','select into/bulkcopy','true'
GO

set quoted_identifier on
GO

/* Set DATEFORMAT so that the date strings are interpreted correctly regardless of
   the default DATEFORMAT on the server.
*/
SET DATEFORMAT mdy
GO
use "Northwind"
go
if exists (select * from sysobjects where id = object_id('dbo.Employee Sales by Country') and sysstat & 0xf = 4)
 drop procedure "dbo"."Employee Sales by Country"
GO
if exists (select * from sysobjects where id = object_id('dbo.Sales by Year') and sysstat & 0xf = 4)
 drop procedure "dbo"."Sales by Year"
GO
if exists (select * from sysobjects where id = object_id('dbo.Ten Most Expensive Products') and sysstat & 0xf = 4)
 drop procedure "dbo"."Ten Most Expensive Products"
GO
if exists (select * from sysobjects where id = object_id('dbo.Category Sales for 1997') and sysstat & 0xf = 2)
 drop view "dbo"."Category Sales for 1997"
GO
if exists (select * from sysobjects where id = object_id('dbo.Sales by Category') and sysstat & 0xf = 2)
 drop view "dbo"."Sales by Category"
GO
if exists (select * from sysobjects where id = object_id('dbo.Sales Totals by Amount') and sysstat & 0xf = 2)
 drop view "dbo"."Sales Totals by Amount"
GO
if exists (select * from sysobjects where id = object_id('dbo.Summary of Sales by Quarter') and sysstat & 0xf = 2)
 drop view "dbo"."Summary of Sales by Quarter"
GO
if exists (select * from sysobjects where id = object_id('dbo.Summary of Sales by Year') and sysstat & 0xf = 2)
 drop view "dbo"."Summary of Sales by Year"
GO
if exists (select * from sysobjects where id = object_id('dbo.Invoices') and sysstat & 0xf = 2)
 drop view "dbo"."Invoices"
GO
if exists (select * from sysobjects where id = object_id('dbo.Order Details Extended') and sysstat & 0xf = 2)
 drop view "dbo"."Order Details Extended"
GO
if exists (select * from sysobjects where id = object_id('dbo.Order Subtotals') and sysstat & 0xf = 2)
 drop view "dbo"."Order Subtotals"
GO
if exists (select * from sysobjects where id = object_id('dbo.Product Sales for 1997') and sysstat & 0xf = 2)
 drop view "dbo"."Product Sales for 1997"
GO
if exists (select * from sysobjects where id = object_id('dbo.Alphabetical list of products') and sysstat & 0xf = 2)
 drop view "dbo"."Alphabetical list of products"
GO
if exists (select * from sysobjects where id = object_id('dbo.Current Product List') and sysstat & 0xf = 2)
 drop view "dbo"."Current Product List"
GO
if exists (select * from sysobjects where id = object_id('dbo.Orders Qry') and sysstat & 0xf = 2)
 drop view "dbo"."Orders Qry"
GO
if exists (select * from sysobjects where id = object_id('dbo.Products Above Average Price') and sysstat & 0xf = 2)
 drop view "dbo"."Products Above Average Price"
GO
if exists (select * from sysobjects where id = object_id('dbo.Products by Category') and sysstat & 0xf = 2)
 drop view "dbo"."Products by Category"
GO
if exists (select * from sysobjects where id = object_id('dbo.Quarterly Orders') and sysstat & 0xf = 2)
 drop view "dbo"."Quarterly Orders"
GO
if exists (select * from sysobjects where id = object_id('dbo.Customer and Suppliers by City') and sysstat & 0xf = 2)
 drop view "dbo"."Customer and Suppliers by City"
GO
if exists (select * from sysobjects where id = object_id('dbo.Order Details') and sysstat & 0xf = 3)
 drop table "dbo"."Order Details"
GO
if exists (select * from sysobjects where id = object_id('dbo.Orders') and sysstat & 0xf = 3)
 drop table "dbo"."Orders"
GO
if exists (select * from sysobjects where id = object_id('dbo.Products') and sysstat & 0xf = 3)
 drop table "dbo"."Products"
GO
if exists (select * from sysobjects where id = object_id('dbo.Categories') and sysstat & 0xf = 3)
 drop table "dbo"."Categories"
GO
if exists (select * from sysobjects where id = object_id('dbo.Customers') and sysstat & 0xf = 3)
 drop table "dbo"."Customers"
GO
if exists (select * from sysobjects where id = object_id('dbo.Shippers') and sysstat & 0xf = 3)
 drop table "dbo"."Shippers"
GO
if exists (select * from sysobjects where id = object_id('dbo.Suppliers') and sysstat & 0xf = 3)
 drop table "dbo"."Suppliers"
GO
if exists (select * from sysobjects where id = object_id('dbo.Employees') and sysstat & 0xf = 3)
 drop table "dbo"."Employees"
GO
CREATE TABLE "Employees" (
 "EmployeeID" "int" IDENTITY (1, 1) NOT NULL ,
 "LastName" nvarchar (20) NOT NULL ,
 "FirstName" nvarchar (10) NOT NULL ,
 "Title" nvarchar (30) NULL ,
 "TitleOfCourtesy" nvarchar (25) NULL ,
 "BirthDate" "datetime" NULL ,
 "HireDate" "datetime" NULL ,
 "Address" nvarchar (60) NULL ,
 "City" nvarchar (15) NULL ,
 "Region" nvarchar (15) NULL ,
 "PostalCode" nvarchar (10) NULL ,
 "Country" nvarchar (15) NULL ,
 "HomePhone" nvarchar (24) NULL ,
 "Extension" nvarchar (4) NULL ,
 "Photo" "image" NULL ,
 "Notes" "ntext" NULL ,
 "ReportsTo" "int" NULL ,
 "PhotoPath" nvarchar (255) NULL ,
 CONSTRAINT "PK_Employees" PRIMARY KEY  CLUSTERED
 (
  "EmployeeID"
 ),
 CONSTRAINT "FK_Employees_Employees" FOREIGN KEY
 (
  "ReportsTo"
 ) REFERENCES "dbo"."Employees" (
  "EmployeeID"
 ),
 CONSTRAINT "CK_Birthdate" CHECK (BirthDate < getdate())
)
GO
 CREATE  INDEX "LastName" ON "dbo"."Employees"("LastName")
GO
 CREATE  INDEX "PostalCode" ON "dbo"."Employees"("PostalCode")
GO

CREATE TABLE "Categories" (
 "CategoryID" "int" IDENTITY (1, 1) NOT NULL ,
 "CategoryName" nvarchar (15) NOT NULL ,
 "Description" "ntext" NULL ,
 "Picture" "image" NULL ,
 CONSTRAINT "PK_Categories" PRIMARY KEY  CLUSTERED
 (
  "CategoryID"
 )
)
GO
 CREATE  INDEX "CategoryName" ON "dbo"."Categories"("CategoryName")
GO

CREATE TABLE "Customers" (
 "CustomerID" nchar (5) NOT NULL ,
 "CompanyName" nvarchar (40) NOT NULL ,
 "ContactName" nvarchar (30) NULL ,
 "ContactTitle" nvarchar (30) NULL ,
 "Address" nvarchar (60) NULL ,
 "City" nvarchar (15) NULL ,
 "Region" nvarchar (15) NULL ,
 "PostalCode" nvarchar (10) NULL ,
 "Country" nvarchar (15) NULL ,
 "Phone" nvarchar (24) NULL ,
 "Fax" nvarchar (24) NULL ,
 CONSTRAINT "PK_Customers" PRIMARY KEY  CLUSTERED
 (
  "CustomerID"
 )
)
GO
 CREATE  INDEX "City" ON "dbo"."Customers"("City")
GO
 CREATE  INDEX "CompanyName" ON "dbo"."Customers"("CompanyName")
GO
 CREATE  INDEX "PostalCode" ON "dbo"."Customers"("PostalCode")
GO
 CREATE  INDEX "Region" ON "dbo"."Customers"("Region")
GO

CREATE TABLE "Shippers" (
 "ShipperID" "int" IDENTITY (1, 1) NOT NULL ,
 "CompanyName" nvarchar (40) NOT NULL ,
 "Phone" nvarchar (24) NULL ,
 CONSTRAINT "PK_Shippers" PRIMARY KEY  CLUSTERED
 (
  "ShipperID"
 )
)
GO
CREATE TABLE "Suppliers" (
 "SupplierID" "int" IDENTITY (1, 1) NOT NULL ,
 "CompanyName" nvarchar (40) NOT NULL ,
 "ContactName" nvarchar (30) NULL ,
 "ContactTitle" nvarchar (30) NULL ,
 "Address" nvarchar (60) NULL ,
 "City" nvarchar (15) NULL ,
 "Region" nvarchar (15) NULL ,
 "PostalCode" nvarchar (10) NULL ,
 "Country" nvarchar (15) NULL ,
 "Phone" nvarchar (24) NULL ,
 "Fax" nvarchar (24) NULL ,
 "HomePage" "ntext" NULL ,
 CONSTRAINT "PK_Suppliers" PRIMARY KEY  CLUSTERED
 (
  "SupplierID"
 )
)
GO
 CREATE  INDEX "CompanyName" ON "dbo"."Suppliers"("CompanyName")
GO
 CREATE  INDEX "PostalCode" ON "dbo"."Suppliers"("PostalCode")
GO

CREATE TABLE "Orders" (
 "OrderID" "int" IDENTITY (1, 1) NOT NULL ,
 "CustomerID" nchar (5) NULL ,
 "EmployeeID" "int" NULL ,
 "OrderDate" "datetime" NULL ,
 "RequiredDate" "datetime" NULL ,
 "ShippedDate" "datetime" NULL ,
 "ShipVia" "int" NULL ,
 "Freight" "money" NULL CONSTRAINT "DF_Orders_Freight" DEFAULT (0),
 "ShipName" nvarchar (40) NULL ,
 "ShipAddress" nvarchar (60) NULL ,
 "ShipCity" nvarchar (15) NULL ,
 "ShipRegion" nvarchar (15) NULL ,
 "ShipPostalCode" nvarchar (10) NULL ,
 "ShipCountry" nvarchar (15) NULL ,
 CONSTRAINT "PK_Orders" PRIMARY KEY  CLUSTERED
 (
  "OrderID"
 ),
 CONSTRAINT "FK_Orders_Customers" FOREIGN KEY
 (
  "CustomerID"
 ) REFERENCES "dbo"."Customers" (
  "CustomerID"
 ),
 CONSTRAINT "FK_Orders_Employees" FOREIGN KEY
 (
  "EmployeeID"
 ) REFERENCES "dbo"."Employees" (
  "EmployeeID"
 ),
 CONSTRAINT "FK_Orders_Shippers" FOREIGN KEY
 (
  "ShipVia"
 ) REFERENCES "dbo"."Shippers" (
  "ShipperID"
 )
)
GO
 CREATE  INDEX "CustomerID" ON "dbo"."Orders"("CustomerID")
GO
 CREATE  INDEX "CustomersOrders" ON "dbo"."Orders"("CustomerID")
GO
 CREATE  INDEX "EmployeeID" ON "dbo"."Orders"("EmployeeID")
GO
 CREATE  INDEX "EmployeesOrders" ON "dbo"."Orders"("EmployeeID")
GO
 CREATE  INDEX "OrderDate" ON "dbo"."Orders"("OrderDate")
GO
 CREATE  INDEX "ShippedDate" ON "dbo"."Orders"("ShippedDate")
GO
 CREATE  INDEX "ShippersOrders" ON "dbo"."Orders"("ShipVia")
GO
 CREATE  INDEX "ShipPostalCode" ON "dbo"."Orders"("ShipPostalCode")
GO

CREATE TABLE "Products" (
 "ProductID" "int" IDENTITY (1, 1) NOT NULL ,
 "ProductName" nvarchar (40) NOT NULL ,
 "SupplierID" "int" NULL ,
 "CategoryID" "int" NULL ,
 "QuantityPerUnit" nvarchar (20) NULL ,
 "UnitPrice" "money" NULL CONSTRAINT "DF_Products_UnitPrice" DEFAULT (0),
 "UnitsInStock" "smallint" NULL CONSTRAINT "DF_Products_UnitsInStock" DEFAULT (0),
 "UnitsOnOrder" "smallint" NULL CONSTRAINT "DF_Products_UnitsOnOrder" DEFAULT (0),
 "ReorderLevel" "smallint" NULL CONSTRAINT "DF_Products_ReorderLevel" DEFAULT (0),
 "Discontinued" "bit" NOT NULL CONSTRAINT "DF_Products_Discontinued" DEFAULT (0),
 CONSTRAINT "PK_Products" PRIMARY KEY  CLUSTERED
 (
  "ProductID"
 ),
 CONSTRAINT "FK_Products_Categories" FOREIGN KEY
 (
  "CategoryID"
 ) REFERENCES "dbo"."Categories" (
  "CategoryID"
 ),
 CONSTRAINT "FK_Products_Suppliers" FOREIGN KEY
 (
  "SupplierID"
 ) REFERENCES "dbo"."Suppliers" (
  "SupplierID"
 ),
 CONSTRAINT "CK_Products_UnitPrice" CHECK (UnitPrice >= 0),
 CONSTRAINT "CK_ReorderLevel" CHECK (ReorderLevel >= 0),
 CONSTRAINT "CK_UnitsInStock" CHECK (UnitsInStock >= 0),
 CONSTRAINT "CK_UnitsOnOrder" CHECK (UnitsOnOrder >= 0)
)
GO
 CREATE  INDEX "CategoriesProducts" ON "dbo"."Products"("CategoryID")
GO
 CREATE  INDEX "CategoryID" ON "dbo"."Products"("CategoryID")
GO
 CREATE  INDEX "ProductName" ON "dbo"."Products"("ProductName")
GO
 CREATE  INDEX "SupplierID" ON "dbo"."Products"("SupplierID")
GO
 CREATE  INDEX "SuppliersProducts" ON "dbo"."Products"("SupplierID")
GO

CREATE TABLE "Order Details" (
 "OrderID" "int" NOT NULL ,
 "ProductID" "int" NOT NULL ,
 "UnitPrice" "money" NOT NULL CONSTRAINT "DF_Order_Details_UnitPrice" DEFAULT (0),
 "Quantity" "smallint" NOT NULL CONSTRAINT "DF_Order_Details_Quantity" DEFAULT (1),
 "Discount" "real" NOT NULL CONSTRAINT "DF_Order_Details_Discount" DEFAULT (0),
 CONSTRAINT "PK_Order_Details" PRIMARY KEY  CLUSTERED
 (
  "OrderID",
  "ProductID"
 ),
 CONSTRAINT "FK_Order_Details_Orders" FOREIGN KEY
 (
  "OrderID"
 ) REFERENCES "dbo"."Orders" (
  "OrderID"
 ),
 CONSTRAINT "FK_Order_Details_Products" FOREIGN KEY
 (
  "ProductID"
 ) REFERENCES "dbo"."Products" (
  "ProductID"
 ),
 CONSTRAINT "CK_Discount" CHECK (Discount >= 0 and (Discount <= 1)),
 CONSTRAINT "CK_Quantity" CHECK (Quantity > 0),
 CONSTRAINT "CK_UnitPrice" CHECK (UnitPrice >= 0)
)
GO
 CREATE  INDEX "OrderID" ON "dbo"."Order Details"("OrderID")
GO
 CREATE  INDEX "OrdersOrder_Details" ON "dbo"."Order Details"("OrderID")
GO
 CREATE  INDEX "ProductID" ON "dbo"."Order Details"("ProductID")
GO
 CREATE  INDEX "ProductsOrder_Details" ON "dbo"."Order Details"("ProductID")
GO

create view "Customer and Suppliers by City" AS
SELECT City, CompanyName, ContactName, 'Customers' AS Relationship
FROM Customers
UNION SELECT City, CompanyName, ContactName, 'Suppliers'
FROM Suppliers
--ORDER BY City, CompanyName
GO

create view "Alphabetical list of products" AS
SELECT Products.*, Categories.CategoryName
FROM Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryID
WHERE (((Products.Discontinued)=0))
GO

create view "Current Product List" AS
SELECT Product_List.ProductID, Product_List.ProductName
FROM Products AS Product_List
WHERE (((Product_List.Discontinued)=0))
--ORDER BY Product_List.ProductName
GO

create view "Orders Qry" AS
SELECT Orders.OrderID, Orders.CustomerID, Orders.EmployeeID, Orders.OrderDate, Orders.RequiredDate,
 Orders.ShippedDate, Orders.ShipVia, Orders.Freight, Orders.ShipName, Orders.ShipAddress, Orders.ShipCity,
 Orders.ShipRegion, Orders.ShipPostalCode, Orders.ShipCountry,
 Customers.CompanyName, Customers.Address, Customers.City, Customers.Region, Customers.PostalCode, Customers.Country
FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID
GO

create view "Products Above Average Price" AS
SELECT Products.ProductName, Products.UnitPrice
FROM Products
WHERE Products.UnitPrice>(SELECT AVG(UnitPrice) From Products)
--ORDER BY Products.UnitPrice DESC
GO

create view "Products by Category" AS
SELECT Categories.CategoryName, Products.ProductName, Products.QuantityPerUnit, Products.UnitsInStock, Products.Discontinued
FROM Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryID
WHERE Products.Discontinued <> 1
--ORDER BY Categories.CategoryName, Products.ProductName
GO

create view "Quarterly Orders" AS
SELECT DISTINCT Customers.CustomerID, Customers.CompanyName, Customers.City, Customers.Country
FROM Customers RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.OrderDate BETWEEN '19970101' And '19971231'
GO

create view Invoices AS
SELECT Orders.ShipName, Orders.ShipAddress, Orders.ShipCity, Orders.ShipRegion, Orders.ShipPostalCode,
 Orders.ShipCountry, Orders.CustomerID, Customers.CompanyName AS CustomerName, Customers.Address, Customers.City,
 Customers.Region, Customers.PostalCode, Customers.Country,
 (FirstName + ' ' + LastName) AS Salesperson,
 Orders.OrderID, Orders.OrderDate, Orders.RequiredDate, Orders.ShippedDate, Shippers.CompanyName As ShipperName,
 "Order Details".ProductID, Products.ProductName, "Order Details".UnitPrice, "Order Details".Quantity,
 "Order Details".Discount,
 (CONVERT(money,("Order Details".UnitPrice*Quantity*(1-Discount)/100))*100) AS ExtendedPrice, Orders.Freight
FROM  Shippers INNER JOIN
  (Products INNER JOIN
   (
    (Employees INNER JOIN
     (Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID)
    ON Employees.EmployeeID = Orders.EmployeeID)
   INNER JOIN "Order Details" ON Orders.OrderID = "Order Details".OrderID)
  ON Products.ProductID = "Order Details".ProductID)
 ON Shippers.ShipperID = Orders.ShipVia
GO

create view "Order Details Extended" AS
SELECT "Order Details".OrderID, "Order Details".ProductID, Products.ProductName,
 "Order Details".UnitPrice, "Order Details".Quantity, "Order Details".Discount,
 (CONVERT(money,("Order Details".UnitPrice*Quantity*(1-Discount)/100))*100) AS ExtendedPrice
FROM Products INNER JOIN "Order Details" ON Products.ProductID = "Order Details".ProductID
--ORDER BY "Order Details".OrderID
GO

create view "Order Subtotals" AS
SELECT "Order Details".OrderID, Sum(CONVERT(money,("Order Details".UnitPrice*Quantity*(1-Discount)/100))*100) AS Subtotal
FROM "Order Details"
GROUP BY "Order Details".OrderID
GO

create view "Product Sales for 1997" AS
SELECT Categories.CategoryName, Products.ProductName,
Sum(CONVERT(money,("Order Details".UnitPrice*Quantity*(1-Discount)/100))*100) AS ProductSales
FROM (Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryID)
 INNER JOIN (Orders
  INNER JOIN "Order Details" ON Orders.OrderID = "Order Details".OrderID)
 ON Products.ProductID = "Order Details".ProductID
WHERE (((Orders.ShippedDate) Between '19970101' And '19971231'))
GROUP BY Categories.CategoryName, Products.ProductName
GO

create view "Category Sales for 1997" AS
SELECT "Product Sales for 1997".CategoryName, Sum("Product Sales for 1997".ProductSales) AS CategorySales
FROM "Product Sales for 1997"
GROUP BY "Product Sales for 1997".CategoryName
GO

create view "Sales by Category" AS
SELECT Categories.CategoryID, Categories.CategoryName, Products.ProductName,
 Sum("Order Details Extended".ExtendedPrice) AS ProductSales
FROM  Categories INNER JOIN
  (Products INNER JOIN
   (Orders INNER JOIN "Order Details Extended" ON Orders.OrderID = "Order Details Extended".OrderID)
  ON Products.ProductID = "Order Details Extended".ProductID)
 ON Categories.CategoryID = Products.CategoryID
WHERE Orders.OrderDate BETWEEN '19970101' And '19971231'
GROUP BY Categories.CategoryID, Categories.CategoryName, Products.ProductName
--ORDER BY Products.ProductName
GO

create view "Sales Totals by Amount" AS
SELECT "Order Subtotals".Subtotal AS SaleAmount, Orders.OrderID, Customers.CompanyName, Orders.ShippedDate
FROM  Customers INNER JOIN
  (Orders INNER JOIN "Order Subtotals" ON Orders.OrderID = "Order Subtotals".OrderID)
 ON Customers.CustomerID = Orders.CustomerID
WHERE ("Order Subtotals".Subtotal >2500) AND (Orders.ShippedDate BETWEEN '19970101' And '19971231')
GO

create view "Summary of Sales by Quarter" AS
SELECT Orders.ShippedDate, Orders.OrderID, "Order Subtotals".Subtotal
FROM Orders INNER JOIN "Order Subtotals" ON Orders.OrderID = "Order Subtotals".OrderID
WHERE Orders.ShippedDate IS NOT NULL
--ORDER BY Orders.ShippedDate
GO

create view "Summary of Sales by Year" AS
SELECT Orders.ShippedDate, Orders.OrderID, "Order Subtotals".Subtotal
FROM Orders INNER JOIN "Order Subtotals" ON Orders.OrderID = "Order Subtotals".OrderID
WHERE Orders.ShippedDate IS NOT NULL
--ORDER BY Orders.ShippedDate
GO

create procedure "Ten Most Expensive Products" AS
SET ROWCOUNT 10
SELECT Products.ProductName AS TenMostExpensiveProducts, Products.UnitPrice
FROM Products
ORDER BY Products.UnitPrice DESC
GO

create procedure "Employee Sales by Country"
@Beginning_Date DateTime, @Ending_Date DateTime AS
SELECT Employees.Country, Employees.LastName, Employees.FirstName, Orders.ShippedDate, Orders.OrderID, "Order Subtotals".Subtotal AS SaleAmount
FROM Employees INNER JOIN
 (Orders INNER JOIN "Order Subtotals" ON Orders.OrderID = "Order Subtotals".OrderID)
 ON Employees.EmployeeID = Orders.EmployeeID
WHERE Orders.ShippedDate Between @Beginning_Date And @Ending_Date
GO

create procedure "Sales by Year"
 @Beginning_Date DateTime, @Ending_Date DateTime AS
SELECT Orders.ShippedDate, Orders.OrderID, "Order Subtotals".Subtotal, DATENAME(yy,ShippedDate) AS Year
FROM Orders INNER JOIN "Order Subtotals" ON Orders.OrderID = "Order Subtotals".OrderID
WHERE Orders.ShippedDate Between @Beginning_Date And @Ending_Date
GO

set quoted_identifier on
go
set identity_insert "Categories" on
go
ALTER TABLE "Categories" NOCHECK CONSTRAINT ALL
go
INSERT "Categories"("CategoryID","CategoryName","Description","Picture") VALUES(1,'Beverages','Soft drinks, coffees, teas, beers, and ales',0x151C2F00020000000D000E0014002100FFFFFFFF4269746D617020496D616765005061696E742E5069637475726500010500000200000007000000504272757368000000000000000000A0290000424D98290000000000005600000028000000AC00000078000000010004000000000000000000880B0000880B00000800000008000000FFFFFF0000FFFF00FF00FF000000FF00FFFF000000FF0000FF000000000000000000100000000010000000010010000000000000010101000100001001000000010100010000001001000001000000101010001000001000100000000000000000000010000000010000000000000010000000000000000000000010010010000000000000000000010010010000125070701000000010000000010001001000000100000010000000001001001000000010010101010100000000000000000000010010001000001010101010000000000000000000000000000000000001010205253637777777777777535301001010001000000000010100010010001001001000000000001000000000000000001000100010010100010000000100100000000000001000000000000000000000000000000010143435777777777777777777777777777701001200010101001020000000000000000000000001001000100100000000001000100000000000000000100100000010010010101000000000000000000000000000000010216177777777757575353535257777777777777701501200001000101010000000000000000010000000000000010010010000000000100100000100100100001010010010000001000000010000000000000000000000014177777376173763777757677717077527777777763401612103000000000100000000000100000000000000000000000000000000000000001000000000001000000000000100001000000000000000000000000001005036775775717050140000001010707177757777777753341014000101010100010100101010000000000000000000000000000010000000000000000000000000000000010100010000010000000000000000000000000103573530000000000000000000000000001717777777774706121010000000010000010000000100000000000000000000000000000001000107030101012100000000000000000000000000000000000000000000001010343500000000106534357775704774747000001077577771710000001010010001010001010100001000000000000000000010414771101310357500200404773010001000000000000000000000000000000000000000000100040141765777070000677777777765604040073717343617014000012410000010000000010000204000002000001017477677770001010737775777777753721000000001000000000000001001000000000100000100000376764767000040005774704167174774214050004341403430005651205101003010140021071713707014377777777757777771121031777777777777057577710100000001000000000000000100001000001010004704404406710074777767777776140606007425240017777777476467767520602500030217167377777777777777747477275747770010167777777777671733177030001010100000000100000000010000000000004204602000774274777677777777756777777464746566067677776657467767571512535071667377777337467775777777775727767711005177777777677760157131410300200010000000010010000000000101000674400440477614777677767067677776747656734706575057673756647467577772712521677177337717377767776775674765775771211037757777777767170277531210101010000100000000001000010100000107670600047767477767767777567767777777770424776760677774674747476767775652565313117711773764777775767577777477101107017777777677774017173400000000001000010000000000010000001010047765406660507776776577776774707747777767476646077773767474767777776777171737353777177377477777777777747747700112710777777677777631717352101210101000000000000000000000100000003004067677576767750770067674777747747777747477704767776567067467776577777777777777777777376677774765747747777710010317777777767677413717710000000000100000000000000000000001010057074425676561760067670047704767077007677700004777477346564467456776767777777777777777773756677777777777777777731000107777777777777717535210101010100000000001000100000000100077777121525030046700777747674270472477765775647000767377476704742777777777777777773677777777657777777777774347777507577753777676767701727731000000000010000000000000010001010071707016142040460077460406761674707741677436567777400777760674074656776777777777777577177777374767757161612434103030777777775777752100000113500010010010000001010001000001000021001715256750700743406700050040767007065707577777677700777447464665677776777777777777777777737767776100000001377753503177777737777377507010001010210010001000000000000101000100103000677777616506040650476047607464047764067056567767700777647504747476777777777777777777737337477777730117357777777777777777577777777777674120410010010000010000010000000100010005777441400006074067067676767767777764777567677774477007740766467647775677777777777777373737377646777477535277777767777777777763657353535130103001203010100000000000000000010001070002100061477676746460404040400666677676777754767770466446440444567767677777777777337373737767777767742447773777177127771653575775342420400100100100000100010000001000100001003000500001466640000001010307343521011000656777670777700476047743776767777677777777773737373337564776570753771007707701777765252716730010121012103010010300000001001000000010000050000600461600040001253435101101010000000000077400000477447337373777576777777777773737373777376567577777773731016767707777177756717730010103000000210210100000000000001000000001000774000004140214140000000000000000000000000003000007777777737373776776777777777773737373337356776777773777101777777177747052717673403000000101010001000001000001001000000010140056600000007375606000000000000000000000000000047307777737333737377777476777777777373373537616667777777377370177716770773537775747353100121010000000100101000001000000000100043000654000000004001412541404040000000000000000000377377767737773737337776777777777776776467465657567477777737730170177107656543527357700170103030310100100000001000010010100307040006600000000000000400000000000000000000000000077775146733733737377777774767777777774746447646667767777777727110310761173073743574773730103410500430300121001000101001000125000000470000000000467420000000000000000000000000777766777773773773737337377677777777777676456765075747776576100571211017316115747776377351052701252130100502101000010702103016500000006400000000067764067764640000406414341777777676676147373373373737777777676777777765647674746646674777617752711121161010023312111010527210161201401610341060101730756177700005700474000474004460000004677705047777671735737567677767677377377737373777767777777777765647467654775767771767007746564747310100110000012501652147161701210120110707771737774000637700400007604676000000007407606007770677777776767676767673373333737373777476777777777767677474246767476771577016776776761313312131313013713173103121615250530730777777777000475777000000060067600006404000064740467407777777776767676767377377773737777777677777777776747467674674777777436701753053253525271353353531701434143716171301312117771777777770017377700067604766770470644664000476400777477777777676767676737733733337373737767467777777654676747047476747653756107317735737525347374170170353031301010100300014277777777377700477777700474607046440644000046400670047670777777777676767676733773777737377777767777777777665656656707677677750770075631533473707310132136170343434343070314171211777737777777402577377000274470000640000000006400640067607777777767677677677733733333737377774767777777777467656744647477677634770271727537171757777577573571717171717174336161637777777357374007377734004606600460000000000040006006767477777777767667667673