AdventureWorks

AdventureWorks Sample OLTP Database30/03/2009
178.75 MB

Summary

Tables

Table: dbo.AWBuildVersion

Current version number of the AdventureWorks sample database.

Fields

Field name Data type Nullable Default value Field description
SystemInformationIDtinyintPrimary key for AWBuildVersion records.
Database Versionnvarchar (25) Version number of the database in 9.yy.mm.dd.00 format.
VersionDatedatetimeDate and time the record was last updated.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_AWBuildVersion_SystemInformationIDSystemInformationIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[AWBuildVersion](
    [SystemInformationID] [tinyint] IDENTITY(1,1) NOT NULL,
    [Database Version] [nvarchar](25) COLLATE Latin1_General_CS_AS NOT NULL,
    [VersionDate] [datetime] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: dbo.DatabaseLog

Audit table tracking all DDL changes made to the AdventureWorks database. Data is captured by the database trigger ddlDatabaseTriggerLog.

Fields

Field name Data type Nullable Default value Field description
DatabaseLogIDintPrimary key for DatabaseLog records.
PostTimedatetimeThe date and time the DDL change occurred.
DatabaseUsernvarchar (128) The user who implemented the DDL change.
Eventnvarchar (128) The type of DDL statement that was executed.
Schemanvarchar (128) YesThe schema to which the changed object belongs.
Objectnvarchar (128) YesThe object that was changed by the DDL statment.
TSQLnvarcharThe exact Transact-SQL statement that was executed.
XmlEventxmlThe raw XML data generated by database trigger.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_DatabaseLog_DatabaseLogIDDatabaseLogIDASCYesNONCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[DatabaseLog](
    [DatabaseLogID] [int] IDENTITY(1,1) NOT NULL,
    [PostTime] [datetime] NOT NULL,
    [DatabaseUser] [sysname] COLLATE Latin1_General_CS_AS NOT NULL,
    [Event] [sysname] COLLATE Latin1_General_CS_AS NOT NULL,
    [Schema] [sysname] COLLATE Latin1_General_CS_AS NULL,
    [Object] [sysname] COLLATE Latin1_General_CS_AS NULL,
    [TSQL] [nvarchar](max) COLLATE Latin1_General_CS_AS NOT NULL,
    [XmlEvent] [xml] NOT NULL
) ON [PRIMARY]

Table: dbo.ErrorLog

Audit table tracking errors in the the AdventureWorks database that are caught by the CATCH block of a TRY...CATCH construct. Data is inserted by stored procedure dbo.uspLogError when it is executed from inside the CATCH block of a TRY...CATCH construct.

Fields

Field name Data type Nullable Default value Field description
ErrorLogIDintPrimary key for ErrorLog records.
ErrorTimedatetime(getdate())The date and time at which the error occurred.
UserNamenvarchar (128) The user who executed the batch in which the error occurred.
ErrorNumberintThe error number of the error that occurred.
ErrorSeverityintYesThe severity of the error that occurred.
ErrorStateintYesThe state number of the error that occurred.
ErrorProcedurenvarchar (126) YesThe name of the stored procedure or trigger where the error occurred.
ErrorLineintYesThe line number at which the error occurred.
ErrorMessagenvarchar (4000) The message text of the error that occurred.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_ErrorLog_ErrorLogIDErrorLogIDASCYesCLUSTERED

Objects that depend on dbo.ErrorLog

stored proceduredbo.uspLogError

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[ErrorLog](
    [ErrorLogID] [int] IDENTITY(1,1) NOT NULL,
    [ErrorTime] [datetime] NOT NULL,
    [UserName] [sysname] COLLATE Latin1_General_CS_AS NOT NULL,
    [ErrorNumber] [int] NOT NULL,
    [ErrorSeverity] [int] NULL,
    [ErrorState] [int] NULL,
    [ErrorProcedure] [nvarchar](126) COLLATE Latin1_General_CS_AS NULL,
    [ErrorLine] [int] NULL,
    [ErrorMessage] [nvarchar](4000) COLLATE Latin1_General_CS_AS NOT NULL
) ON [PRIMARY]

Table: HumanResources.Department

Lookup table containing the departments within the Adventure Works Cycles company.

Fields

Field name Data type Nullable Default value Field description
DepartmentIDsmallintPrimary key for Department records.
NameNameName of the department.
GroupNameNameName of the group to which the department belongs.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
HumanResources.EmployeeDepartmentHistoryFK_EmployeeDepartmentHistory_Department_DepartmentIDPK_Department_DepartmentID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Department_NameNameASCYesNONCLUSTERED
PK_Department_DepartmentIDDepartmentIDASCYesCLUSTERED

Objects that depend on HumanResources.Department

viewHumanResources.vEmployeeDepartment
viewHumanResources.vEmployeeDepartmentHistory

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [HumanResources].[Department](
    [DepartmentID] [smallint] IDENTITY(1,1) NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [GroupName] [dbo].[Name] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: HumanResources.Employee

Employee information such as salary, department, and title.

Fields

Field name Data type Nullable Default value Field description
EmployeeIDintPrimary key for Employee records.
NationalIDNumbernvarchar (15) Unique national identification number such as a social security number.
ContactIDintIdentifies the employee in the Contact table. Foreign key to Contact.ContactID.
LoginIDnvarchar (256) Network login.
ManagerIDintYesManager to whom the employee is assigned. Foreign Key to Employee.M
Titlenvarchar (50) Work title such as Buyer or Sales Representative.
BirthDatedatetimeDate of birth.
MaritalStatusnchar (1) M = Married, S = Single
Gendernchar (1) M = Male, F = Female
HireDatedatetimeEmployee hired on this date.
SalariedFlagFlag((1))Job classification. 0 = Hourly, not exempt from collective bargaining. 1 = Salaried, exempt from collective bargaining.
VacationHourssmallint((0))Number of available vacation hours.
SickLeaveHourssmallint((0))Number of available sick leave hours.
CurrentFlagFlag((1))0 = Inactive, 1 = Active
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_Employee_Contact_ContactIDContactIDPK_Contact_ContactID (Person.Contact) Foreign key constraint referencing Contact.ContactID.
FK_Employee_Employee_ManagerIDManagerIDPK_Employee_EmployeeID (HumanResources.Employee) Foreign key constraint referencing Employee.ManagerID.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
HumanResources.JobCandidateFK_JobCandidate_Employee_EmployeeIDPK_Employee_EmployeeID
Purchasing.PurchaseOrderHeaderFK_PurchaseOrderHeader_Employee_EmployeeIDPK_Employee_EmployeeID
Sales.SalesPersonFK_SalesPerson_Employee_SalesPersonIDPK_Employee_EmployeeID
HumanResources.EmployeeFK_Employee_Employee_ManagerIDPK_Employee_EmployeeID
HumanResources.EmployeeDepartmentHistoryFK_EmployeeDepartmentHistory_Employee_EmployeeIDPK_Employee_EmployeeID
HumanResources.EmployeeAddressFK_EmployeeAddress_Employee_EmployeeIDPK_Employee_EmployeeID
HumanResources.EmployeePayHistoryFK_EmployeePayHistory_Employee_EmployeeIDPK_Employee_EmployeeID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Employee_LoginIDLoginIDASCYesNONCLUSTERED
AK_Employee_NationalIDNumberNationalIDNumberASCYesNONCLUSTERED
AK_Employee_rowguidrowguidASCYesNONCLUSTERED
IX_Employee_ManagerIDManagerIDASCNONCLUSTERED
PK_Employee_EmployeeIDEmployeeIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_Employee_BirthDateBirthDate([BirthDate]>='1930-01-01' AND [BirthDate]<=dateadd(year,(-18),getdate()))
CK_Employee_MaritalStatusMaritalStatus(upper([MaritalStatus])='S' OR upper([MaritalStatus])='M')
CK_Employee_HireDateHireDate([HireDate]>='1996-07-01' AND [HireDate]<=dateadd(day,(1),getdate()))
CK_Employee_GenderGender(upper([Gender])='F' OR upper([Gender])='M')
CK_Employee_VacationHoursVacationHours([VacationHours]>=(-40) AND [VacationHours]<=(240))
CK_Employee_SickLeaveHoursSickLeaveHours([SickLeaveHours]>=(0) AND [SickLeaveHours]<=(120))

Triggers

Trigger name:HumanResources.dEmployee
Description:INSTEAD OF DELETE trigger which keeps Employees from being deleted.
Creation date:26 Apr 2006
Trigger type:INSTEAD OF DELETE
Trigger active:Yes
Trigger definition

CREATE TRIGGER [HumanResources].[dEmployee] ON [HumanResources].[Employee] 
INSTEAD OF DELETE NOT FOR REPLICATION AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN
        RAISERROR
            (N'Employees cannot be deleted. They can only be marked as not current.', -- Message
            10, -- Severity.
            1); -- State.

        -- Rollback any active or uncommittable transactions
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END
    END;
END;

Objects that depend on HumanResources.Employee

stored proceduredbo.uspGetEmployeeManagers
stored proceduredbo.uspGetManagerEmployees
stored procedureHumanResources.uspUpdateEmployeeHireInfo
stored procedureHumanResources.uspUpdateEmployeeLogin
stored procedureHumanResources.uspUpdateEmployeePersonalInfo
viewHumanResources.vEmployee
viewHumanResources.vEmployeeDepartment
viewHumanResources.vEmployeeDepartmentHistory
viewSales.vSalesPerson
viewSales.vSalesPersonSalesByFiscalYears

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [HumanResources].[Employee](
    [EmployeeID] [int] IDENTITY(1,1) NOT NULL,
    [NationalIDNumber] [nvarchar](15) COLLATE Latin1_General_CS_AS NOT NULL,
    [ContactID] [int] NOT NULL,
    [LoginID] [nvarchar](256) COLLATE Latin1_General_CS_AS NOT NULL,
    [ManagerID] [int] NULL,
    [Title] [nvarchar](50) COLLATE Latin1_General_CS_AS NOT NULL,
    [BirthDate] [datetime] NOT NULL,
    [MaritalStatus] [nchar](1) COLLATE Latin1_General_CS_AS NOT NULL,
    [Gender] [nchar](1) COLLATE Latin1_General_CS_AS NOT NULL,
    [HireDate] [datetime] NOT NULL,
    [SalariedFlag] [dbo].[Flag] NOT NULL,
    [VacationHours] [smallint] NOT NULL,
    [SickLeaveHours] [smallint] NOT NULL,
    [CurrentFlag] [dbo].[Flag] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: HumanResources.EmployeeAddress

Cross-reference table mapping employees to their address(es).

Fields

Field name Data type Nullable Default value Field description
EmployeeIDintPrimary key. Foreign key to Employee.EmployeeID.
AddressIDintPrimary key. Foreign key to Address.AddressID.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_EmployeeAddress_Employee_EmployeeIDEmployeeIDPK_Employee_EmployeeID (HumanResources.Employee) Foreign key constraint referencing Employee.EmployeeID.
FK_EmployeeAddress_Address_AddressIDAddressIDPK_Address_AddressID (Person.Address) Foreign key constraint referencing Address.AddressID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_EmployeeAddress_rowguidrowguidASCYesNONCLUSTERED
PK_EmployeeAddress_EmployeeID_AddressIDEmployeeIDASCYesCLUSTERED
PK_EmployeeAddress_EmployeeID_AddressIDAddressIDASCYesCLUSTERED

Objects that depend on HumanResources.EmployeeAddress

viewHumanResources.vEmployee
viewSales.vSalesPerson

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [HumanResources].[EmployeeAddress](
    [EmployeeID] [int] NOT NULL,
    [AddressID] [int] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: HumanResources.EmployeeDepartmentHistory

Employee department transfers.

Fields

Field name Data type Nullable Default value Field description
EmployeeIDintEmployee identification number. Foreign key to Employee.EmployeeID.
DepartmentIDsmallintDepartment in which the employee worked including currently. Foreign key to Department.DepartmentID.
ShiftIDtinyintIdentifies which 8-hour shift the employee works. Foreign key to Shift.Shift.ID.
StartDatedatetimeDate the employee started work in the department.
EndDatedatetimeYesDate the employee left the department. NULL = Current department.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_EmployeeDepartmentHistory_Employee_EmployeeIDEmployeeIDPK_Employee_EmployeeID (HumanResources.Employee) Foreign key constraint referencing Employee.EmployeeID.
FK_EmployeeDepartmentHistory_Department_DepartmentIDDepartmentIDPK_Department_DepartmentID (HumanResources.Department) Foreign key constraint referencing Department.DepartmentID.
FK_EmployeeDepartmentHistory_Shift_ShiftIDShiftIDPK_Shift_ShiftID (HumanResources.Shift) Foreign key constraint referencing Shift.ShiftID

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_EmployeeDepartmentHistory_DepartmentIDDepartmentIDASCNONCLUSTERED
IX_EmployeeDepartmentHistory_ShiftIDShiftIDASCNONCLUSTERED
PK_EmployeeDepartmentHistory_EmployeeID_StartDate_DepartmentIDEmployeeIDASCYesCLUSTERED
PK_EmployeeDepartmentHistory_EmployeeID_StartDate_DepartmentIDDepartmentIDASCYesCLUSTERED
PK_EmployeeDepartmentHistory_EmployeeID_StartDate_DepartmentIDShiftIDASCYesCLUSTERED
PK_EmployeeDepartmentHistory_EmployeeID_StartDate_DepartmentIDStartDateASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_EmployeeDepartmentHistory_EndDateStartDate([EndDate]>=[StartDate] OR [EndDate] IS NULL)
CK_EmployeeDepartmentHistory_EndDateEndDate([EndDate]>=[StartDate] OR [EndDate] IS NULL)

Objects that depend on HumanResources.EmployeeDepartmentHistory

viewHumanResources.vEmployeeDepartment
viewHumanResources.vEmployeeDepartmentHistory

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [HumanResources].[EmployeeDepartmentHistory](
    [EmployeeID] [int] NOT NULL,
    [DepartmentID] [smallint] NOT NULL,
    [ShiftID] [tinyint] NOT NULL,
    [StartDate] [datetime] NOT NULL,
    [EndDate] [datetime] NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: HumanResources.EmployeePayHistory

Employee pay history.

Fields

Field name Data type Nullable Default value Field description
EmployeeIDintEmployee identification number. Foreign key to Employee.EmployeeID.
RateChangeDatedatetimeDate the change in pay is effective
RatemoneySalary hourly rate.
PayFrequencytinyint1 = Salary received monthly, 2 = Salary received biweekly
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_EmployeePayHistory_Employee_EmployeeIDEmployeeIDPK_Employee_EmployeeID (HumanResources.Employee) Foreign key constraint referencing Employee.EmployeeID.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_EmployeePayHistory_EmployeeID_RateChangeDateEmployeeIDASCYesCLUSTERED
PK_EmployeePayHistory_EmployeeID_RateChangeDateRateChangeDateASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_EmployeePayHistory_PayFrequencyPayFrequency([PayFrequency]=(2) OR [PayFrequency]=(1))
CK_EmployeePayHistory_RateRate([Rate]>=(6.50) AND [Rate]<=(200.00))

Objects that depend on HumanResources.EmployeePayHistory

stored procedureHumanResources.uspUpdateEmployeeHireInfo

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [HumanResources].[EmployeePayHistory](
    [EmployeeID] [int] NOT NULL,
    [RateChangeDate] [datetime] NOT NULL,
    [Rate] [money] NOT NULL,
    [PayFrequency] [tinyint] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: HumanResources.JobCandidate

Résumés submitted to Human Resources by job applicants.

Fields

Field name Data type Nullable Default value Field description
JobCandidateIDintPrimary key for JobCandidate records.
EmployeeIDintYesEmployee identification number if applicant was hired. Foreign key to Employee.EmployeeID.
ResumexmlYesRésumé in XML format.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_JobCandidate_Employee_EmployeeIDEmployeeIDPK_Employee_EmployeeID (HumanResources.Employee) Foreign key constraint referencing Employee.EmployeeID.

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_JobCandidate_EmployeeIDEmployeeIDASCNONCLUSTERED
PK_JobCandidate_JobCandidateIDJobCandidateIDASCYesCLUSTERED

Objects that depend on HumanResources.JobCandidate

viewHumanResources.vJobCandidate
viewHumanResources.vJobCandidateEducation
viewHumanResources.vJobCandidateEmployment

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [HumanResources].[JobCandidate](
    [JobCandidateID] [int] IDENTITY(1,1) NOT NULL,
    [EmployeeID] [int] NULL,
    [Resume] [xml](CONTENT [HumanResources].[HRResumeSchemaCollection]) NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: HumanResources.Shift

Work shift lookup table.

Fields

Field name Data type Nullable Default value Field description
ShiftIDtinyintPrimary key for Shift records.
NameNameShift description.
StartTimedatetimeShift start time.
EndTimedatetimeShift end time.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
HumanResources.EmployeeDepartmentHistoryFK_EmployeeDepartmentHistory_Shift_ShiftIDPK_Shift_ShiftID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Shift_NameNameASCYesNONCLUSTERED
AK_Shift_StartTime_EndTimeStartTimeASCYesNONCLUSTERED
AK_Shift_StartTime_EndTimeEndTimeASCYesNONCLUSTERED
PK_Shift_ShiftIDShiftIDASCYesCLUSTERED

Objects that depend on HumanResources.Shift

viewHumanResources.vEmployeeDepartmentHistory

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [HumanResources].[Shift](
    [ShiftID] [tinyint] IDENTITY(1,1) NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [StartTime] [datetime] NOT NULL,
    [EndTime] [datetime] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Person.Address

Street address information for customers, employees, and vendors.

Fields

Field name Data type Nullable Default value Field description
AddressIDintPrimary key for Address records.
AddressLine1nvarchar (60) First street address line.
AddressLine2nvarchar (60) YesSecond street address line.
Citynvarchar (30) Name of the city.
StateProvinceIDintUnique identification number for the state or province. Foreign key to StateProvince table.
PostalCodenvarchar (15) Postal code for the street address.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_Address_StateProvince_StateProvinceIDStateProvinceIDPK_StateProvince_StateProvinceID (Person.StateProvince) Foreign key constraint referencing StateProvince.StateProvinceID.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.SalesOrderHeaderFK_SalesOrderHeader_Address_BillToAddressIDPK_Address_AddressID
Purchasing.VendorAddressFK_VendorAddress_Address_AddressIDPK_Address_AddressID
Sales.CustomerAddressFK_CustomerAddress_Address_AddressIDPK_Address_AddressID
HumanResources.EmployeeAddressFK_EmployeeAddress_Address_AddressIDPK_Address_AddressID
Sales.SalesOrderHeaderFK_SalesOrderHeader_Address_ShipToAddressIDPK_Address_AddressID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Address_rowguidrowguidASCYesNONCLUSTERED
IX_Address_AddressLine1_AddressLine2_City_StateProvinceID_PostalCodeAddressLine1ASCYesNONCLUSTERED
IX_Address_AddressLine1_AddressLine2_City_StateProvinceID_PostalCodeAddressLine2ASCYesNONCLUSTERED
IX_Address_AddressLine1_AddressLine2_City_StateProvinceID_PostalCodeCityASCYesNONCLUSTERED
IX_Address_AddressLine1_AddressLine2_City_StateProvinceID_PostalCodeStateProvinceIDASCYesNONCLUSTERED
IX_Address_AddressLine1_AddressLine2_City_StateProvinceID_PostalCodePostalCodeASCYesNONCLUSTERED
IX_Address_StateProvinceIDStateProvinceIDASCNONCLUSTERED
PK_Address_AddressIDAddressIDASCYesCLUSTERED

Objects that depend on Person.Address

viewHumanResources.vEmployee
viewPurchasing.vVendor
viewSales.vIndividualCustomer
viewSales.vSalesPerson
viewSales.vStoreWithDemographics

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Person].[Address](
    [AddressID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    [AddressLine1] [nvarchar](60) COLLATE Latin1_General_CS_AS NOT NULL,
    [AddressLine2] [nvarchar](60) COLLATE Latin1_General_CS_AS NULL,
    [City] [nvarchar](30) COLLATE Latin1_General_CS_AS NOT NULL,
    [StateProvinceID] [int] NOT NULL,
    [PostalCode] [nvarchar](15) COLLATE Latin1_General_CS_AS NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Person.AddressType

Types of addresses stored in the Address table.

Fields

Field name Data type Nullable Default value Field description
AddressTypeIDintPrimary key for AddressType records.
NameNameAddress type description. For example, Billing, Home, or Shipping.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.CustomerAddressFK_CustomerAddress_AddressType_AddressTypeIDPK_AddressType_AddressTypeID
Purchasing.VendorAddressFK_VendorAddress_AddressType_AddressTypeIDPK_AddressType_AddressTypeID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_AddressType_NameNameASCYesNONCLUSTERED
AK_AddressType_rowguidrowguidASCYesNONCLUSTERED
PK_AddressType_AddressTypeIDAddressTypeIDASCYesCLUSTERED

Objects that depend on Person.AddressType

viewSales.vIndividualCustomer
viewSales.vStoreWithDemographics

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Person].[AddressType](
    [AddressTypeID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Person.Contact

Names of each employee, customer contact, and vendor contact.

Fields

Field name Data type Nullable Default value Field description
ContactIDintPrimary key for Contact records.
NameStyleNameStyle((0))0 = The data in FirstName and LastName are stored in western style (first name, last name) order. 1 = Eastern style (last name, first name) order.
Titlenvarchar (8) YesA courtesy title. For example, Mr. or Ms.
FirstNameNameFirst name of the person.
MiddleNameNameYesMiddle name or middle initial of the person.
LastNameNameLast name of the person.
Suffixnvarchar (10) YesSurname suffix. For example, Sr. or Jr.
EmailAddressnvarchar (50) YesE-mail address for the person.
EmailPromotionint((0))0 = Contact does not wish to receive e-mail promotions, 1 = Contact does wish to receive e-mail promotions from AdventureWorks, 2 = Contact does wish to receive e-mail promotions from AdventureWorks and selected partners.
PhonePhoneYesPhone number associated with the person.
PasswordHashvarchar (128) Password for the e-mail account.
PasswordSaltvarchar (10) Random value concatenated with the password string before the password is hashed.
AdditionalContactInfoxmlYesAdditional contact information about the person stored in xml format.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.SalesOrderHeaderFK_SalesOrderHeader_Contact_ContactIDPK_Contact_ContactID
Sales.StoreContactFK_StoreContact_Contact_ContactIDPK_Contact_ContactID
Purchasing.VendorContactFK_VendorContact_Contact_ContactIDPK_Contact_ContactID
Sales.ContactCreditCardFK_ContactCreditCard_Contact_ContactIDPK_Contact_ContactID
HumanResources.EmployeeFK_Employee_Contact_ContactIDPK_Contact_ContactID
Sales.IndividualFK_Individual_Contact_ContactIDPK_Contact_ContactID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Contact_rowguidrowguidASCYesNONCLUSTERED
IX_Contact_EmailAddressEmailAddressASCNONCLUSTERED
PK_Contact_ContactIDContactIDASCYesCLUSTERED
PXML_Contact_AddContactAdditionalContactInfoASCXML

Check constraints

Check nameColumn nameCheck expresion
CK_Contact_EmailPromotionEmailPromotion([EmailPromotion]>=(0) AND [EmailPromotion]<=(2))

Objects that depend on Person.Contact

stored proceduredbo.uspGetEmployeeManagers
stored proceduredbo.uspGetManagerEmployees
viewHumanResources.vEmployee
viewHumanResources.vEmployeeDepartment
viewHumanResources.vEmployeeDepartmentHistory
viewPerson.vAdditionalContactInfo
viewPurchasing.vVendor
viewSales.vIndividualCustomer
viewSales.vSalesPerson
viewSales.vSalesPersonSalesByFiscalYears
viewSales.vStoreWithDemographics

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Person].[Contact](
    [ContactID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    [NameStyle] [dbo].[NameStyle] NOT NULL,
    [Title] [nvarchar](8) COLLATE Latin1_General_CS_AS NULL,
    [FirstName] [dbo].[Name] NOT NULL,
    [MiddleName] [dbo].[Name] NULL,
    [LastName] [dbo].[Name] NOT NULL,
    [Suffix] [nvarchar](10) COLLATE Latin1_General_CS_AS NULL,
    [EmailAddress] [nvarchar](50) COLLATE Latin1_General_CS_AS NULL,
    [EmailPromotion] [int] NOT NULL,
    [Phone] [dbo].[Phone] NULL,
    [PasswordHash] [varchar](128) COLLATE Latin1_General_CS_AS NOT NULL,
    [PasswordSalt] [varchar](10) COLLATE Latin1_General_CS_AS NOT NULL,
    [AdditionalContactInfo] [xml](CONTENT [Person].[AdditionalContactInfoSchemaCollection]) NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Person.ContactType

Lookup table containing the types of contacts stored in Contact.

Fields

Field name Data type Nullable Default value Field description
ContactTypeIDintPrimary key for ContactType records.
NameNameContact type description.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Purchasing.VendorContactFK_VendorContact_ContactType_ContactTypeIDPK_ContactType_ContactTypeID
Sales.StoreContactFK_StoreContact_ContactType_ContactTypeIDPK_ContactType_ContactTypeID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_ContactType_NameNameASCYesNONCLUSTERED
PK_ContactType_ContactTypeIDContactTypeIDASCYesCLUSTERED

Objects that depend on Person.ContactType

viewPurchasing.vVendor
viewSales.vStoreWithDemographics

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Person].[ContactType](
    [ContactTypeID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Person.CountryRegion

Lookup table containing the ISO standard codes for countries and regions.

Fields

Field name Data type Nullable Default value Field description
CountryRegionCodenvarchar (3) ISO standard code for countries and regions.
NameNameCountry or region name.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Person.StateProvinceFK_StateProvince_CountryRegion_CountryRegionCodePK_CountryRegion_CountryRegionCode
Sales.CountryRegionCurrencyFK_CountryRegionCurrency_CountryRegion_CountryRegionCodePK_CountryRegion_CountryRegionCode

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_CountryRegion_NameNameASCYesNONCLUSTERED
PK_CountryRegion_CountryRegionCodeCountryRegionCodeASCYesCLUSTERED

Objects that depend on Person.CountryRegion

viewHumanResources.vEmployee
viewPerson.vStateProvinceCountryRegion
viewPurchasing.vVendor
viewSales.vIndividualCustomer
viewSales.vSalesPerson
viewSales.vStoreWithDemographics

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Person].[CountryRegion](
    [CountryRegionCode] [nvarchar](3) COLLATE Latin1_General_CS_AS NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Person.StateProvince

State and province lookup table.

Fields

Field name Data type Nullable Default value Field description
StateProvinceIDintPrimary key for StateProvince records.
StateProvinceCodenchar (3) ISO standard state or province code.
CountryRegionCodenvarchar (3) ISO standard country or region code. Foreign key to CountryRegion.CountryRegionCode.
IsOnlyStateProvinceFlagFlag((1))0 = StateProvinceCode exists. 1 = StateProvinceCode unavailable, using CountryRegionCode.
NameNameState or province description.
TerritoryIDintID of the territory in which the state or province is located. Foreign key to SalesTerritory.SalesTerritoryID.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_StateProvince_CountryRegion_CountryRegionCodeCountryRegionCodePK_CountryRegion_CountryRegionCode (Person.CountryRegion) Foreign key constraint referencing CountryRegion.CountryRegionCode.
FK_StateProvince_SalesTerritory_TerritoryIDTerritoryIDPK_SalesTerritory_TerritoryID (Sales.SalesTerritory) Foreign key constraint referencing SalesTerritory.TerritoryID.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.SalesTaxRateFK_SalesTaxRate_StateProvince_StateProvinceIDPK_StateProvince_StateProvinceID
Person.AddressFK_Address_StateProvince_StateProvinceIDPK_StateProvince_StateProvinceID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_StateProvince_NameNameASCYesNONCLUSTERED
AK_StateProvince_rowguidrowguidASCYesNONCLUSTERED
AK_StateProvince_StateProvinceCode_CountryRegionCodeStateProvinceCodeASCYesNONCLUSTERED
AK_StateProvince_StateProvinceCode_CountryRegionCodeCountryRegionCodeASCYesNONCLUSTERED
PK_StateProvince_StateProvinceIDStateProvinceIDASCYesCLUSTERED

Objects that depend on Person.StateProvince

viewHumanResources.vEmployee
viewPerson.vStateProvinceCountryRegion
viewPurchasing.vVendor
viewSales.vIndividualCustomer
viewSales.vSalesPerson
viewSales.vStoreWithDemographics

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Person].[StateProvince](
    [StateProvinceID] [int] IDENTITY(1,1) NOT NULL,
    [StateProvinceCode] [nchar](3) COLLATE Latin1_General_CS_AS NOT NULL,
    [CountryRegionCode] [nvarchar](3) COLLATE Latin1_General_CS_AS NOT NULL,
    [IsOnlyStateProvinceFlag] [dbo].[Flag] NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [TerritoryID] [int] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.BillOfMaterials

Items required to make bicycles and bicycle subassemblies. It identifies the heirarchical relationship between a parent product and its components.

Fields

Field name Data type Nullable Default value Field description
BillOfMaterialsIDintPrimary key for BillOfMaterials records.
ProductAssemblyIDintYesParent product identification number. Foreign key to Product.ProductID.
ComponentIDintComponent identification number. Foreign key to Product.ProductID.
StartDatedatetime(getdate())Date the component started being used in the assembly item.
EndDatedatetimeYesDate the component stopped being used in the assembly item.
UnitMeasureCodenchar (3) Standard code identifying the unit of measure for the quantity.
BOMLevelsmallintIndicates the depth the component is from its parent (AssemblyID).
PerAssemblyQtydecimal (8.2) ((1.00))Quantity of the component needed to create the assembly.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_BillOfMaterials_Product_ProductAssemblyIDProductAssemblyIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductAssemblyID.
FK_BillOfMaterials_Product_ComponentIDComponentIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ComponentID.
FK_BillOfMaterials_UnitMeasure_UnitMeasureCodeUnitMeasureCodePK_UnitMeasure_UnitMeasureCode (Production.UnitMeasure) Foreign key constraint referencing UnitMeasure.UnitMeasureCode.

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_BillOfMaterials_ProductAssemblyID_ComponentID_StartDateProductAssemblyIDASCYesCLUSTERED
AK_BillOfMaterials_ProductAssemblyID_ComponentID_StartDateComponentIDASCYesCLUSTERED
AK_BillOfMaterials_ProductAssemblyID_ComponentID_StartDateStartDateASCYesCLUSTERED
IX_BillOfMaterials_UnitMeasureCodeUnitMeasureCodeASCNONCLUSTERED
PK_BillOfMaterials_BillOfMaterialsIDBillOfMaterialsIDASCYesNONCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_BillOfMaterials_EndDateStartDate([EndDate]>[StartDate] OR [EndDate] IS NULL)
CK_BillOfMaterials_EndDateEndDate([EndDate]>[StartDate] OR [EndDate] IS NULL)
CK_BillOfMaterials_ProductAssemblyIDProductAssemblyID([ProductAssemblyID]<>[ComponentID])
CK_BillOfMaterials_ProductAssemblyIDComponentID([ProductAssemblyID]<>[ComponentID])
CK_BillOfMaterials_BOMLevelProductAssemblyID([ProductAssemblyID] IS NULL AND [BOMLevel]=(0) AND [PerAssemblyQty]=(1.00) OR [ProductAssemblyID] IS NOT NULL AND [BOMLevel]>=(1))
CK_BillOfMaterials_BOMLevelBOMLevel([ProductAssemblyID] IS NULL AND [BOMLevel]=(0) AND [PerAssemblyQty]=(1.00) OR [ProductAssemblyID] IS NOT NULL AND [BOMLevel]>=(1))
CK_BillOfMaterials_BOMLevelPerAssemblyQty([ProductAssemblyID] IS NULL AND [BOMLevel]=(0) AND [PerAssemblyQty]=(1.00) OR [ProductAssemblyID] IS NOT NULL AND [BOMLevel]>=(1))
CK_BillOfMaterials_PerAssemblyQtyPerAssemblyQty([PerAssemblyQty]>=(1.00))

Objects that depend on Production.BillOfMaterials

stored proceduredbo.uspGetBillOfMaterials
stored proceduredbo.uspGetWhereUsedProductID

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[BillOfMaterials](
    [BillOfMaterialsID] [int] IDENTITY(1,1) NOT NULL,
    [ProductAssemblyID] [int] NULL,
    [ComponentID] [int] NOT NULL,
    [StartDate] [datetime] NOT NULL,
    [EndDate] [datetime] NULL,
    [UnitMeasureCode] [nchar](3) COLLATE Latin1_General_CS_AS NOT NULL,
    [BOMLevel] [smallint] NOT NULL,
    [PerAssemblyQty] [decimal](8, 2) NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.Culture

Lookup table containing the languages in which some AdventureWorks data is stored.

Fields

Field name Data type Nullable Default value Field description
CultureIDnchar (6) Primary key for Culture records.
NameNameCulture description.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.ProductModelProductDescriptionCultureFK_ProductModelProductDescriptionCulture_Culture_CultureIDPK_Culture_CultureID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Culture_NameNameASCYesNONCLUSTERED
PK_Culture_CultureIDCultureIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[Culture](
    [CultureID] [nchar](6) COLLATE Latin1_General_CS_AS NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.Document

Product maintenance documents.

Fields

Field name Data type Nullable Default value Field description
DocumentIDintPrimary key for Document records.
Titlenvarchar (50) Title of the document.
FileNamenvarchar (400) Directory path and file name of the document
FileExtensionnvarchar (8) File extension indicating the document type. For example, .doc or .txt.
Revisionnchar (5) Revision number of the document.
ChangeNumberint((0))Engineering change approval number.
Statustinyint1 = Pending approval, 2 = Approved, 3 = Obsolete
DocumentSummarynvarcharYesDocument abstract.
DocumentvarbinaryYesComplete document.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.ProductDocumentFK_ProductDocument_Document_DocumentIDPK_Document_DocumentID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Document_FileName_RevisionFileNameASCYesNONCLUSTERED
AK_Document_FileName_RevisionRevisionASCYesNONCLUSTERED
PK_Document_DocumentIDDocumentIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_Document_StatusStatus([Status]>=(1) AND [Status]<=(3))

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[Document](
    [DocumentID] [int] IDENTITY(1,1) NOT NULL,
    [Title] [nvarchar](50) COLLATE Latin1_General_CS_AS NOT NULL,
    [FileName] [nvarchar](400) COLLATE Latin1_General_CS_AS NOT NULL,
    [FileExtension] [nvarchar](8) COLLATE Latin1_General_CS_AS NOT NULL,
    [Revision] [nchar](5) COLLATE Latin1_General_CS_AS NOT NULL,
    [ChangeNumber] [int] NOT NULL,
    [Status] [tinyint] NOT NULL,
    [DocumentSummary] [nvarchar](max) COLLATE Latin1_General_CS_AS NULL,
    [Document] [varbinary](max) NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.Illustration

Bicycle assembly diagrams.

Fields

Field name Data type Nullable Default value Field description
IllustrationIDintPrimary key for Illustration records.
DiagramxmlYesIllustrations used in manufacturing instructions. Stored as XML.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.ProductModelIllustrationFK_ProductModelIllustration_Illustration_IllustrationIDPK_Illustration_IllustrationID

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_Illustration_IllustrationIDIllustrationIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[Illustration](
    [IllustrationID] [int] IDENTITY(1,1) NOT NULL,
    [Diagram] [xml] NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.Location

Product inventory and manufacturing locations.

Fields

Field name Data type Nullable Default value Field description
LocationIDsmallintPrimary key for Location records.
NameNameLocation description.
CostRatesmallmoney((0.00))Standard hourly cost of the manufacturing location.
Availabilitydecimal (8.2) ((0.00))Work capacity (in hours) of the manufacturing location.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.ProductInventoryFK_ProductInventory_Location_LocationIDPK_Location_LocationID
Production.WorkOrderRoutingFK_WorkOrderRouting_Location_LocationIDPK_Location_LocationID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Location_NameNameASCYesNONCLUSTERED
PK_Location_LocationIDLocationIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_Location_CostRateCostRate([CostRate]>=(0.00))
CK_Location_AvailabilityAvailability([Availability]>=(0.00))

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[Location](
    [LocationID] [smallint] IDENTITY(1,1) NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [CostRate] [smallmoney] NOT NULL,
    [Availability] [decimal](8, 2) NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.Product

Products sold or used in the manfacturing of sold products.

Fields

Field name Data type Nullable Default value Field description
ProductIDintPrimary key for Product records.
NameNameName of the product.
ProductNumbernvarchar (25) Unique product identification number.
MakeFlagFlag((1))0 = Product is purchased, 1 = Product is manufactured in-house.
FinishedGoodsFlagFlag((1))0 = Product is not a salable item. 1 = Product is salable.
Colornvarchar (15) YesProduct color.
SafetyStockLevelsmallintMinimum inventory quantity.
ReorderPointsmallintInventory level that triggers a purchase order or work order.
StandardCostmoneyStandard cost of the product.
ListPricemoneySelling price.
Sizenvarchar (5) YesProduct size.
SizeUnitMeasureCodenchar (3) YesUnit of measure for Size column.
WeightUnitMeasureCodenchar (3) YesUnit of measure for Weight column.
Weightdecimal (8.2) YesProduct weight.
DaysToManufactureintNumber of days required to manufacture the product.
ProductLinenchar (2) YesR = Road, M = Mountain, T = Touring, S = Standard
Classnchar (2) YesH = High, M = Medium, L = Low
Stylenchar (2) YesW = Womens, M = Mens, U = Universal
ProductSubcategoryIDintYesProduct is a member of this product subcategory. Foreign key to ProductSubCategory.ProductSubCategoryID.
ProductModelIDintYesProduct is a member of this product model. Foreign key to ProductModel.ProductModelID.
SellStartDatedatetimeDate the product was available for sale.
SellEndDatedatetimeYesDate the product was no longer available for sale.
DiscontinuedDatedatetimeYesDate the product was discontinued.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_Product_UnitMeasure_SizeUnitMeasureCodeSizeUnitMeasureCodePK_UnitMeasure_UnitMeasureCode (Production.UnitMeasure) Foreign key constraint referencing UnitMeasure.UnitMeasureCode
FK_Product_UnitMeasure_WeightUnitMeasureCodeWeightUnitMeasureCodePK_UnitMeasure_UnitMeasureCode (Production.UnitMeasure) Foreign key constraint referencing UnitMeasure.UnitMeasureCode.
FK_Product_ProductSubcategory_ProductSubcategoryIDProductSubcategoryIDPK_ProductSubcategory_ProductSubcategoryID (Production.ProductSubcategory) Foreign key constraint referencing ProductSubcategory.ProductSubcategoryID.
FK_Product_ProductModel_ProductModelIDProductModelIDPK_ProductModel_ProductModelID (Production.ProductModel) Foreign key constraint referencing ProductModel.ProductModelID.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.ProductCostHistoryFK_ProductCostHistory_Product_ProductIDPK_Product_ProductID
Production.ProductDocumentFK_ProductDocument_Product_ProductIDPK_Product_ProductID
Production.ProductInventoryFK_ProductInventory_Product_ProductIDPK_Product_ProductID
Production.ProductListPriceHistoryFK_ProductListPriceHistory_Product_ProductIDPK_Product_ProductID
Production.ProductProductPhotoFK_ProductProductPhoto_Product_ProductIDPK_Product_ProductID
Production.ProductReviewFK_ProductReview_Product_ProductIDPK_Product_ProductID
Purchasing.ProductVendorFK_ProductVendor_Product_ProductIDPK_Product_ProductID
Sales.SpecialOfferProductFK_SpecialOfferProduct_Product_ProductIDPK_Product_ProductID
Production.TransactionHistoryFK_TransactionHistory_Product_ProductIDPK_Product_ProductID
Production.WorkOrderFK_WorkOrder_Product_ProductIDPK_Product_ProductID
Production.BillOfMaterialsFK_BillOfMaterials_Product_ComponentIDPK_Product_ProductID
Purchasing.PurchaseOrderDetailFK_PurchaseOrderDetail_Product_ProductIDPK_Product_ProductID
Sales.ShoppingCartItemFK_ShoppingCartItem_Product_ProductIDPK_Product_ProductID
Production.BillOfMaterialsFK_BillOfMaterials_Product_ProductAssemblyIDPK_Product_ProductID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Product_NameNameASCYesNONCLUSTERED
AK_Product_ProductNumberProductNumberASCYesNONCLUSTERED
AK_Product_rowguidrowguidASCYesNONCLUSTERED
PK_Product_ProductIDProductIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_Product_SafetyStockLevelSafetyStockLevel([SafetyStockLevel]>(0))
CK_Product_ReorderPointReorderPoint([ReorderPoint]>(0))
CK_Product_StandardCostStandardCost([StandardCost]>=(0.00))
CK_Product_ListPriceListPrice([ListPrice]>=(0.00))
CK_Product_WeightWeight([Weight]>(0.00))
CK_Product_DaysToManufactureDaysToManufacture([DaysToManufacture]>=(0))
CK_Product_ProductLineProductLine(upper([ProductLine])='R' OR upper([ProductLine])='M' OR upper([ProductLine])='T' OR upper([ProductLine])='S' OR [ProductLine] IS NULL)
CK_Product_ClassClass(upper([Class])='H' OR upper([Class])='M' OR upper([Class])='L' OR [Class] IS NULL)
CK_Product_StyleStyle(upper([Style])='U' OR upper([Style])='M' OR upper([Style])='W' OR [Style] IS NULL)
CK_Product_SellEndDateSellStartDate([SellEndDate]>=[SellStartDate] OR [SellEndDate] IS NULL)
CK_Product_SellEndDateSellEndDate([SellEndDate]>=[SellStartDate] OR [SellEndDate] IS NULL)

Objects that depend on Production.Product

udfdbo.ufnGetProductDealerPrice
udfdbo.ufnGetProductListPrice
udfdbo.ufnGetProductStandardCost
stored proceduredbo.uspGetBillOfMaterials
stored proceduredbo.uspGetWhereUsedProductID
viewProduction.vProductAndDescription

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[Product](
    [ProductID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [ProductNumber] [nvarchar](25) COLLATE Latin1_General_CS_AS NOT NULL,
    [MakeFlag] [dbo].[Flag] NOT NULL,
    [FinishedGoodsFlag] [dbo].[Flag] NOT NULL,
    [Color] [nvarchar](15) COLLATE Latin1_General_CS_AS NULL,
    [SafetyStockLevel] [smallint] NOT NULL,
    [ReorderPoint] [smallint] NOT NULL,
    [StandardCost] [money] NOT NULL,
    [ListPrice] [money] NOT NULL,
    [Size] [nvarchar](5) COLLATE Latin1_General_CS_AS NULL,
    [SizeUnitMeasureCode] [nchar](3) COLLATE Latin1_General_CS_AS NULL,
    [WeightUnitMeasureCode] [nchar](3) COLLATE Latin1_General_CS_AS NULL,
    [Weight] [decimal](8, 2) NULL,
    [DaysToManufacture] [int] NOT NULL,
    [ProductLine] [nchar](2) COLLATE Latin1_General_CS_AS NULL,
    [Class] [nchar](2) COLLATE Latin1_General_CS_AS NULL,
    [Style] [nchar](2) COLLATE Latin1_General_CS_AS NULL,
    [ProductSubcategoryID] [int] NULL,
    [ProductModelID] [int] NULL,
    [SellStartDate] [datetime] NOT NULL,
    [SellEndDate] [datetime] NULL,
    [DiscontinuedDate] [datetime] NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductCategory

High-level product categorization.

Fields

Field name Data type Nullable Default value Field description
ProductCategoryIDintPrimary key for ProductCategory records.
NameNameCategory description.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.ProductSubcategoryFK_ProductSubcategory_ProductCategory_ProductCategoryIDPK_ProductCategory_ProductCategoryID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_ProductCategory_NameNameASCYesNONCLUSTERED
AK_ProductCategory_rowguidrowguidASCYesNONCLUSTERED
PK_ProductCategory_ProductCategoryIDProductCategoryIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductCategory](
    [ProductCategoryID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductCostHistory

Changes in the cost of a product over time.

Fields

Field name Data type Nullable Default value Field description
ProductIDintProduct identification number. Foreign key to Product.ProductID
StartDatedatetimeProduct cost start date.
EndDatedatetimeYesProduct cost end date.
StandardCostmoneyStandard cost of the product.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_ProductCostHistory_Product_ProductIDProductIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductID.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_ProductCostHistory_ProductID_StartDateProductIDASCYesCLUSTERED
PK_ProductCostHistory_ProductID_StartDateStartDateASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_ProductCostHistory_EndDateStartDate([EndDate]>=[StartDate] OR [EndDate] IS NULL)
CK_ProductCostHistory_EndDateEndDate([EndDate]>=[StartDate] OR [EndDate] IS NULL)
CK_ProductCostHistory_StandardCostStandardCost([StandardCost]>=(0.00))

Objects that depend on Production.ProductCostHistory

udfdbo.ufnGetProductStandardCost

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductCostHistory](
    [ProductID] [int] NOT NULL,
    [StartDate] [datetime] NOT NULL,
    [EndDate] [datetime] NULL,
    [StandardCost] [money] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductDescription

Product descriptions in several languages.

Fields

Field name Data type Nullable Default value Field description
ProductDescriptionIDintPrimary key for ProductDescription records.
Descriptionnvarchar (400) Description of the product.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.ProductModelProductDescriptionCultureFK_ProductModelProductDescriptionCulture_ProductDescription_ProductDescriptionIDPK_ProductDescription_ProductDescriptionID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_ProductDescription_rowguidrowguidASCYesNONCLUSTERED
PK_ProductDescription_ProductDescriptionIDProductDescriptionIDASCYesCLUSTERED

Objects that depend on Production.ProductDescription

viewProduction.vProductAndDescription

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductDescription](
    [ProductDescriptionID] [int] IDENTITY(1,1) NOT NULL,
    [Description] [nvarchar](400) COLLATE Latin1_General_CS_AS NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductDocument

Cross-reference table mapping products to related product documents.

Fields

Field name Data type Nullable Default value Field description
ProductIDintProduct identification number. Foreign key to Product.ProductID.
DocumentIDintDocument identification number. Foreign key to Document.DocumentID.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_ProductDocument_Product_ProductIDProductIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductID.
FK_ProductDocument_Document_DocumentIDDocumentIDPK_Document_DocumentID (Production.Document) Foreign key constraint referencing Document.DocumentID.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_ProductDocument_ProductID_DocumentIDProductIDASCYesCLUSTERED
PK_ProductDocument_ProductID_DocumentIDDocumentIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductDocument](
    [ProductID] [int] NOT NULL,
    [DocumentID] [int] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductInventory

Product inventory information.

Fields

Field name Data type Nullable Default value Field description
ProductIDintProduct identification number. Foreign key to Product.ProductID.
LocationIDsmallintInventory location identification number. Foreign key to Location.LocationID.
Shelfnvarchar (10) Storage compartment within an inventory location.
BintinyintStorage container on a shelf in an inventory location.
Quantitysmallint((0))Quantity of products in the inventory location.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_ProductInventory_Product_ProductIDProductIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductID.
FK_ProductInventory_Location_LocationIDLocationIDPK_Location_LocationID (Production.Location) Foreign key constraint referencing Location.LocationID.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_ProductInventory_ProductID_LocationIDProductIDASCYesCLUSTERED
PK_ProductInventory_ProductID_LocationIDLocationIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_ProductInventory_ShelfShelf([Shelf] like '[A-Za-z]' OR [Shelf]='N/A')
CK_ProductInventory_BinBin([Bin]>=(0) AND [Bin]<=(100))

Objects that depend on Production.ProductInventory

udfdbo.ufnGetStock

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductInventory](
    [ProductID] [int] NOT NULL,
    [LocationID] [smallint] NOT NULL,
    [Shelf] [nvarchar](10) COLLATE Latin1_General_CS_AS NOT NULL,
    [Bin] [tinyint] NOT NULL,
    [Quantity] [smallint] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductListPriceHistory

Changes in the list price of a product over time.

Fields

Field name Data type Nullable Default value Field description
ProductIDintProduct identification number. Foreign key to Product.ProductID
StartDatedatetimeList price start date.
EndDatedatetimeYesList price end date
ListPricemoneyProduct list price.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_ProductListPriceHistory_Product_ProductIDProductIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductID.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_ProductListPriceHistory_ProductID_StartDateProductIDASCYesCLUSTERED
PK_ProductListPriceHistory_ProductID_StartDateStartDateASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_ProductListPriceHistory_EndDateStartDate([EndDate]>=[StartDate] OR [EndDate] IS NULL)
CK_ProductListPriceHistory_EndDateEndDate([EndDate]>=[StartDate] OR [EndDate] IS NULL)
CK_ProductListPriceHistory_ListPriceListPrice([ListPrice]>(0.00))

Objects that depend on Production.ProductListPriceHistory

udfdbo.ufnGetProductDealerPrice
udfdbo.ufnGetProductListPrice

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductListPriceHistory](
    [ProductID] [int] NOT NULL,
    [StartDate] [datetime] NOT NULL,
    [EndDate] [datetime] NULL,
    [ListPrice] [money] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductModel

Product model classification.

Fields

Field name Data type Nullable Default value Field description
ProductModelIDintPrimary key for ProductModel records.
NameNameProduct model description.
CatalogDescriptionxmlYesDetailed product catalog information in xml format.
InstructionsxmlYesManufacturing instructions in xml format.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.ProductFK_Product_ProductModel_ProductModelIDPK_ProductModel_ProductModelID
Production.ProductModelIllustrationFK_ProductModelIllustration_ProductModel_ProductModelIDPK_ProductModel_ProductModelID
Production.ProductModelProductDescriptionCultureFK_ProductModelProductDescriptionCulture_ProductModel_ProductModelIDPK_ProductModel_ProductModelID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_ProductModel_NameNameASCYesNONCLUSTERED
AK_ProductModel_rowguidrowguidASCYesNONCLUSTERED
PK_ProductModel_ProductModelIDProductModelIDASCYesCLUSTERED
PXML_ProductModel_CatalogDescriptionCatalogDescriptionASCXML
PXML_ProductModel_InstructionsInstructionsASCXML

Objects that depend on Production.ProductModel

viewProduction.vProductAndDescription
viewProduction.vProductModelCatalogDescription
viewProduction.vProductModelInstructions

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductModel](
    [ProductModelID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [CatalogDescription] [xml](CONTENT [Production].[ProductDescriptionSchemaCollection]) NULL,
    [Instructions] [xml](CONTENT [Production].[ManuInstructionsSchemaCollection]) NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductModelIllustration

Cross-reference table mapping product models and illustrations.

Fields

Field name Data type Nullable Default value Field description
ProductModelIDintPrimary key. Foreign key to ProductModel.ProductModelID.
IllustrationIDintPrimary key. Foreign key to Illustration.IllustrationID.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_ProductModelIllustration_ProductModel_ProductModelIDProductModelIDPK_ProductModel_ProductModelID (Production.ProductModel) Foreign key constraint referencing ProductModel.ProductModelID.
FK_ProductModelIllustration_Illustration_IllustrationIDIllustrationIDPK_Illustration_IllustrationID (Production.Illustration) Foreign key constraint referencing Illustration.IllustrationID.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_ProductModelIllustration_ProductModelID_IllustrationIDProductModelIDASCYesCLUSTERED
PK_ProductModelIllustration_ProductModelID_IllustrationIDIllustrationIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductModelIllustration](
    [ProductModelID] [int] NOT NULL,
    [IllustrationID] [int] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductModelProductDescriptionCulture

Cross-reference table mapping product descriptions and the language the description is written in.

Fields

Field name Data type Nullable Default value Field description
ProductModelIDintPrimary key. Foreign key to ProductModel.ProductModelID.
ProductDescriptionIDintPrimary key. Foreign key to ProductDescription.ProductDescriptionID.
CultureIDnchar (6) Culture identification number. Foreign key to Culture.CultureID.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_ProductModelProductDescriptionCulture_ProductModel_ProductModelIDProductModelIDPK_ProductModel_ProductModelID (Production.ProductModel) Foreign key constraint referencing ProductModel.ProductModelID.
FK_ProductModelProductDescriptionCulture_ProductDescription_ProductDescriptionIDProductDescriptionIDPK_ProductDescription_ProductDescriptionID (Production.ProductDescription) Foreign key constraint referencing ProductDescription.ProductDescriptionID.
FK_ProductModelProductDescriptionCulture_Culture_CultureIDCultureIDPK_Culture_CultureID (Production.Culture) Foreign key constraint referencing Culture.CultureID.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_ProductModelProductDescriptionCulture_ProductModelID_ProductDescriptionID_CultureIDProductModelIDASCYesCLUSTERED
PK_ProductModelProductDescriptionCulture_ProductModelID_ProductDescriptionID_CultureIDProductDescriptionIDASCYesCLUSTERED
PK_ProductModelProductDescriptionCulture_ProductModelID_ProductDescriptionID_CultureIDCultureIDASCYesCLUSTERED

Objects that depend on Production.ProductModelProductDescriptionCulture

viewProduction.vProductAndDescription

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductModelProductDescriptionCulture](
    [ProductModelID] [int] NOT NULL,
    [ProductDescriptionID] [int] NOT NULL,
    [CultureID] [nchar](6) COLLATE Latin1_General_CS_AS NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductPhoto

Product images.

Fields

Field name Data type Nullable Default value Field description
ProductPhotoIDintPrimary key for ProductPhoto records.
ThumbNailPhotovarbinaryYesSmall image of the product.
ThumbnailPhotoFileNamenvarchar (50) YesSmall image file name.
LargePhotovarbinaryYesLarge image of the product.
LargePhotoFileNamenvarchar (50) YesLarge image file name.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.ProductProductPhotoFK_ProductProductPhoto_ProductPhoto_ProductPhotoIDPK_ProductPhoto_ProductPhotoID

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_ProductPhoto_ProductPhotoIDProductPhotoIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductPhoto](
    [ProductPhotoID] [int] IDENTITY(1,1) NOT NULL,
    [ThumbNailPhoto] [varbinary](max) NULL,
    [ThumbnailPhotoFileName] [nvarchar](50) COLLATE Latin1_General_CS_AS NULL,
    [LargePhoto] [varbinary](max) NULL,
    [LargePhotoFileName] [nvarchar](50) COLLATE Latin1_General_CS_AS NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductProductPhoto

Cross-reference table mapping products and product photos.

Fields

Field name Data type Nullable Default value Field description
ProductIDintProduct identification number. Foreign key to Product.ProductID.
ProductPhotoIDintProduct photo identification number. Foreign key to ProductPhoto.ProductPhotoID.
PrimaryFlag((0))0 = Photo is not the principal image. 1 = Photo is the principal image.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_ProductProductPhoto_Product_ProductIDProductIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductID.
FK_ProductProductPhoto_ProductPhoto_ProductPhotoIDProductPhotoIDPK_ProductPhoto_ProductPhotoID (Production.ProductPhoto) Foreign key constraint referencing ProductPhoto.ProductPhotoID.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_ProductProductPhoto_ProductID_ProductPhotoIDProductIDASCYesNONCLUSTERED
PK_ProductProductPhoto_ProductID_ProductPhotoIDProductPhotoIDASCYesNONCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductProductPhoto](
    [ProductID] [int] NOT NULL,
    [ProductPhotoID] [int] NOT NULL,
    [Primary] [dbo].[Flag] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductReview

Customer reviews of products they have purchased.

Fields

Field name Data type Nullable Default value Field description
ProductReviewIDintPrimary key for ProductReview records.
ProductIDintProduct identification number. Foreign key to Product.ProductID.
ReviewerNameNameName of the reviewer.
ReviewDatedatetime(getdate())Date review was submitted.
EmailAddressnvarchar (50) Reviewer's e-mail address.
RatingintProduct rating given by the reviewer. Scale is 1 to 5 with 5 as the highest rating.
Commentsnvarchar (3850) YesReviewer's comments
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_ProductReview_Product_ProductIDProductIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductID.

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_ProductReview_ProductID_NameProductIDASCNONCLUSTERED
IX_ProductReview_ProductID_NameReviewerNameASCNONCLUSTERED
PK_ProductReview_ProductReviewIDProductReviewIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_ProductReview_RatingRating([Rating]>=(1) AND [Rating]<=(5))

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductReview](
    [ProductReviewID] [int] IDENTITY(1,1) NOT NULL,
    [ProductID] [int] NOT NULL,
    [ReviewerName] [dbo].[Name] NOT NULL,
    [ReviewDate] [datetime] NOT NULL,
    [EmailAddress] [nvarchar](50) COLLATE Latin1_General_CS_AS NOT NULL,
    [Rating] [int] NOT NULL,
    [Comments] [nvarchar](3850) COLLATE Latin1_General_CS_AS NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ProductSubcategory

Product subcategories. See ProductCategory table.

Fields

Field name Data type Nullable Default value Field description
ProductSubcategoryIDintPrimary key for ProductSubcategory records.
ProductCategoryIDintProduct category identification number. Foreign key to ProductCategory.ProductCategoryID.
NameNameSubcategory description.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_ProductSubcategory_ProductCategory_ProductCategoryIDProductCategoryIDPK_ProductCategory_ProductCategoryID (Production.ProductCategory) Foreign key constraint referencing ProductCategory.ProductCategoryID.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.ProductFK_Product_ProductSubcategory_ProductSubcategoryIDPK_ProductSubcategory_ProductSubcategoryID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_ProductSubcategory_NameNameASCYesNONCLUSTERED
AK_ProductSubcategory_rowguidrowguidASCYesNONCLUSTERED
PK_ProductSubcategory_ProductSubcategoryIDProductSubcategoryIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ProductSubcategory](
    [ProductSubcategoryID] [int] IDENTITY(1,1) NOT NULL,
    [ProductCategoryID] [int] NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.ScrapReason

Manufacturing failure reasons lookup table.

Fields

Field name Data type Nullable Default value Field description
ScrapReasonIDsmallintPrimary key for ScrapReason records.
NameNameFailure description.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.WorkOrderFK_WorkOrder_ScrapReason_ScrapReasonIDPK_ScrapReason_ScrapReasonID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_ScrapReason_NameNameASCYesNONCLUSTERED
PK_ScrapReason_ScrapReasonIDScrapReasonIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[ScrapReason](
    [ScrapReasonID] [smallint] IDENTITY(1,1) NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.TransactionHistory

Record of each purchase order, sales order, or work order transaction year to date.

Fields

Field name Data type Nullable Default value Field description
TransactionIDintPrimary key for TransactionHistory records.
ProductIDintProduct identification number. Foreign key to Product.ProductID.
ReferenceOrderIDintPurchase order, sales order, or work order identification number.
ReferenceOrderLineIDint((0))Line number associated with the purchase order, sales order, or work order.
TransactionDatedatetime(getdate())Date and time of the transaction.
TransactionTypenchar (1) W = WorkOrder, S = SalesOrder, P = PurchaseOrder
QuantityintProduct quantity.
ActualCostmoneyProduct cost.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_TransactionHistory_Product_ProductIDProductIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductID.

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_TransactionHistory_ProductIDProductIDASCNONCLUSTERED
IX_TransactionHistory_ReferenceOrderID_ReferenceOrderLineIDReferenceOrderIDASCNONCLUSTERED
IX_TransactionHistory_ReferenceOrderID_ReferenceOrderLineIDReferenceOrderLineIDASCNONCLUSTERED
PK_TransactionHistory_TransactionIDTransactionIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_TransactionHistory_TransactionTypeTransactionType(upper([TransactionType])='P' OR upper([TransactionType])='S' OR upper([TransactionType])='W')

Objects that depend on Production.TransactionHistory

triggerProduction.iWorkOrder
triggerProduction.uWorkOrder
triggerPurchasing.iPurchaseOrderDetail
triggerPurchasing.uPurchaseOrderDetail
triggerSales.iduSalesOrderDetail

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[TransactionHistory](
    [TransactionID] [int] IDENTITY(100000,1) NOT NULL,
    [ProductID] [int] NOT NULL,
    [ReferenceOrderID] [int] NOT NULL,
    [ReferenceOrderLineID] [int] NOT NULL,
    [TransactionDate] [datetime] NOT NULL,
    [TransactionType] [nchar](1) COLLATE Latin1_General_CS_AS NOT NULL,
    [Quantity] [int] NOT NULL,
    [ActualCost] [money] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.TransactionHistoryArchive

Transactions for previous years.

Fields

Field name Data type Nullable Default value Field description
TransactionIDintPrimary key for TransactionHistoryArchive records.
ProductIDintProduct identification number. Foreign key to Product.ProductID.
ReferenceOrderIDintPurchase order, sales order, or work order identification number.
ReferenceOrderLineIDint((0))Line number associated with the purchase order, sales order, or work order.
TransactionDatedatetime(getdate())Date and time of the transaction.
TransactionTypenchar (1) W = Work Order, S = Sales Order, P = Purchase Order
QuantityintProduct quantity.
ActualCostmoneyProduct cost.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_TransactionHistoryArchive_ProductIDProductIDASCNONCLUSTERED
IX_TransactionHistoryArchive_ReferenceOrderID_ReferenceOrderLineIDReferenceOrderIDASCNONCLUSTERED
IX_TransactionHistoryArchive_ReferenceOrderID_ReferenceOrderLineIDReferenceOrderLineIDASCNONCLUSTERED
PK_TransactionHistoryArchive_TransactionIDTransactionIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_TransactionHistoryArchive_TransactionTypeTransactionType(upper([TransactionType])='P' OR upper([TransactionType])='S' OR upper([TransactionType])='W')

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[TransactionHistoryArchive](
    [TransactionID] [int] NOT NULL,
    [ProductID] [int] NOT NULL,
    [ReferenceOrderID] [int] NOT NULL,
    [ReferenceOrderLineID] [int] NOT NULL,
    [TransactionDate] [datetime] NOT NULL,
    [TransactionType] [nchar](1) COLLATE Latin1_General_CS_AS NOT NULL,
    [Quantity] [int] NOT NULL,
    [ActualCost] [money] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.UnitMeasure

Unit of measure lookup table.

Fields

Field name Data type Nullable Default value Field description
UnitMeasureCodenchar (3) Primary key.
NameNameUnit of measure description.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.ProductFK_Product_UnitMeasure_SizeUnitMeasureCodePK_UnitMeasure_UnitMeasureCode
Production.ProductFK_Product_UnitMeasure_WeightUnitMeasureCodePK_UnitMeasure_UnitMeasureCode
Purchasing.ProductVendorFK_ProductVendor_UnitMeasure_UnitMeasureCodePK_UnitMeasure_UnitMeasureCode
Production.BillOfMaterialsFK_BillOfMaterials_UnitMeasure_UnitMeasureCodePK_UnitMeasure_UnitMeasureCode

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_UnitMeasure_NameNameASCYesNONCLUSTERED
PK_UnitMeasure_UnitMeasureCodeUnitMeasureCodeASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[UnitMeasure](
    [UnitMeasureCode] [nchar](3) COLLATE Latin1_General_CS_AS NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.WorkOrder

Manufacturing work orders.

Fields

Field name Data type Nullable Default value Field description
WorkOrderIDintPrimary key for WorkOrder records.
ProductIDintProduct identification number. Foreign key to Product.ProductID.
OrderQtyintProduct quantity to build.
StockedQtyintQuantity built and put in inventory.
ScrappedQtysmallintQuantity that failed inspection.
StartDatedatetimeWork order start date.
EndDatedatetimeYesWork order end date.
DueDatedatetimeWork order due date.
ScrapReasonIDsmallintYesReason for inspection failure.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_WorkOrder_Product_ProductIDProductIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductID.
FK_WorkOrder_ScrapReason_ScrapReasonIDScrapReasonIDPK_ScrapReason_ScrapReasonID (Production.ScrapReason) Foreign key constraint referencing ScrapReason.ScrapReasonID.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Production.WorkOrderRoutingFK_WorkOrderRouting_WorkOrder_WorkOrderIDPK_WorkOrder_WorkOrderID

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_WorkOrder_ProductIDProductIDASCNONCLUSTERED
IX_WorkOrder_ScrapReasonIDScrapReasonIDASCNONCLUSTERED
PK_WorkOrder_WorkOrderIDWorkOrderIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_WorkOrder_OrderQtyOrderQty([OrderQty]>(0))
CK_WorkOrder_ScrappedQtyScrappedQty([ScrappedQty]>=(0))
CK_WorkOrder_EndDateStartDate([EndDate]>=[StartDate] OR [EndDate] IS NULL)
CK_WorkOrder_EndDateEndDate([EndDate]>=[StartDate] OR [EndDate] IS NULL)

Triggers

Trigger name:Production.iWorkOrder
Description:AFTER INSERT trigger that inserts a row in the TransactionHistory table.
Creation date:26 Apr 2006
Trigger type:INSERT
Trigger active:Yes
Trigger definition

CREATE TRIGGER [Production].[iWorkOrder] ON [Production].[WorkOrder] 
AFTER INSERT AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
        INSERT INTO [Production].[TransactionHistory](
            [ProductID]
            ,[ReferenceOrderID]
            ,[TransactionType]
            ,[TransactionDate]
            ,[Quantity]
            ,[ActualCost])
        SELECT 
            inserted.[ProductID]
            ,inserted.[WorkOrderID]
            ,'W'
            ,GETDATE()
            ,inserted.[OrderQty]
            ,0
        FROM inserted;
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];

        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Trigger name:Production.uWorkOrder
Description:AFTER UPDATE trigger that inserts a row in the TransactionHistory table, updates ModifiedDate in the WorkOrder table.
Creation date:26 Apr 2006
Trigger type:UPDATE
Trigger active:Yes
Trigger definition

CREATE TRIGGER [Production].[uWorkOrder] ON [Production].[WorkOrder] 
AFTER UPDATE AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
        IF UPDATE([ProductID]) OR UPDATE([OrderQty])
        BEGIN
            INSERT INTO [Production].[TransactionHistory](
                [ProductID]
                ,[ReferenceOrderID]
                ,[TransactionType]
                ,[TransactionDate]
                ,[Quantity])
            SELECT 
                inserted.[ProductID]
                ,inserted.[WorkOrderID]
                ,'W'
                ,GETDATE()
                ,inserted.[OrderQty]
            FROM inserted;
        END;
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];

        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Objects that depend on Production.WorkOrder

triggerProduction.uWorkOrder
tableProduction.WorkOrder

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[WorkOrder](
    [WorkOrderID] [int] IDENTITY(1,1) NOT NULL,
    [ProductID] [int] NOT NULL,
    [OrderQty] [int] NOT NULL,
    [StockedQty]  AS (isnull([OrderQty]-[ScrappedQty],(0))),
    [ScrappedQty] [smallint] NOT NULL,
    [StartDate] [datetime] NOT NULL,
    [EndDate] [datetime] NULL,
    [DueDate] [datetime] NOT NULL,
    [ScrapReasonID] [smallint] NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Production.WorkOrderRouting

Work order details.

Fields

Field name Data type Nullable Default value Field description
WorkOrderIDintPrimary key. Foreign key to WorkOrder.WorkOrderID.
ProductIDintPrimary key. Foreign key to Product.ProductID.
OperationSequencesmallintPrimary key. Indicates the manufacturing process sequence.
LocationIDsmallintManufacturing location where the part is processed. Foreign key to Location.LocationID.
ScheduledStartDatedatetimePlanned manufacturing start date.
ScheduledEndDatedatetimePlanned manufacturing end date.
ActualStartDatedatetimeYesActual start date.
ActualEndDatedatetimeYesActual end date.
ActualResourceHrsdecimal (9.4) YesNumber of manufacturing hours used.
PlannedCostmoneyEstimated manufacturing cost.
ActualCostmoneyYesActual manufacturing cost.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_WorkOrderRouting_WorkOrder_WorkOrderIDWorkOrderIDPK_WorkOrder_WorkOrderID (Production.WorkOrder) Foreign key constraint referencing WorkOrder.WorkOrderID.
FK_WorkOrderRouting_Location_LocationIDLocationIDPK_Location_LocationID (Production.Location) Foreign key constraint referencing Location.LocationID.

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_WorkOrderRouting_ProductIDProductIDASCNONCLUSTERED
PK_WorkOrderRouting_WorkOrderID_ProductID_OperationSequenceWorkOrderIDASCYesCLUSTERED
PK_WorkOrderRouting_WorkOrderID_ProductID_OperationSequenceProductIDASCYesCLUSTERED
PK_WorkOrderRouting_WorkOrderID_ProductID_OperationSequenceOperationSequenceASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_WorkOrderRouting_ScheduledEndDateScheduledStartDate([ScheduledEndDate]>=[ScheduledStartDate])
CK_WorkOrderRouting_ScheduledEndDateScheduledEndDate([ScheduledEndDate]>=[ScheduledStartDate])
CK_WorkOrderRouting_ActualEndDateActualStartDate([ActualEndDate]>=[ActualStartDate] OR [ActualEndDate] IS NULL OR [ActualStartDate] IS NULL)
CK_WorkOrderRouting_ActualEndDateActualEndDate([ActualEndDate]>=[ActualStartDate] OR [ActualEndDate] IS NULL OR [ActualStartDate] IS NULL)
CK_WorkOrderRouting_ActualResourceHrsActualResourceHrs([ActualResourceHrs]>=(0.0000))
CK_WorkOrderRouting_PlannedCostPlannedCost([PlannedCost]>(0.00))
CK_WorkOrderRouting_ActualCostActualCost([ActualCost]>(0.00))

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Production].[WorkOrderRouting](
    [WorkOrderID] [int] NOT NULL,
    [ProductID] [int] NOT NULL,
    [OperationSequence] [smallint] NOT NULL,
    [LocationID] [smallint] NOT NULL,
    [ScheduledStartDate] [datetime] NOT NULL,
    [ScheduledEndDate] [datetime] NOT NULL,
    [ActualStartDate] [datetime] NULL,
    [ActualEndDate] [datetime] NULL,
    [ActualResourceHrs] [decimal](9, 4) NULL,
    [PlannedCost] [money] NOT NULL,
    [ActualCost] [money] NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Purchasing.ProductVendor

Cross-reference table mapping vendors with the products they supply.

Fields

Field name Data type Nullable Default value Field description
ProductIDintPrimary key. Foreign key to Product.ProductID.
VendorIDintPrimary key. Foreign key to Vendor.VendorID.
AverageLeadTimeintThe average span of time (in days) between placing an order with the vendor and receiving the purchased product.
StandardPricemoneyThe vendor's usual selling price.
LastReceiptCostmoneyYesThe selling price when last purchased.
LastReceiptDatedatetimeYesDate the product was last received by the vendor.
MinOrderQtyintThe maximum quantity that should be ordered.
MaxOrderQtyintThe minimum quantity that should be ordered.
OnOrderQtyintYesThe quantity currently on order.
UnitMeasureCodenchar (3) The product's unit of measure.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_ProductVendor_Product_ProductIDProductIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductID.
FK_ProductVendor_Vendor_VendorIDVendorIDPK_Vendor_VendorID (Purchasing.Vendor) Foreign key constraint referencing Vendor.VendorID.
FK_ProductVendor_UnitMeasure_UnitMeasureCodeUnitMeasureCodePK_UnitMeasure_UnitMeasureCode (Production.UnitMeasure) Foreign key constraint referencing UnitMeasure.UnitMeasureCode.

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_ProductVendor_UnitMeasureCodeUnitMeasureCodeASCNONCLUSTERED
IX_ProductVendor_VendorIDVendorIDASCNONCLUSTERED
PK_ProductVendor_ProductID_VendorIDProductIDASCYesCLUSTERED
PK_ProductVendor_ProductID_VendorIDVendorIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_ProductVendor_AverageLeadTimeAverageLeadTime([AverageLeadTime]>=(1))
CK_ProductVendor_StandardPriceStandardPrice([StandardPrice]>(0.00))
CK_ProductVendor_LastReceiptCostLastReceiptCost([LastReceiptCost]>(0.00))
CK_ProductVendor_MinOrderQtyMinOrderQty([MinOrderQty]>=(1))
CK_ProductVendor_MaxOrderQtyMaxOrderQty([MaxOrderQty]>=(1))
CK_ProductVendor_OnOrderQtyOnOrderQty([OnOrderQty]>=(0))

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Purchasing].[ProductVendor](
    [ProductID] [int] NOT NULL,
    [VendorID] [int] NOT NULL,
    [AverageLeadTime] [int] NOT NULL,
    [StandardPrice] [money] NOT NULL,
    [LastReceiptCost] [money] NULL,
    [LastReceiptDate] [datetime] NULL,
    [MinOrderQty] [int] NOT NULL,
    [MaxOrderQty] [int] NOT NULL,
    [OnOrderQty] [int] NULL,
    [UnitMeasureCode] [nchar](3) COLLATE Latin1_General_CS_AS NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Purchasing.PurchaseOrderDetail

Individual products associated with a specific purchase order. See PurchaseOrderHeader.

Fields

Field name Data type Nullable Default value Field description
PurchaseOrderIDintPrimary key. Foreign key to PurchaseOrderHeader.PurchaseOrderID.
PurchaseOrderDetailIDintPrimary key. One line number per purchased product.
DueDatedatetimeDate the product is expected to be received.
OrderQtysmallintQuantity ordered.
ProductIDintProduct identification number. Foreign key to Product.ProductID.
UnitPricemoneyVendor's selling price of a single product.
LineTotalmoneyPer product subtotal. Computed as OrderQty * UnitPrice.
ReceivedQtydecimal (8.2) Quantity actually received from the vendor.
RejectedQtydecimal (8.2) Quantity rejected during inspection.
StockedQtydecimal (9.2) Quantity accepted into inventory. Computed as ReceivedQty - RejectedQty.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_PurchaseOrderDetail_PurchaseOrderHeader_PurchaseOrderIDPurchaseOrderIDPK_PurchaseOrderHeader_PurchaseOrderID (Purchasing.PurchaseOrderHeader) Foreign key constraint referencing PurchaseOrderHeader.PurchaseOrderID.
FK_PurchaseOrderDetail_Product_ProductIDProductIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductID.

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_PurchaseOrderDetail_ProductIDProductIDASCNONCLUSTERED
PK_PurchaseOrderDetail_PurchaseOrderID_PurchaseOrderDetailIDPurchaseOrderIDASCYesCLUSTERED
PK_PurchaseOrderDetail_PurchaseOrderID_PurchaseOrderDetailIDPurchaseOrderDetailIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_PurchaseOrderDetail_OrderQtyOrderQty([OrderQty]>(0))
CK_PurchaseOrderDetail_UnitPriceUnitPrice([UnitPrice]>=(0.00))
CK_PurchaseOrderDetail_ReceivedQtyReceivedQty([ReceivedQty]>=(0.00))
CK_PurchaseOrderDetail_RejectedQtyRejectedQty([RejectedQty]>=(0.00))

Triggers

Trigger name:Purchasing.iPurchaseOrderDetail
Description:AFTER INSERT trigger that inserts a row in the TransactionHistory table and updates the PurchaseOrderHeader.SubTotal column.
Creation date:26 Apr 2006
Trigger type:INSERT
Trigger active:Yes
Trigger definition

CREATE TRIGGER [Purchasing].[iPurchaseOrderDetail] ON [Purchasing].[PurchaseOrderDetail] 
AFTER INSERT AS
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
        INSERT INTO [Production].[TransactionHistory]
            ([ProductID]
            ,[ReferenceOrderID]
            ,[ReferenceOrderLineID]
            ,[TransactionType]
            ,[TransactionDate]
            ,[Quantity]
            ,[ActualCost])
        SELECT 
            inserted.[ProductID]
            ,inserted.[PurchaseOrderID]
            ,inserted.[PurchaseOrderDetailID]
            ,'P'
            ,GETDATE()
            ,inserted.[OrderQty]
            ,inserted.[UnitPrice]
        FROM inserted 
            INNER JOIN [Purchasing].[PurchaseOrderHeader] 
            ON inserted.[PurchaseOrderID] = [Purchasing].[PurchaseOrderHeader].[PurchaseOrderID];

        -- Update SubTotal in PurchaseOrderHeader record. Note that this causes the 
        -- PurchaseOrderHeader trigger to fire which will update the RevisionNumber.
        UPDATE [Purchasing].[PurchaseOrderHeader]
        SET [Purchasing].[PurchaseOrderHeader].[SubTotal] = 
            (SELECT SUM([Purchasing].[PurchaseOrderDetail].[LineTotal])
                FROM [Purchasing].[PurchaseOrderDetail]
                WHERE [Purchasing].[PurchaseOrderHeader].[PurchaseOrderID] = [Purchasing].[PurchaseOrderDetail].[PurchaseOrderID])
        WHERE [Purchasing].[PurchaseOrderHeader].[PurchaseOrderID] IN (SELECT inserted.[PurchaseOrderID] FROM inserted);
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];

        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Trigger name:Purchasing.uPurchaseOrderDetail
Description:AFTER UPDATE trigger that inserts a row in the TransactionHistory table, updates ModifiedDate in PurchaseOrderDetail and updates the PurchaseOrderHeader.SubTotal column.
Creation date:26 Apr 2006
Trigger type:UPDATE
Trigger active:Yes
Trigger definition

CREATE TRIGGER [Purchasing].[uPurchaseOrderDetail] ON [Purchasing].[PurchaseOrderDetail] 
AFTER UPDATE AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
        IF UPDATE([ProductID]) OR UPDATE([OrderQty]) OR UPDATE([UnitPrice])
        -- Insert record into TransactionHistory 
        BEGIN
            INSERT INTO [Production].[TransactionHistory]
                ([ProductID]
                ,[ReferenceOrderID]
                ,[ReferenceOrderLineID]
                ,[TransactionType]
                ,[TransactionDate]
                ,[Quantity]
                ,[ActualCost])
            SELECT 
                inserted.[ProductID]
                ,inserted.[PurchaseOrderID]
                ,inserted.[PurchaseOrderDetailID]
                ,'P'
                ,GETDATE()
                ,inserted.[OrderQty]
                ,inserted.[UnitPrice]
            FROM inserted 
                INNER JOIN [Purchasing].[PurchaseOrderDetail] 
                ON inserted.[PurchaseOrderID] = [Purchasing].[PurchaseOrderDetail].[PurchaseOrderID];

            -- Update SubTotal in PurchaseOrderHeader record. Note that this causes the 
            -- PurchaseOrderHeader trigger to fire which will update the RevisionNumber.
            UPDATE [Purchasing].[PurchaseOrderHeader]
            SET [Purchasing].[PurchaseOrderHeader].[SubTotal] = 
                (SELECT SUM([Purchasing].[PurchaseOrderDetail].[LineTotal])
                    FROM [Purchasing].[PurchaseOrderDetail]
                    WHERE [Purchasing].[PurchaseOrderHeader].[PurchaseOrderID] 
                        = [Purchasing].[PurchaseOrderDetail].[PurchaseOrderID])
            WHERE [Purchasing].[PurchaseOrderHeader].[PurchaseOrderID] 
                IN (SELECT inserted.[PurchaseOrderID] FROM inserted);

            UPDATE [Purchasing].[PurchaseOrderDetail]
            SET [Purchasing].[PurchaseOrderDetail].[ModifiedDate] = GETDATE()
            FROM inserted
            WHERE inserted.[PurchaseOrderID] = [Purchasing].[PurchaseOrderDetail].[PurchaseOrderID]
                AND inserted.[PurchaseOrderDetailID] = [Purchasing].[PurchaseOrderDetail].[PurchaseOrderDetailID];
        END;
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];

        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Objects that depend on Purchasing.PurchaseOrderDetail

triggerPurchasing.iPurchaseOrderDetail
tablePurchasing.PurchaseOrderDetail
triggerPurchasing.uPurchaseOrderDetail

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Purchasing].[PurchaseOrderDetail](
    [PurchaseOrderID] [int] NOT NULL,
    [PurchaseOrderDetailID] [int] IDENTITY(1,1) NOT NULL,
    [DueDate] [datetime] NOT NULL,
    [OrderQty] [smallint] NOT NULL,
    [ProductID] [int] NOT NULL,
    [UnitPrice] [money] NOT NULL,
    [LineTotal]  AS (isnull([OrderQty]*[UnitPrice],(0.00))),
    [ReceivedQty] [decimal](8, 2) NOT NULL,
    [RejectedQty] [decimal](8, 2) NOT NULL,
    [StockedQty]  AS (isnull([ReceivedQty]-[RejectedQty],(0.00))),
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Purchasing.PurchaseOrderHeader

General purchase order information. See PurchaseOrderDetail.

Fields

Field name Data type Nullable Default value Field description
PurchaseOrderIDintPrimary key.
RevisionNumbertinyint((0))Incremental number to track changes to the purchase order over time.
Statustinyint((1))Order current status. 1 = Pending; 2 = Approved; 3 = Rejected; 4 = Complete
EmployeeIDintEmployee who created the purchase order. Foreign key to Employee.EmployeeID.
VendorIDintVendor with whom the purchase order is placed. Foreign key to Vendor.VendorID.
ShipMethodIDintShipping method. Foreign key to ShipMethod.ShipMethodID.
OrderDatedatetime(getdate())Purchase order creation date.
ShipDatedatetimeYesEstimated shipment date from the vendor.
SubTotalmoney((0.00))Purchase order subtotal. Computed as SUM(PurchaseOrderDetail.LineTotal)for the appropriate PurchaseOrderID.
TaxAmtmoney((0.00))Tax amount.
Freightmoney((0.00))Shipping cost.
TotalDuemoneyTotal due to vendor. Computed as Subtotal + TaxAmt + Freight.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_PurchaseOrderHeader_Employee_EmployeeIDEmployeeIDPK_Employee_EmployeeID (HumanResources.Employee) Foreign key constraint referencing Employee.EmployeeID.
FK_PurchaseOrderHeader_Vendor_VendorIDVendorIDPK_Vendor_VendorID (Purchasing.Vendor) Foreign key constraint referencing Vendor.VendorID.
FK_PurchaseOrderHeader_ShipMethod_ShipMethodIDShipMethodIDPK_ShipMethod_ShipMethodID (Purchasing.ShipMethod) Foreign key constraint referencing ShipMethod.ShipMethodID.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Purchasing.PurchaseOrderDetailFK_PurchaseOrderDetail_PurchaseOrderHeader_PurchaseOrderIDPK_PurchaseOrderHeader_PurchaseOrderID

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_PurchaseOrderHeader_EmployeeIDEmployeeIDASCNONCLUSTERED
IX_PurchaseOrderHeader_VendorIDVendorIDASCNONCLUSTERED
PK_PurchaseOrderHeader_PurchaseOrderIDPurchaseOrderIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_PurchaseOrderHeader_StatusStatus([Status]>=(1) AND [Status]<=(4))
CK_PurchaseOrderHeader_ShipDateOrderDate([ShipDate]>=[OrderDate] OR [ShipDate] IS NULL)
CK_PurchaseOrderHeader_ShipDateShipDate([ShipDate]>=[OrderDate] OR [ShipDate] IS NULL)
CK_PurchaseOrderHeader_SubTotalSubTotal([SubTotal]>=(0.00))
CK_PurchaseOrderHeader_TaxAmtTaxAmt([TaxAmt]>=(0.00))
CK_PurchaseOrderHeader_FreightFreight([Freight]>=(0.00))

Triggers

Trigger name:Purchasing.uPurchaseOrderHeader
Description:AFTER UPDATE trigger that updates the RevisionNumber and ModifiedDate columns in the PurchaseOrderHeader table.
Creation date:26 Apr 2006
Trigger type:UPDATE
Trigger active:Yes
Trigger definition

CREATE TRIGGER [Purchasing].[uPurchaseOrderHeader] ON [Purchasing].[PurchaseOrderHeader] 
AFTER UPDATE AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
        -- Update RevisionNumber for modification of any field EXCEPT the Status.
        IF NOT UPDATE([Status])
        BEGIN
            UPDATE [Purchasing].[PurchaseOrderHeader]
            SET [Purchasing].[PurchaseOrderHeader].[RevisionNumber] = 
                [Purchasing].[PurchaseOrderHeader].[RevisionNumber] + 1
            WHERE [Purchasing].[PurchaseOrderHeader].[PurchaseOrderID] IN 
                (SELECT inserted.[PurchaseOrderID] FROM inserted);
        END;
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];

        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Objects that depend on Purchasing.PurchaseOrderHeader

triggerPurchasing.iPurchaseOrderDetail
tablePurchasing.PurchaseOrderHeader
triggerPurchasing.uPurchaseOrderDetail
triggerPurchasing.uPurchaseOrderHeader

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Purchasing].[PurchaseOrderHeader](
    [PurchaseOrderID] [int] IDENTITY(1,1) NOT NULL,
    [RevisionNumber] [tinyint] NOT NULL,
    [Status] [tinyint] NOT NULL,
    [EmployeeID] [int] NOT NULL,
    [VendorID] [int] NOT NULL,
    [ShipMethodID] [int] NOT NULL,
    [OrderDate] [datetime] NOT NULL,
    [ShipDate] [datetime] NULL,
    [SubTotal] [money] NOT NULL,
    [TaxAmt] [money] NOT NULL,
    [Freight] [money] NOT NULL,
    [TotalDue]  AS (isnull(([SubTotal]+[TaxAmt])+[Freight],(0))) PERSISTED NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Purchasing.ShipMethod

Shipping company lookup table.

Fields

Field name Data type Nullable Default value Field description
ShipMethodIDintPrimary key for ShipMethod records.
NameNameShipping company name.
ShipBasemoney((0.00))Minimum shipping charge.
ShipRatemoney((0.00))Shipping charge per pound.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.SalesOrderHeaderFK_SalesOrderHeader_ShipMethod_ShipMethodIDPK_ShipMethod_ShipMethodID
Purchasing.PurchaseOrderHeaderFK_PurchaseOrderHeader_ShipMethod_ShipMethodIDPK_ShipMethod_ShipMethodID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_ShipMethod_NameNameASCYesNONCLUSTERED
AK_ShipMethod_rowguidrowguidASCYesNONCLUSTERED
PK_ShipMethod_ShipMethodIDShipMethodIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_ShipMethod_ShipBaseShipBase([ShipBase]>(0.00))
CK_ShipMethod_ShipRateShipRate([ShipRate]>(0.00))

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Purchasing].[ShipMethod](
    [ShipMethodID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [ShipBase] [money] NOT NULL,
    [ShipRate] [money] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Purchasing.Vendor

Companies from whom Adventure Works Cycles purchases parts or other goods.

Fields

Field name Data type Nullable Default value Field description
VendorIDintPrimary key for Vendor records.
AccountNumberAccountNumberVendor account (identification) number.
NameNameCompany name.
CreditRatingtinyint1 = Superior, 2 = Excellent, 3 = Above average, 4 = Average, 5 = Below average
PreferredVendorStatusFlag((1))0 = Do not use if another vendor is available. 1 = Preferred over other vendors supplying the same product.
ActiveFlagFlag((1))0 = Vendor no longer used. 1 = Vendor is actively used.
PurchasingWebServiceURLnvarchar (1024) YesVendor URL.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Purchasing.ProductVendorFK_ProductVendor_Vendor_VendorIDPK_Vendor_VendorID
Purchasing.PurchaseOrderHeaderFK_PurchaseOrderHeader_Vendor_VendorIDPK_Vendor_VendorID
Purchasing.VendorAddressFK_VendorAddress_Vendor_VendorIDPK_Vendor_VendorID
Purchasing.VendorContactFK_VendorContact_Vendor_VendorIDPK_Vendor_VendorID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Vendor_AccountNumberAccountNumberASCYesNONCLUSTERED
PK_Vendor_VendorIDVendorIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_Vendor_CreditRatingCreditRating([CreditRating]>=(1) AND [CreditRating]<=(5))

Triggers

Trigger name:Purchasing.dVendor
Description:INSTEAD OF DELETE trigger which keeps Vendors from being deleted.
Creation date:26 Apr 2006
Trigger type:INSTEAD OF DELETE
Trigger active:Yes
Trigger definition

CREATE TRIGGER [Purchasing].[dVendor] ON [Purchasing].[Vendor] 
INSTEAD OF DELETE NOT FOR REPLICATION AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
        DECLARE @DeleteCount int;

        SELECT @DeleteCount = COUNT(*) FROM deleted;
        IF @DeleteCount > 0 
        BEGIN
            RAISERROR
                (N'Vendors cannot be deleted. They can only be marked as not active.', -- Message
                10, -- Severity.
                1); -- State.

        -- Rollback any active or uncommittable transactions
            IF @@TRANCOUNT > 0
            BEGIN
                ROLLBACK TRANSACTION;
            END
        END;
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];

        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Objects that depend on Purchasing.Vendor

viewPurchasing.vVendor

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Purchasing].[Vendor](
    [VendorID] [int] IDENTITY(1,1) NOT NULL,
    [AccountNumber] [dbo].[AccountNumber] NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [CreditRating] [tinyint] NOT NULL,
    [PreferredVendorStatus] [dbo].[Flag] NOT NULL,
    [ActiveFlag] [dbo].[Flag] NOT NULL,
    [PurchasingWebServiceURL] [nvarchar](1024) COLLATE Latin1_General_CS_AS NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Purchasing.VendorAddress

Cross-reference mapping vendors and addresses.

Fields

Field name Data type Nullable Default value Field description
VendorIDintPrimary key. Foreign key to Vendor.VendorID.
AddressIDintPrimary key. Foreign key to Address.AddressID.
AddressTypeIDintAddress type. Foreign key to AddressType.AddressTypeID.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_VendorAddress_Vendor_VendorIDVendorIDPK_Vendor_VendorID (Purchasing.Vendor) Foreign key constraint referencing Vendor.VendorID.
FK_VendorAddress_Address_AddressIDAddressIDPK_Address_AddressID (Person.Address) Foreign key constraint referencing Address.AddressID.
FK_VendorAddress_AddressType_AddressTypeIDAddressTypeIDPK_AddressType_AddressTypeID (Person.AddressType) Foreign key constraint referencing AddressType.AddressTypeID.

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_VendorAddress_AddressIDAddressIDASCNONCLUSTERED
PK_VendorAddress_VendorID_AddressIDVendorIDASCYesCLUSTERED
PK_VendorAddress_VendorID_AddressIDAddressIDASCYesCLUSTERED

Objects that depend on Purchasing.VendorAddress

viewPurchasing.vVendor

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Purchasing].[VendorAddress](
    [VendorID] [int] NOT NULL,
    [AddressID] [int] NOT NULL,
    [AddressTypeID] [int] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Purchasing.VendorContact

Cross-reference table mapping vendors and their employees.

Fields

Field name Data type Nullable Default value Field description
VendorIDintPrimary key.
ContactIDintContact (Vendor employee) identification number. Foreign key to Contact.ContactID.
ContactTypeIDintContact type such as sales manager, or sales agent.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_VendorContact_Vendor_VendorIDVendorIDPK_Vendor_VendorID (Purchasing.Vendor) Foreign key constraint referencing Vendor.VendorID.
FK_VendorContact_Contact_ContactIDContactIDPK_Contact_ContactID (Person.Contact) Foreign key constraint referencing Contact.ContactID.
FK_VendorContact_ContactType_ContactTypeIDContactTypeIDPK_ContactType_ContactTypeID (Person.ContactType) Foreign key constraint referencing ContactType.ContactTypeID.

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_VendorContact_ContactIDContactIDASCNONCLUSTERED
IX_VendorContact_ContactTypeIDContactTypeIDASCNONCLUSTERED
PK_VendorContact_VendorID_ContactIDVendorIDASCYesCLUSTERED
PK_VendorContact_VendorID_ContactIDContactIDASCYesCLUSTERED

Objects that depend on Purchasing.VendorContact

viewPurchasing.vVendor

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Purchasing].[VendorContact](
    [VendorID] [int] NOT NULL,
    [ContactID] [int] NOT NULL,
    [ContactTypeID] [int] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.ContactCreditCard

Cross-reference table mapping customers in the Contact table to their credit card information in the CreditCard table.

Fields

Field name Data type Nullable Default value Field description
ContactIDintCustomer identification number. Foreign key to Contact.ContactID.
CreditCardIDintCredit card identification number. Foreign key to CreditCard.CreditCardID.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_ContactCreditCard_Contact_ContactIDContactIDPK_Contact_ContactID (Person.Contact) Foreign key constraint referencing Contact.ContactID.
FK_ContactCreditCard_CreditCard_CreditCardIDCreditCardIDPK_CreditCard_CreditCardID (Sales.CreditCard) Foreign key constraint referencing CreditCard.CreditCardID.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_ContactCreditCard_ContactID_CreditCardIDContactIDASCYesCLUSTERED
PK_ContactCreditCard_ContactID_CreditCardIDCreditCardIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[ContactCreditCard](
    [ContactID] [int] NOT NULL,
    [CreditCardID] [int] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.CountryRegionCurrency

Cross-reference table mapping ISO currency codes to a country or region.

Fields

Field name Data type Nullable Default value Field description
CountryRegionCodenvarchar (3) ISO code for countries and regions. Foreign key to CountryRegion.CountryRegionCode.
CurrencyCodenchar (3) ISO standard currency code. Foreign key to Currency.CurrencyCode.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_CountryRegionCurrency_CountryRegion_CountryRegionCodeCountryRegionCodePK_CountryRegion_CountryRegionCode (Person.CountryRegion) Foreign key constraint referencing CountryRegion.CountryRegionCode.
FK_CountryRegionCurrency_Currency_CurrencyCodeCurrencyCodePK_Currency_CurrencyCode (Sales.Currency) Foreign key constraint referencing Currency.CurrencyCode.

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_CountryRegionCurrency_CurrencyCodeCurrencyCodeASCNONCLUSTERED
PK_CountryRegionCurrency_CountryRegionCode_CurrencyCodeCountryRegionCodeASCYesCLUSTERED
PK_CountryRegionCurrency_CountryRegionCode_CurrencyCodeCurrencyCodeASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[CountryRegionCurrency](
    [CountryRegionCode] [nvarchar](3) COLLATE Latin1_General_CS_AS NOT NULL,
    [CurrencyCode] [nchar](3) COLLATE Latin1_General_CS_AS NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.CreditCard

Customer credit card information.

Fields

Field name Data type Nullable Default value Field description
CreditCardIDintPrimary key for CreditCard records.
CardTypenvarchar (50) Credit card name.
CardNumbernvarchar (25) Credit card number.
ExpMonthtinyintCredit card expiration month.
ExpYearsmallintCredit card expiration year.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.SalesOrderHeaderFK_SalesOrderHeader_CreditCard_CreditCardIDPK_CreditCard_CreditCardID
Sales.ContactCreditCardFK_ContactCreditCard_CreditCard_CreditCardIDPK_CreditCard_CreditCardID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_CreditCard_CardNumberCardNumberASCYesNONCLUSTERED
PK_CreditCard_CreditCardIDCreditCardIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[CreditCard](
    [CreditCardID] [int] IDENTITY(1,1) NOT NULL,
    [CardType] [nvarchar](50) COLLATE Latin1_General_CS_AS NOT NULL,
    [CardNumber] [nvarchar](25) COLLATE Latin1_General_CS_AS NOT NULL,
    [ExpMonth] [tinyint] NOT NULL,
    [ExpYear] [smallint] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.Currency

Lookup table containing standard ISO currencies.

Fields

Field name Data type Nullable Default value Field description
CurrencyCodenchar (3) The ISO code for the Currency.
NameNameCurrency name.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.CountryRegionCurrencyFK_CountryRegionCurrency_Currency_CurrencyCodePK_Currency_CurrencyCode
Sales.CurrencyRateFK_CurrencyRate_Currency_FromCurrencyCodePK_Currency_CurrencyCode
Sales.CurrencyRateFK_CurrencyRate_Currency_ToCurrencyCodePK_Currency_CurrencyCode

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Currency_NameNameASCYesNONCLUSTERED
PK_Currency_CurrencyCodeCurrencyCodeASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[Currency](
    [CurrencyCode] [nchar](3) COLLATE Latin1_General_CS_AS NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.CurrencyRate

Currency exchange rates.

Fields

Field name Data type Nullable Default value Field description
CurrencyRateIDintPrimary key for CurrencyRate records.
CurrencyRateDatedatetimeDate and time the exchange rate was obtained.
FromCurrencyCodenchar (3) Exchange rate was converted from this currency code.
ToCurrencyCodenchar (3) Exchange rate was converted to this currency code.
AverageRatemoneyAverage exchange rate for the day.
EndOfDayRatemoneyFinal exchange rate for the day.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_CurrencyRate_Currency_FromCurrencyCodeFromCurrencyCodePK_Currency_CurrencyCode (Sales.Currency) Foreign key constraint referencing Currency.FromCurrencyCode.
FK_CurrencyRate_Currency_ToCurrencyCodeToCurrencyCodePK_Currency_CurrencyCode (Sales.Currency) Foreign key constraint referencing Currency.ToCurrencyCode.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.SalesOrderHeaderFK_SalesOrderHeader_CurrencyRate_CurrencyRateIDPK_CurrencyRate_CurrencyRateID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_CurrencyRate_CurrencyRateDate_FromCurrencyCode_ToCurrencyCodeCurrencyRateDateASCYesNONCLUSTERED
AK_CurrencyRate_CurrencyRateDate_FromCurrencyCode_ToCurrencyCodeFromCurrencyCodeASCYesNONCLUSTERED
AK_CurrencyRate_CurrencyRateDate_FromCurrencyCode_ToCurrencyCodeToCurrencyCodeASCYesNONCLUSTERED
PK_CurrencyRate_CurrencyRateIDCurrencyRateIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[CurrencyRate](
    [CurrencyRateID] [int] IDENTITY(1,1) NOT NULL,
    [CurrencyRateDate] [datetime] NOT NULL,
    [FromCurrencyCode] [nchar](3) COLLATE Latin1_General_CS_AS NOT NULL,
    [ToCurrencyCode] [nchar](3) COLLATE Latin1_General_CS_AS NOT NULL,
    [AverageRate] [money] NOT NULL,
    [EndOfDayRate] [money] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.Customer

Current customer information. Also see the Individual and Store tables.

Fields

Field name Data type Nullable Default value Field description
CustomerIDintPrimary key for Customer records.
TerritoryIDintYesID of the territory in which the customer is located. Foreign key to SalesTerritory.SalesTerritoryID.
AccountNumbervarchar (10) Unique number identifying the customer assigned by the accounting system.
CustomerTypenchar (1) Customer type: I = Individual, S = Store
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_Customer_SalesTerritory_TerritoryIDTerritoryIDPK_SalesTerritory_TerritoryID (Sales.SalesTerritory) Foreign key constraint referencing SalesTerritory.TerritoryID.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.StoreFK_Store_Customer_CustomerIDPK_Customer_CustomerID
Sales.IndividualFK_Individual_Customer_CustomerIDPK_Customer_CustomerID
Sales.SalesOrderHeaderFK_SalesOrderHeader_Customer_CustomerIDPK_Customer_CustomerID
Sales.CustomerAddressFK_CustomerAddress_Customer_CustomerIDPK_Customer_CustomerID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Customer_AccountNumberAccountNumberASCYesNONCLUSTERED
AK_Customer_rowguidrowguidASCYesNONCLUSTERED
IX_Customer_TerritoryIDTerritoryIDASCNONCLUSTERED
PK_Customer_CustomerIDCustomerIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_Customer_CustomerTypeCustomerType(upper([CustomerType])='I' OR upper([CustomerType])='S')

Objects that depend on Sales.Customer

tableSales.Customer
viewSales.vIndividualCustomer
viewSales.vStoreWithDemographics

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
CREATE TABLE [Sales].[Customer](
    [CustomerID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    [TerritoryID] [int] NULL,
    [AccountNumber]  AS (isnull('AW'+[dbo].[ufnLeadingZeros]([CustomerID]),'')),
    [CustomerType] [nchar](1) COLLATE Latin1_General_CS_AS NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.CustomerAddress

Cross-reference table mapping customers to their address(es).

Fields

Field name Data type Nullable Default value Field description
CustomerIDintPrimary key. Foreign key to Customer.CustomerID.
AddressIDintPrimary key. Foreign key to Address.AddressID.
AddressTypeIDintAddress type. Foreign key to AddressType.AddressTypeID.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_CustomerAddress_Customer_CustomerIDCustomerIDPK_Customer_CustomerID (Sales.Customer) Foreign key constraint referencing Customer.CustomerID.
FK_CustomerAddress_Address_AddressIDAddressIDPK_Address_AddressID (Person.Address) Foreign key constraint referencing Address.AddressID.
FK_CustomerAddress_AddressType_AddressTypeIDAddressTypeIDPK_AddressType_AddressTypeID (Person.AddressType) Foreign key constraint referencing AddressType.AddressTypeID.

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_CustomerAddress_rowguidrowguidASCYesNONCLUSTERED
PK_CustomerAddress_CustomerID_AddressIDCustomerIDASCYesCLUSTERED
PK_CustomerAddress_CustomerID_AddressIDAddressIDASCYesCLUSTERED

Objects that depend on Sales.CustomerAddress

viewSales.vIndividualCustomer
viewSales.vStoreWithDemographics

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[CustomerAddress](
    [CustomerID] [int] NOT NULL,
    [AddressID] [int] NOT NULL,
    [AddressTypeID] [int] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.Individual

Demographic data about customers that purchase Adventure Works products online.

Fields

Field name Data type Nullable Default value Field description
CustomerIDintUnique customer identification number. Foreign key to Customer.CustomerID.
ContactIDintIdentifies the customer in the Contact table. Foreign key to Contact.ContactID.
DemographicsxmlYesPersonal information such as hobbies, and income collected from online shoppers. Used for sales analysis.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_Individual_Customer_CustomerIDCustomerIDPK_Customer_CustomerID (Sales.Customer) Foreign key constraint referencing Customer.CustomerID.
FK_Individual_Contact_ContactIDContactIDPK_Contact_ContactID (Person.Contact) Foreign key constraint referencing Contact.ContactID.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_Individual_CustomerIDCustomerIDASCYesCLUSTERED
PXML_Individual_DemographicsDemographicsASCXML
XMLPATH_Individual_DemographicsDemographicsASCXML
XMLPROPERTY_Individual_DemographicsDemographicsASCXML
XMLVALUE_Individual_DemographicsDemographicsASCXML

Triggers

Trigger name:Sales.iuIndividual
Description:AFTER INSERT, UPDATE trigger inserting Individual only if the Customer does not exist in the Store table and setting the ModifiedDate column in the Individual table to the current date.
Creation date:26 Apr 2006
Trigger type:INSERT
Trigger active:Yes
Trigger definition

CREATE TRIGGER [Sales].[iuIndividual] ON [Sales].[Individual] 
AFTER INSERT, UPDATE NOT FOR REPLICATION AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    -- Only allow the Customer to be a Store OR Individual
    IF EXISTS (SELECT * FROM inserted INNER JOIN [Sales].[Store] 
        ON inserted.[CustomerID] = [Sales].[Store].[CustomerID]) 
    BEGIN
        -- Rollback any active or uncommittable transactions
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END
    END;

    IF UPDATE([CustomerID]) OR UPDATE([Demographics]) 
    BEGIN
        UPDATE [Sales].[Individual] 
        SET [Sales].[Individual].[Demographics] = N'<IndividualSurvey xmlns="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"> 
            <TotalPurchaseYTD>0.00</TotalPurchaseYTD> 
            </IndividualSurvey>' 
        FROM inserted 
        WHERE [Sales].[Individual].[CustomerID] = inserted.[CustomerID] 
            AND inserted.[Demographics] IS NULL;
        
        UPDATE [Sales].[Individual] 
        SET [Demographics].modify(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
            insert <TotalPurchaseYTD>0.00</TotalPurchaseYTD> 
            as first 
            into (/IndividualSurvey)[1]') 
        FROM inserted 
        WHERE [Sales].[Individual].[CustomerID] = inserted.[CustomerID] 
            AND inserted.[Demographics] IS NOT NULL 
            AND inserted.[Demographics].exist(N'declare default element namespace 
                "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
                /IndividualSurvey/TotalPurchaseYTD') <> 1;
    END;
END;

CREATE TRIGGER [Sales].[iuIndividual] ON [Sales].[Individual] 
AFTER INSERT, UPDATE NOT FOR REPLICATION AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    -- Only allow the Customer to be a Store OR Individual
    IF EXISTS (SELECT * FROM inserted INNER JOIN [Sales].[Store] 
        ON inserted.[CustomerID] = [Sales].[Store].[CustomerID]) 
    BEGIN
        -- Rollback any active or uncommittable transactions
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END
    END;

    IF UPDATE([CustomerID]) OR UPDATE([Demographics]) 
    BEGIN
        UPDATE [Sales].[Individual] 
        SET [Sales].[Individual].[Demographics] = N'<IndividualSurvey xmlns="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"> 
            <TotalPurchaseYTD>0.00</TotalPurchaseYTD> 
            </IndividualSurvey>' 
        FROM inserted 
        WHERE [Sales].[Individual].[CustomerID] = inserted.[CustomerID] 
            AND inserted.[Demographics] IS NULL;
        
        UPDATE [Sales].[Individual] 
        SET [Demographics].modify(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
            insert <TotalPurchaseYTD>0.00</TotalPurchaseYTD> 
            as first 
            into (/IndividualSurvey)[1]') 
        FROM inserted 
        WHERE [Sales].[Individual].[CustomerID] = inserted.[CustomerID] 
            AND inserted.[Demographics] IS NOT NULL 
            AND inserted.[Demographics].exist(N'declare default element namespace 
                "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
                /IndividualSurvey/TotalPurchaseYTD') <> 1;
    END;
END;

Objects that depend on Sales.Individual

triggerSales.iduSalesOrderDetail
triggerSales.iStore
triggerSales.iuIndividual
viewSales.vIndividualCustomer
viewSales.vIndividualDemographics

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[Individual](
    [CustomerID] [int] NOT NULL,
    [ContactID] [int] NOT NULL,
    [Demographics] [xml](CONTENT [Sales].[IndividualSurveySchemaCollection]) NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.SalesOrderDetail

Individual products associated with a specific sales order. See SalesOrderHeader.

Fields

Field name Data type Nullable Default value Field description
SalesOrderIDintPrimary key. Foreign key to SalesOrderHeader.SalesOrderID.
SalesOrderDetailIDintPrimary key. One incremental unique number per product sold.
CarrierTrackingNumbernvarchar (25) YesShipment tracking number supplied by the shipper.
OrderQtysmallintQuantity ordered per product.
ProductIDintProduct sold to customer. Foreign key to Product.ProductID.
SpecialOfferIDintPromotional code. Foreign key to SpecialOffer.SpecialOfferID.
UnitPricemoneySelling price of a single product.
UnitPriceDiscountmoney((0.0))Discount amount.
LineTotalnumeric (38.6) Per product subtotal. Computed as UnitPrice * (1 - UnitPriceDiscount) * OrderQty.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_SalesOrderDetail_SalesOrderHeader_SalesOrderIDSalesOrderIDPK_SalesOrderHeader_SalesOrderID (Sales.SalesOrderHeader) Foreign key constraint referencing SalesOrderHeader.PurchaseOrderID.
FK_SalesOrderDetail_SpecialOfferProduct_SpecialOfferIDProductIDProductIDPK_SpecialOfferProduct_SpecialOfferID_ProductID (Sales.SpecialOfferProduct) Foreign key constraint referencing SpecialOfferProduct.SpecialOfferIDProductID.
FK_SalesOrderDetail_SpecialOfferProduct_SpecialOfferIDProductIDSpecialOfferIDPK_SpecialOfferProduct_SpecialOfferID_ProductID (Sales.SpecialOfferProduct) Foreign key constraint referencing SpecialOfferProduct.SpecialOfferIDProductID.

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_SalesOrderDetail_rowguidrowguidASCYesNONCLUSTERED
IX_SalesOrderDetail_ProductIDProductIDASCNONCLUSTERED
PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailIDSalesOrderIDASCYesCLUSTERED
PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailIDSalesOrderDetailIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_SalesOrderDetail_OrderQtyOrderQty([OrderQty]>(0))
CK_SalesOrderDetail_UnitPriceUnitPrice([UnitPrice]>=(0.00))
CK_SalesOrderDetail_UnitPriceDiscountUnitPriceDiscount([UnitPriceDiscount]>=(0.00))

Triggers

Trigger name:Sales.iduSalesOrderDetail
Description:AFTER INSERT, DELETE, UPDATE trigger that inserts a row in the TransactionHistory table, updates ModifiedDate in SalesOrderDetail and updates the SalesOrderHeader.SubTotal column.
Creation date:26 Apr 2006
Trigger type:INSERT
Trigger active:Yes
Trigger definition

CREATE TRIGGER [Sales].[iduSalesOrderDetail] ON [Sales].[SalesOrderDetail] 
AFTER INSERT, DELETE, UPDATE AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
        -- If inserting or updating these columns
        IF UPDATE([ProductID]) OR UPDATE([OrderQty]) OR UPDATE([UnitPrice]) OR UPDATE([UnitPriceDiscount]) 
        -- Insert record into TransactionHistory
        BEGIN
            INSERT INTO [Production].[TransactionHistory]
                ([ProductID]
                ,[ReferenceOrderID]
                ,[ReferenceOrderLineID]
                ,[TransactionType]
                ,[TransactionDate]
                ,[Quantity]
                ,[ActualCost])
            SELECT 
                inserted.[ProductID]
                ,inserted.[SalesOrderID]
                ,inserted.[SalesOrderDetailID]
                ,'S'
                ,GETDATE()
                ,inserted.[OrderQty]
                ,inserted.[UnitPrice]
            FROM inserted 
                INNER JOIN [Sales].[SalesOrderHeader] 
                ON inserted.[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID];

            UPDATE [Sales].[Individual] 
            SET [Demographics].modify('declare default element namespace 
                "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
                replace value of (/IndividualSurvey/TotalPurchaseYTD)[1] 
                with data(/IndividualSurvey/TotalPurchaseYTD)[1] + sql:column ("inserted.LineTotal")') 
            FROM inserted 
                INNER JOIN [Sales].[SalesOrderHeader] 
                ON inserted.[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] 
            WHERE [Sales].[SalesOrderHeader].[CustomerID] = [Sales].[Individual].[CustomerID];
        END;

        -- Update SubTotal in SalesOrderHeader record. Note that this causes the 
        -- SalesOrderHeader trigger to fire which will update the RevisionNumber.
        UPDATE [Sales].[SalesOrderHeader]
        SET [Sales].[SalesOrderHeader].[SubTotal] = 
            (SELECT SUM([Sales].[SalesOrderDetail].[LineTotal])
                FROM [Sales].[SalesOrderDetail]
                WHERE [Sales].[SalesOrderHeader].[SalesOrderID] = [Sales].[SalesOrderDetail].[SalesOrderID])
        WHERE [Sales].[SalesOrderHeader].[SalesOrderID] IN (SELECT inserted.[SalesOrderID] FROM inserted);

        UPDATE [Sales].[Individual] 
        SET [Demographics].modify('declare default element namespace 
            "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
            replace value of (/IndividualSurvey/TotalPurchaseYTD)[1] 
            with data(/IndividualSurvey/TotalPurchaseYTD)[1] - sql:column("deleted.LineTotal")') 
        FROM deleted 
            INNER JOIN [Sales].[SalesOrderHeader] 
            ON deleted.[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] 
        WHERE [Sales].[SalesOrderHeader].[CustomerID] = [Sales].[Individual].[CustomerID];
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];

        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

CREATE TRIGGER [Sales].[iduSalesOrderDetail] ON [Sales].[SalesOrderDetail] 
AFTER INSERT, DELETE, UPDATE AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
        -- If inserting or updating these columns
        IF UPDATE([ProductID]) OR UPDATE([OrderQty]) OR UPDATE([UnitPrice]) OR UPDATE([UnitPriceDiscount]) 
        -- Insert record into TransactionHistory
        BEGIN
            INSERT INTO [Production].[TransactionHistory]
                ([ProductID]
                ,[ReferenceOrderID]
                ,[ReferenceOrderLineID]
                ,[TransactionType]
                ,[TransactionDate]
                ,[Quantity]
                ,[ActualCost])
            SELECT 
                inserted.[ProductID]
                ,inserted.[SalesOrderID]
                ,inserted.[SalesOrderDetailID]
                ,'S'
                ,GETDATE()
                ,inserted.[OrderQty]
                ,inserted.[UnitPrice]
            FROM inserted 
                INNER JOIN [Sales].[SalesOrderHeader] 
                ON inserted.[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID];

            UPDATE [Sales].[Individual] 
            SET [Demographics].modify('declare default element namespace 
                "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
                replace value of (/IndividualSurvey/TotalPurchaseYTD)[1] 
                with data(/IndividualSurvey/TotalPurchaseYTD)[1] + sql:column ("inserted.LineTotal")') 
            FROM inserted 
                INNER JOIN [Sales].[SalesOrderHeader] 
                ON inserted.[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] 
            WHERE [Sales].[SalesOrderHeader].[CustomerID] = [Sales].[Individual].[CustomerID];
        END;

        -- Update SubTotal in SalesOrderHeader record. Note that this causes the 
        -- SalesOrderHeader trigger to fire which will update the RevisionNumber.
        UPDATE [Sales].[SalesOrderHeader]
        SET [Sales].[SalesOrderHeader].[SubTotal] = 
            (SELECT SUM([Sales].[SalesOrderDetail].[LineTotal])
                FROM [Sales].[SalesOrderDetail]
                WHERE [Sales].[SalesOrderHeader].[SalesOrderID] = [Sales].[SalesOrderDetail].[SalesOrderID])
        WHERE [Sales].[SalesOrderHeader].[SalesOrderID] IN (SELECT inserted.[SalesOrderID] FROM inserted);

        UPDATE [Sales].[Individual] 
        SET [Demographics].modify('declare default element namespace 
            "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
            replace value of (/IndividualSurvey/TotalPurchaseYTD)[1] 
            with data(/IndividualSurvey/TotalPurchaseYTD)[1] - sql:column("deleted.LineTotal")') 
        FROM deleted 
            INNER JOIN [Sales].[SalesOrderHeader] 
            ON deleted.[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] 
        WHERE [Sales].[SalesOrderHeader].[CustomerID] = [Sales].[Individual].[CustomerID];
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];

        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

CREATE TRIGGER [Sales].[iduSalesOrderDetail] ON [Sales].[SalesOrderDetail] 
AFTER INSERT, DELETE, UPDATE AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
        -- If inserting or updating these columns
        IF UPDATE([ProductID]) OR UPDATE([OrderQty]) OR UPDATE([UnitPrice]) OR UPDATE([UnitPriceDiscount]) 
        -- Insert record into TransactionHistory
        BEGIN
            INSERT INTO [Production].[TransactionHistory]
                ([ProductID]
                ,[ReferenceOrderID]
                ,[ReferenceOrderLineID]
                ,[TransactionType]
                ,[TransactionDate]
                ,[Quantity]
                ,[ActualCost])
            SELECT 
                inserted.[ProductID]
                ,inserted.[SalesOrderID]
                ,inserted.[SalesOrderDetailID]
                ,'S'
                ,GETDATE()
                ,inserted.[OrderQty]
                ,inserted.[UnitPrice]
            FROM inserted 
                INNER JOIN [Sales].[SalesOrderHeader] 
                ON inserted.[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID];

            UPDATE [Sales].[Individual] 
            SET [Demographics].modify('declare default element namespace 
                "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
                replace value of (/IndividualSurvey/TotalPurchaseYTD)[1] 
                with data(/IndividualSurvey/TotalPurchaseYTD)[1] + sql:column ("inserted.LineTotal")') 
            FROM inserted 
                INNER JOIN [Sales].[SalesOrderHeader] 
                ON inserted.[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] 
            WHERE [Sales].[SalesOrderHeader].[CustomerID] = [Sales].[Individual].[CustomerID];
        END;

        -- Update SubTotal in SalesOrderHeader record. Note that this causes the 
        -- SalesOrderHeader trigger to fire which will update the RevisionNumber.
        UPDATE [Sales].[SalesOrderHeader]
        SET [Sales].[SalesOrderHeader].[SubTotal] = 
            (SELECT SUM([Sales].[SalesOrderDetail].[LineTotal])
                FROM [Sales].[SalesOrderDetail]
                WHERE [Sales].[SalesOrderHeader].[SalesOrderID] = [Sales].[SalesOrderDetail].[SalesOrderID])
        WHERE [Sales].[SalesOrderHeader].[SalesOrderID] IN (SELECT inserted.[SalesOrderID] FROM inserted);

        UPDATE [Sales].[Individual] 
        SET [Demographics].modify('declare default element namespace 
            "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
            replace value of (/IndividualSurvey/TotalPurchaseYTD)[1] 
            with data(/IndividualSurvey/TotalPurchaseYTD)[1] - sql:column("deleted.LineTotal")') 
        FROM deleted 
            INNER JOIN [Sales].[SalesOrderHeader] 
            ON deleted.[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] 
        WHERE [Sales].[SalesOrderHeader].[CustomerID] = [Sales].[Individual].[CustomerID];
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];

        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Objects that depend on Sales.SalesOrderDetail

triggerSales.iduSalesOrderDetail
tableSales.SalesOrderDetail

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[SalesOrderDetail](
    [SalesOrderID] [int] NOT NULL,
    [SalesOrderDetailID] [int] IDENTITY(1,1) NOT NULL,
    [CarrierTrackingNumber] [nvarchar](25) COLLATE Latin1_General_CS_AS NULL,
    [OrderQty] [smallint] NOT NULL,
    [ProductID] [int] NOT NULL,
    [SpecialOfferID] [int] NOT NULL,
    [UnitPrice] [money] NOT NULL,
    [UnitPriceDiscount] [money] NOT NULL,
    [LineTotal]  AS (isnull(([UnitPrice]*((1.0)-[UnitPriceDiscount]))*[OrderQty],(0.0))),
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.SalesOrderHeader

General sales order information.

Fields

Field name Data type Nullable Default value Field description
SalesOrderIDintPrimary key.
RevisionNumbertinyint((0))Incremental number to track changes to the sales order over time.
OrderDatedatetime(getdate())Dates the sales order was created.
DueDatedatetimeDate the order is due to the customer.
ShipDatedatetimeYesDate the order was shipped to the customer.
Statustinyint((1))Order current status. 1 = In process; 2 = Approved; 3 = Backordered; 4 = Rejected; 5 = Shipped; 6 = Cancelled
OnlineOrderFlagFlag((1))0 = Order placed by sales person. 1 = Order placed online by customer.
SalesOrderNumbernvarchar (25) Unique sales order identification number.
PurchaseOrderNumberOrderNumberYesCustomer purchase order number reference.
AccountNumberAccountNumberYesFinancial accounting number reference.
CustomerIDintCustomer identification number. Foreign key to Customer.CustomerID.
ContactIDintCustomer contact identification number. Foreign key to Contact.ContactID.
SalesPersonIDintYesSales person who created the sales order. Foreign key to SalesPerson.SalePersonID.
TerritoryIDintYesTerritory in which the sale was made. Foreign key to SalesTerritory.SalesTerritoryID.
BillToAddressIDintCustomer billing address. Foreign key to Address.AddressID.
ShipToAddressIDintCustomer shipping address. Foreign key to Address.AddressID.
ShipMethodIDintShipping method. Foreign key to ShipMethod.ShipMethodID.
CreditCardIDintYesCredit card identification number. Foreign key to CreditCard.CreditCardID.
CreditCardApprovalCodevarchar (15) YesApproval code provided by the credit card company.
CurrencyRateIDintYesCurrency exchange rate used. Foreign key to CurrencyRate.CurrencyRateID.
SubTotalmoney((0.00))Sales subtotal. Computed as SUM(SalesOrderDetail.LineTotal)for the appropriate SalesOrderID.
TaxAmtmoney((0.00))Tax amount.
Freightmoney((0.00))Shipping cost.
TotalDuemoneyTotal due from customer. Computed as Subtotal + TaxAmt + Freight.
Commentnvarchar (128) YesSales representative comments.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_SalesOrderHeader_Customer_CustomerIDCustomerIDPK_Customer_CustomerID (Sales.Customer) Foreign key constraint referencing Customer.CustomerID.
FK_SalesOrderHeader_Contact_ContactIDContactIDPK_Contact_ContactID (Person.Contact) Foreign key constraint referencing Contact.ContactID.
FK_SalesOrderHeader_SalesPerson_SalesPersonIDSalesPersonIDPK_SalesPerson_SalesPersonID (Sales.SalesPerson) Foreign key constraint referencing SalesPerson.SalesPersonID.
FK_SalesOrderHeader_SalesTerritory_TerritoryIDTerritoryIDPK_SalesTerritory_TerritoryID (Sales.SalesTerritory) Foreign key constraint referencing SalesTerritory.TerritoryID.
FK_SalesOrderHeader_Address_BillToAddressIDBillToAddressIDPK_Address_AddressID (Person.Address) Foreign key constraint referencing Address.AddressID.
FK_SalesOrderHeader_Address_ShipToAddressIDShipToAddressIDPK_Address_AddressID (Person.Address) Foreign key constraint referencing Address.AddressID.
FK_SalesOrderHeader_ShipMethod_ShipMethodIDShipMethodIDPK_ShipMethod_ShipMethodID (Purchasing.ShipMethod) Foreign key constraint referencing ShipMethod.ShipMethodID.
FK_SalesOrderHeader_CreditCard_CreditCardIDCreditCardIDPK_CreditCard_CreditCardID (Sales.CreditCard) Foreign key constraint referencing CreditCard.CreditCardID.
FK_SalesOrderHeader_CurrencyRate_CurrencyRateIDCurrencyRateIDPK_CurrencyRate_CurrencyRateID (Sales.CurrencyRate) Foreign key constraint referencing CurrencyRate.CurrencyRateID.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.SalesOrderDetailFK_SalesOrderDetail_SalesOrderHeader_SalesOrderIDPK_SalesOrderHeader_SalesOrderID
Sales.SalesOrderHeaderSalesReasonFK_SalesOrderHeaderSalesReason_SalesOrderHeader_SalesOrderIDPK_SalesOrderHeader_SalesOrderID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_SalesOrderHeader_rowguidrowguidASCYesNONCLUSTERED
AK_SalesOrderHeader_SalesOrderNumberSalesOrderNumberASCYesNONCLUSTERED
IX_SalesOrderHeader_CustomerIDCustomerIDASCNONCLUSTERED
IX_SalesOrderHeader_SalesPersonIDSalesPersonIDASCNONCLUSTERED
PK_SalesOrderHeader_SalesOrderIDSalesOrderIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_SalesOrderHeader_StatusStatus([Status]>=(0) AND [Status]<=(8))
CK_SalesOrderHeader_DueDateOrderDate([DueDate]>=[OrderDate])
CK_SalesOrderHeader_DueDateDueDate([DueDate]>=[OrderDate])
CK_SalesOrderHeader_ShipDateOrderDate([ShipDate]>=[OrderDate] OR [ShipDate] IS NULL)
CK_SalesOrderHeader_ShipDateShipDate([ShipDate]>=[OrderDate] OR [ShipDate] IS NULL)
CK_SalesOrderHeader_SubTotalSubTotal([SubTotal]>=(0.00))
CK_SalesOrderHeader_TaxAmtTaxAmt([TaxAmt]>=(0.00))
CK_SalesOrderHeader_FreightFreight([Freight]>=(0.00))

Triggers

Trigger name:Sales.uSalesOrderHeader
Description:AFTER UPDATE trigger that updates the RevisionNumber and ModifiedDate columns in the SalesOrderHeader table.Updates the SalesYTD column in the SalesPerson and SalesTerritory tables.
Creation date:26 Apr 2006
Trigger type:UPDATE
Trigger active:Yes
Trigger definition

CREATE TRIGGER [Sales].[uSalesOrderHeader] ON [Sales].[SalesOrderHeader] 
AFTER UPDATE NOT FOR REPLICATION AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
        -- Update RevisionNumber for modification of any field EXCEPT the Status.
        IF NOT UPDATE([Status])
        BEGIN
            UPDATE [Sales].[SalesOrderHeader]
            SET [Sales].[SalesOrderHeader].[RevisionNumber] = 
                [Sales].[SalesOrderHeader].[RevisionNumber] + 1
            WHERE [Sales].[SalesOrderHeader].[SalesOrderID] IN 
                (SELECT inserted.[SalesOrderID] FROM inserted);
        END;

        -- Update the SalesPerson SalesYTD when SubTotal is updated
        IF UPDATE([SubTotal])
        BEGIN
            DECLARE @StartDate datetime,
                    @EndDate datetime

            SET @StartDate = [dbo].[ufnGetAccountingStartDate]();
            SET @EndDate = [dbo].[ufnGetAccountingEndDate]();

            UPDATE [Sales].[SalesPerson]
            SET [Sales].[SalesPerson].[SalesYTD] = 
                (SELECT SUM([Sales].[SalesOrderHeader].[SubTotal])
                FROM [Sales].[SalesOrderHeader] 
                WHERE [Sales].[SalesPerson].[SalesPersonID] = [Sales].[SalesOrderHeader].[SalesPersonID]
                    AND ([Sales].[SalesOrderHeader].[Status] = 5) -- Shipped
                    AND [Sales].[SalesOrderHeader].[OrderDate] BETWEEN @StartDate AND @EndDate)
            WHERE [Sales].[SalesPerson].[SalesPersonID] 
                IN (SELECT DISTINCT inserted.[SalesPersonID] FROM inserted 
                    WHERE inserted.[OrderDate] BETWEEN @StartDate AND @EndDate);

            -- Update the SalesTerritory SalesYTD when SubTotal is updated
            UPDATE [Sales].[SalesTerritory]
            SET [Sales].[SalesTerritory].[SalesYTD] = 
                (SELECT SUM([Sales].[SalesOrderHeader].[SubTotal])
                FROM [Sales].[SalesOrderHeader] 
                WHERE [Sales].[SalesTerritory].[TerritoryID] = [Sales].[SalesOrderHeader].[TerritoryID]
                    AND ([Sales].[SalesOrderHeader].[Status] = 5) -- Shipped
                    AND [Sales].[SalesOrderHeader].[OrderDate] BETWEEN @StartDate AND @EndDate)
            WHERE [Sales].[SalesTerritory].[TerritoryID] 
                IN (SELECT DISTINCT inserted.[TerritoryID] FROM inserted 
                    WHERE inserted.[OrderDate] BETWEEN @StartDate AND @EndDate);
        END;
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];

        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Objects that depend on Sales.SalesOrderHeader

triggerSales.iduSalesOrderDetail
tableSales.SalesOrderHeader
triggerSales.uSalesOrderHeader
viewSales.vSalesPersonSalesByFiscalYears

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
CREATE TABLE [Sales].[SalesOrderHeader](
    [SalesOrderID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    [RevisionNumber] [tinyint] NOT NULL,
    [OrderDate] [datetime] NOT NULL,
    [DueDate] [datetime] NOT NULL,
    [ShipDate] [datetime] NULL,
    [Status] [tinyint] NOT NULL,
    [OnlineOrderFlag] [dbo].[Flag] NOT NULL,
    [SalesOrderNumber]  AS (isnull(N'SO'+CONVERT([nvarchar](23),[SalesOrderID],0),N'*** ERROR ***')),
    [PurchaseOrderNumber] [dbo].[OrderNumber] NULL,
    [AccountNumber] [dbo].[AccountNumber] NULL,
    [CustomerID] [int] NOT NULL,
    [ContactID] [int] NOT NULL,
    [SalesPersonID] [int] NULL,
    [TerritoryID] [int] NULL,
    [BillToAddressID] [int] NOT NULL,
    [ShipToAddressID] [int] NOT NULL,
    [ShipMethodID] [int] NOT NULL,
    [CreditCardID] [int] NULL,
    [CreditCardApprovalCode] [varchar](15) COLLATE Latin1_General_CS_AS NULL,
    [CurrencyRateID] [int] NULL,
    [SubTotal] [money] NOT NULL,
    [TaxAmt] [money] NOT NULL,
    [Freight] [money] NOT NULL,
    [TotalDue]  AS (isnull(([SubTotal]+[TaxAmt])+[Freight],(0))),
    [Comment] [nvarchar](128) COLLATE Latin1_General_CS_AS NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.SalesOrderHeaderSalesReason

Cross-reference table mapping sales orders to sales reason codes.

Fields

Field name Data type Nullable Default value Field description
SalesOrderIDintPrimary key. Foreign key to SalesOrderHeader.SalesOrderID.
SalesReasonIDintPrimary key. Foreign key to SalesReason.SalesReasonID.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_SalesOrderHeaderSalesReason_SalesOrderHeader_SalesOrderIDSalesOrderIDPK_SalesOrderHeader_SalesOrderID (Sales.SalesOrderHeader) Foreign key constraint referencing SalesOrderHeader.SalesOrderID.
FK_SalesOrderHeaderSalesReason_SalesReason_SalesReasonIDSalesReasonIDPK_SalesReason_SalesReasonID (Sales.SalesReason) Foreign key constraint referencing SalesReason.SalesReasonID.

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_SalesOrderHeaderSalesReason_SalesOrderID_SalesReasonIDSalesOrderIDASCYesCLUSTERED
PK_SalesOrderHeaderSalesReason_SalesOrderID_SalesReasonIDSalesReasonIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[SalesOrderHeaderSalesReason](
    [SalesOrderID] [int] NOT NULL,
    [SalesReasonID] [int] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.SalesPerson

Sales representative current information.

Fields

Field name Data type Nullable Default value Field description
SalesPersonIDintPrimary key for SalesPerson records.
TerritoryIDintYesTerritory currently assigned to. Foreign key to SalesTerritory.SalesTerritoryID.
SalesQuotamoneyYesProjected yearly sales.
Bonusmoney((0.00))Bonus due if quota is met.
CommissionPctsmallmoney((0.00))Commision percent received per sale.
SalesYTDmoney((0.00))Sales total year to date.
SalesLastYearmoney((0.00))Sales total of previous year.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_SalesPerson_Employee_SalesPersonIDSalesPersonIDPK_Employee_EmployeeID (HumanResources.Employee) Foreign key constraint referencing Employee.EmployeeID.
FK_SalesPerson_SalesTerritory_TerritoryIDTerritoryIDPK_SalesTerritory_TerritoryID (Sales.SalesTerritory) Foreign key constraint referencing SalesTerritory.TerritoryID.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.SalesOrderHeaderFK_SalesOrderHeader_SalesPerson_SalesPersonIDPK_SalesPerson_SalesPersonID
Sales.SalesTerritoryHistoryFK_SalesTerritoryHistory_SalesPerson_SalesPersonIDPK_SalesPerson_SalesPersonID
Sales.StoreFK_Store_SalesPerson_SalesPersonIDPK_SalesPerson_SalesPersonID
Sales.SalesPersonQuotaHistoryFK_SalesPersonQuotaHistory_SalesPerson_SalesPersonIDPK_SalesPerson_SalesPersonID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_SalesPerson_rowguidrowguidASCYesNONCLUSTERED
PK_SalesPerson_SalesPersonIDSalesPersonIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_SalesPerson_SalesQuotaSalesQuota([SalesQuota]>(0.00))
CK_SalesPerson_BonusBonus([Bonus]>=(0.00))
CK_SalesPerson_CommissionPctCommissionPct([CommissionPct]>=(0.00))
CK_SalesPerson_SalesYTDSalesYTD([SalesYTD]>=(0.00))
CK_SalesPerson_SalesLastYearSalesLastYear([SalesLastYear]>=(0.00))

Objects that depend on Sales.SalesPerson

triggerSales.uSalesOrderHeader
viewSales.vSalesPerson
viewSales.vSalesPersonSalesByFiscalYears

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[SalesPerson](
    [SalesPersonID] [int] NOT NULL,
    [TerritoryID] [int] NULL,
    [SalesQuota] [money] NULL,
    [Bonus] [money] NOT NULL,
    [CommissionPct] [smallmoney] NOT NULL,
    [SalesYTD] [money] NOT NULL,
    [SalesLastYear] [money] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.SalesPersonQuotaHistory

Sales performance tracking.

Fields

Field name Data type Nullable Default value Field description
SalesPersonIDintSales person identification number. Foreign key to SalesPerson.SalesPersonID.
QuotaDatedatetimeSales quota date.
SalesQuotamoneySales quota amount.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_SalesPersonQuotaHistory_SalesPerson_SalesPersonIDSalesPersonIDPK_SalesPerson_SalesPersonID (Sales.SalesPerson) Foreign key constraint referencing SalesPerson.SalesPersonID.

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_SalesPersonQuotaHistory_rowguidrowguidASCYesNONCLUSTERED
PK_SalesPersonQuotaHistory_SalesPersonID_QuotaDateSalesPersonIDASCYesCLUSTERED
PK_SalesPersonQuotaHistory_SalesPersonID_QuotaDateQuotaDateASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_SalesPersonQuotaHistory_SalesQuotaSalesQuota([SalesQuota]>(0.00))

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[SalesPersonQuotaHistory](
    [SalesPersonID] [int] NOT NULL,
    [QuotaDate] [datetime] NOT NULL,
    [SalesQuota] [money] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.SalesReason

Lookup table of customer purchase reasons.

Fields

Field name Data type Nullable Default value Field description
SalesReasonIDintPrimary key for SalesReason records.
NameNameSales reason description.
ReasonTypeNameCategory the sales reason belongs to.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.SalesOrderHeaderSalesReasonFK_SalesOrderHeaderSalesReason_SalesReason_SalesReasonIDPK_SalesReason_SalesReasonID

Indices

Index nameColumn nameSort directionUniqueIndex type
PK_SalesReason_SalesReasonIDSalesReasonIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[SalesReason](
    [SalesReasonID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [ReasonType] [dbo].[Name] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.SalesTaxRate

Tax rate lookup table.

Fields

Field name Data type Nullable Default value Field description
SalesTaxRateIDintPrimary key for SalesTaxRate records.
StateProvinceIDintState, province, or country/region the sales tax applies to.
TaxTypetinyint1 = Tax applied to retail transactions, 2 = Tax applied to wholesale transactions, 3 = Tax applied to all sales (retail and wholesale) transactions.
TaxRatesmallmoney((0.00))Tax rate amount.
NameNameTax rate description.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_SalesTaxRate_StateProvince_StateProvinceIDStateProvinceIDPK_StateProvince_StateProvinceID (Person.StateProvince) Foreign key constraint referencing StateProvince.StateProvinceID.

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_SalesTaxRate_rowguidrowguidASCYesNONCLUSTERED
AK_SalesTaxRate_StateProvinceID_TaxTypeStateProvinceIDASCYesNONCLUSTERED
AK_SalesTaxRate_StateProvinceID_TaxTypeTaxTypeASCYesNONCLUSTERED
PK_SalesTaxRate_SalesTaxRateIDSalesTaxRateIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_SalesTaxRate_TaxTypeTaxType([TaxType]>=(1) AND [TaxType]<=(3))

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[SalesTaxRate](
    [SalesTaxRateID] [int] IDENTITY(1,1) NOT NULL,
    [StateProvinceID] [int] NOT NULL,
    [TaxType] [tinyint] NOT NULL,
    [TaxRate] [smallmoney] NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.SalesTerritory

Sales territory lookup table.

Fields

Field name Data type Nullable Default value Field description
TerritoryIDintPrimary key for SalesTerritory records.
NameNameSales territory description
CountryRegionCodenvarchar (3) ISO standard country or region code. Foreign key to CountryRegion.CountryRegionCode.
Groupnvarchar (50) Geographic area to which the sales territory belong.
SalesYTDmoney((0.00))Sales in the territory year to date.
SalesLastYearmoney((0.00))Sales in the territory the previous year.
CostYTDmoney((0.00))Business costs in the territory year to date.
CostLastYearmoney((0.00))Business costs in the territory the previous year.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.SalesOrderHeaderFK_SalesOrderHeader_SalesTerritory_TerritoryIDPK_SalesTerritory_TerritoryID
Sales.SalesPersonFK_SalesPerson_SalesTerritory_TerritoryIDPK_SalesTerritory_TerritoryID
Sales.SalesTerritoryHistoryFK_SalesTerritoryHistory_SalesTerritory_TerritoryIDPK_SalesTerritory_TerritoryID
Sales.CustomerFK_Customer_SalesTerritory_TerritoryIDPK_SalesTerritory_TerritoryID
Person.StateProvinceFK_StateProvince_SalesTerritory_TerritoryIDPK_SalesTerritory_TerritoryID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_SalesTerritory_NameNameASCYesNONCLUSTERED
AK_SalesTerritory_rowguidrowguidASCYesNONCLUSTERED
PK_SalesTerritory_TerritoryIDTerritoryIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_SalesTerritory_SalesYTDSalesYTD([SalesYTD]>=(0.00))
CK_SalesTerritory_SalesLastYearSalesLastYear([SalesLastYear]>=(0.00))
CK_SalesTerritory_CostYTDCostYTD([CostYTD]>=(0.00))
CK_SalesTerritory_CostLastYearCostLastYear([CostLastYear]>=(0.00))

Objects that depend on Sales.SalesTerritory

triggerSales.uSalesOrderHeader
viewSales.vSalesPerson
viewSales.vSalesPersonSalesByFiscalYears

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[SalesTerritory](
    [TerritoryID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [CountryRegionCode] [nvarchar](3) COLLATE Latin1_General_CS_AS NOT NULL,
    [Group] [nvarchar](50) COLLATE Latin1_General_CS_AS NOT NULL,
    [SalesYTD] [money] NOT NULL,
    [SalesLastYear] [money] NOT NULL,
    [CostYTD] [money] NOT NULL,
    [CostLastYear] [money] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.SalesTerritoryHistory

Sales representative transfers to other sales territories.

Fields

Field name Data type Nullable Default value Field description
SalesPersonIDintPrimary key for SalesTerritoryHistory records.
TerritoryIDintTerritory identification number. Foreign key to SalesTerritory.SalesTerritoryID.
StartDatedatetimeDate the sales representive started work in the territory.
EndDatedatetimeYesDate the sales representative left work in the territory.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_SalesTerritoryHistory_SalesPerson_SalesPersonIDSalesPersonIDPK_SalesPerson_SalesPersonID (Sales.SalesPerson) Foreign key constraint referencing SalesPerson.SalesPersonID.
FK_SalesTerritoryHistory_SalesTerritory_TerritoryIDTerritoryIDPK_SalesTerritory_TerritoryID (Sales.SalesTerritory) Foreign key constraint referencing SalesTerritory.TerritoryID.

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_SalesTerritoryHistory_rowguidrowguidASCYesNONCLUSTERED
PK_SalesTerritoryHistory_SalesPersonID_StartDate_TerritoryIDSalesPersonIDASCYesCLUSTERED
PK_SalesTerritoryHistory_SalesPersonID_StartDate_TerritoryIDTerritoryIDASCYesCLUSTERED
PK_SalesTerritoryHistory_SalesPersonID_StartDate_TerritoryIDStartDateASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_SalesTerritoryHistory_EndDateStartDate([EndDate]>=[StartDate] OR [EndDate] IS NULL)
CK_SalesTerritoryHistory_EndDateEndDate([EndDate]>=[StartDate] OR [EndDate] IS NULL)

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[SalesTerritoryHistory](
    [SalesPersonID] [int] NOT NULL,
    [TerritoryID] [int] NOT NULL,
    [StartDate] [datetime] NOT NULL,
    [EndDate] [datetime] NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.ShoppingCartItem

Contains online customer orders until the order is submitted or cancelled.

Fields

Field name Data type Nullable Default value Field description
ShoppingCartItemIDintPrimary key for ShoppingCartItem records.
ShoppingCartIDnvarchar (50) Shopping cart identification number.
Quantityint((1))Product quantity ordered.
ProductIDintProduct ordered. Foreign key to Product.ProductID.
DateCreateddatetime(getdate())Date the time the record was created.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_ShoppingCartItem_Product_ProductIDProductIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductID.

Indices

Index nameColumn nameSort directionUniqueIndex type
IX_ShoppingCartItem_ShoppingCartID_ProductIDShoppingCartIDASCNONCLUSTERED
IX_ShoppingCartItem_ShoppingCartID_ProductIDProductIDASCNONCLUSTERED
PK_ShoppingCartItem_ShoppingCartItemIDShoppingCartItemIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_ShoppingCartItem_QuantityQuantity([Quantity]>=(1))

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[ShoppingCartItem](
    [ShoppingCartItemID] [int] IDENTITY(1,1) NOT NULL,
    [ShoppingCartID] [nvarchar](50) COLLATE Latin1_General_CS_AS NOT NULL,
    [Quantity] [int] NOT NULL,
    [ProductID] [int] NOT NULL,
    [DateCreated] [datetime] NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.SpecialOffer

Sale discounts lookup table.

Fields

Field name Data type Nullable Default value Field description
SpecialOfferIDintPrimary key for SpecialOffer records.
Descriptionnvarchar (255) Discount description.
DiscountPctsmallmoney((0.00))Discount precentage.
Typenvarchar (50) Discount type category.
Categorynvarchar (50) Group the discount applies to such as Reseller or Customer.
StartDatedatetimeDiscount start date.
EndDatedatetimeDiscount end date.
MinQtyint((0))Minimum discount percent allowed.
MaxQtyintYesMaximum discount percent allowed.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.SpecialOfferProductFK_SpecialOfferProduct_SpecialOffer_SpecialOfferIDPK_SpecialOffer_SpecialOfferID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_SpecialOffer_rowguidrowguidASCYesNONCLUSTERED
PK_SpecialOffer_SpecialOfferIDSpecialOfferIDASCYesCLUSTERED

Check constraints

Check nameColumn nameCheck expresion
CK_SpecialOffer_EndDateStartDate([EndDate]>=[StartDate])
CK_SpecialOffer_EndDateEndDate([EndDate]>=[StartDate])
CK_SpecialOffer_DiscountPctDiscountPct([DiscountPct]>=(0.00))
CK_SpecialOffer_MinQtyMinQty([MinQty]>=(0))
CK_SpecialOffer_MaxQtyMaxQty([MaxQty]>=(0))

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[SpecialOffer](
    [SpecialOfferID] [int] IDENTITY(1,1) NOT NULL,
    [Description] [nvarchar](255) COLLATE Latin1_General_CS_AS NOT NULL,
    [DiscountPct] [smallmoney] NOT NULL,
    [Type] [nvarchar](50) COLLATE Latin1_General_CS_AS NOT NULL,
    [Category] [nvarchar](50) COLLATE Latin1_General_CS_AS NOT NULL,
    [StartDate] [datetime] NOT NULL,
    [EndDate] [datetime] NOT NULL,
    [MinQty] [int] NOT NULL,
    [MaxQty] [int] NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.SpecialOfferProduct

Cross-reference table mapping products to special offer discounts.

Fields

Field name Data type Nullable Default value Field description
SpecialOfferIDintPrimary key for SpecialOfferProduct records.
ProductIDintProduct identification number. Foreign key to Product.ProductID.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_SpecialOfferProduct_SpecialOffer_SpecialOfferIDSpecialOfferIDPK_SpecialOffer_SpecialOfferID (Sales.SpecialOffer) Foreign key constraint referencing SpecialOffer.SpecialOfferID.
FK_SpecialOfferProduct_Product_ProductIDProductIDPK_Product_ProductID (Production.Product) Foreign key constraint referencing Product.ProductID.

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.SalesOrderDetailFK_SalesOrderDetail_SpecialOfferProduct_SpecialOfferIDProductIDPK_SpecialOfferProduct_SpecialOfferID_ProductID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_SpecialOfferProduct_rowguidrowguidASCYesNONCLUSTERED
IX_SpecialOfferProduct_ProductIDProductIDASCNONCLUSTERED
PK_SpecialOfferProduct_SpecialOfferID_ProductIDSpecialOfferIDASCYesCLUSTERED
PK_SpecialOfferProduct_SpecialOfferID_ProductIDProductIDASCYesCLUSTERED

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[SpecialOfferProduct](
    [SpecialOfferID] [int] NOT NULL,
    [ProductID] [int] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.Store

Customers (resellers) of Adventure Works products.

Fields

Field name Data type Nullable Default value Field description
CustomerIDintPrimary key. Foreign key to Customer.CustomerID.
NameNameName of the store.
SalesPersonIDintYesID of the sales person assigned to the customer. Foreign key to SalesPerson.SalesPersonID.
DemographicsxmlYesDemographic informationg about the store such as the number of employees, annual sales and store type.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_Store_Customer_CustomerIDCustomerIDPK_Customer_CustomerID (Sales.Customer) Foreign key constraint referencing Customer.CustomerID.
FK_Store_SalesPerson_SalesPersonIDSalesPersonIDPK_SalesPerson_SalesPersonID (Sales.SalesPerson) Foreign key constraint referencing SalesPerson.SalesPersonID

Referencing tables

Table nameForeign keyPrimary key or unique constraint
Sales.StoreContactFK_StoreContact_Store_CustomerIDPK_Store_CustomerID

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_Store_rowguidrowguidASCYesNONCLUSTERED
IX_Store_SalesPersonIDSalesPersonIDASCNONCLUSTERED
PK_Store_CustomerIDCustomerIDASCYesCLUSTERED
PXML_Store_DemographicsDemographicsASCXML

Triggers

Trigger name:Sales.iStore
Description:AFTER INSERT trigger inserting Store only if the Customer does not exist in the Individual table.
Creation date:26 Apr 2006
Trigger type:INSERT
Trigger active:Yes
Trigger definition

CREATE TRIGGER [Sales].[iStore] ON [Sales].[Store] 
AFTER INSERT AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
        -- Only allow the Customer to be a Store OR Individual
        IF EXISTS (SELECT * FROM inserted INNER JOIN [Sales].[Individual] 
            ON inserted.[CustomerID] = [Sales].[Individual].[CustomerID]) 
        BEGIN
            -- Rollback any active or uncommittable transactions
            IF @@TRANCOUNT > 0
            BEGIN
                ROLLBACK TRANSACTION;
            END
        END;
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];

        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Objects that depend on Sales.Store

triggerSales.iuIndividual
viewSales.vStoreWithDemographics

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[Store](
    [CustomerID] [int] NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [SalesPersonID] [int] NULL,
    [Demographics] [xml](CONTENT [Sales].[StoreSurveySchemaCollection]) NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Table: Sales.StoreContact

Cross-reference table mapping stores and their employees.

Fields

Field name Data type Nullable Default value Field description
CustomerIDintStore identification number. Foreign key to Customer.CustomerID.
ContactIDintContact (store employee) identification number. Foreign key to Contact.ContactID.
ContactTypeIDintContact type such as owner or purchasing agent. Foreign key to ContactType.ContactTypeID.
rowguiduniqueidentifier(newid())ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
ModifiedDatedatetime(getdate())Date and time the record was last updated.

Foreign keys dependencies:

NameColumnReferenceForeign Key description
FK_StoreContact_Store_CustomerIDCustomerIDPK_Store_CustomerID (Sales.Store) Foreign key constraint referencing Store.CustomerID.
FK_StoreContact_Contact_ContactIDContactIDPK_Contact_ContactID (Person.Contact) Foreign key constraint referencing Contact.ContactID.
FK_StoreContact_ContactType_ContactTypeIDContactTypeIDPK_ContactType_ContactTypeID (Person.ContactType) Foreign key constraint referencing ContactType.ContactTypeID.

Indices

Index nameColumn nameSort directionUniqueIndex type
AK_StoreContact_rowguidrowguidASCYesNONCLUSTERED
IX_StoreContact_ContactIDContactIDASCNONCLUSTERED
IX_StoreContact_ContactTypeIDContactTypeIDASCNONCLUSTERED
PK_StoreContact_CustomerID_ContactIDCustomerIDASCYesCLUSTERED
PK_StoreContact_CustomerID_ContactIDContactIDASCYesCLUSTERED

Objects that depend on Sales.StoreContact

viewSales.vStoreWithDemographics

Table definition

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[StoreContact](
    [CustomerID] [int] NOT NULL,
    [ContactID] [int] NOT NULL,
    [ContactTypeID] [int] NOT NULL,
    [rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]

Views

View: HumanResources.vEmployee

View name:HumanResources.vEmployee
Description:Employee names and addresses.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableHumanResources.EmployeeEmployeeIDint
tablePerson.ContactTitlenvarchar (8) Yes
tablePerson.ContactFirstNameName
tablePerson.ContactMiddleNameNameYes
tablePerson.ContactLastNameName
tablePerson.ContactSuffixnvarchar (10) Yes
tableJobTitlenvarchar (50)
tablePerson.ContactPhonePhoneYes
tablePerson.ContactEmailAddressnvarchar (50) Yes
tablePerson.ContactEmailPromotionint
tablePerson.AddressAddressLine1nvarchar (60)
tablePerson.AddressAddressLine2nvarchar (60) Yes
tablePerson.AddressCitynvarchar (30)
tableStateProvinceNameName
tablePerson.AddressPostalCodenvarchar (15)
tableCountryRegionNameName
tablePerson.ContactAdditionalContactInfoxmlYes

View definition

CREATE VIEW [HumanResources].[vEmployee] 
AS 
SELECT 
    e.[EmployeeID]
    ,c.[Title]
    ,c.[FirstName]
    ,c.[MiddleName]
    ,c.[LastName]
    ,c.[Suffix]
    ,e.[Title] AS [JobTitle] 
    ,c.[Phone]
    ,c.[EmailAddress]
    ,c.[EmailPromotion]
    ,a.[AddressLine1]
    ,a.[AddressLine2]
    ,a.[City]
    ,sp.[Name] AS [StateProvinceName] 
    ,a.[PostalCode]
    ,cr.[Name] AS [CountryRegionName] 
    ,c.[AdditionalContactInfo]
FROM [HumanResources].[Employee] e
    INNER JOIN [Person].[Contact] c 
    ON c.[ContactID] = e.[ContactID]
    INNER JOIN [HumanResources].[EmployeeAddress] ea 
    ON e.[EmployeeID] = ea.[EmployeeID] 
    INNER JOIN [Person].[Address] a 
    ON ea.[AddressID] = a.[AddressID]
    INNER JOIN [Person].[StateProvince] sp 
    ON sp.[StateProvinceID] = a.[StateProvinceID]
    INNER JOIN [Person].[CountryRegion] cr 
    ON cr.[CountryRegionCode] = sp.[CountryRegionCode];

Related objects

tablePerson.Address
tablePerson.StateProvince
tableHumanResources.Employee
tableHumanResources.EmployeeAddress
tablePerson.Contact
tablePerson.CountryRegion

View: HumanResources.vEmployeeDepartment

View name:HumanResources.vEmployeeDepartment
Description:Returns employee name, title, and current department.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableHumanResources.EmployeeEmployeeIDint
tablePerson.ContactTitlenvarchar (8) Yes
tablePerson.ContactFirstNameName
tablePerson.ContactMiddleNameNameYes
tablePerson.ContactLastNameName
tablePerson.ContactSuffixnvarchar (10) Yes
tableJobTitlenvarchar (50)
tableDepartmentName
tableHumanResources.DepartmentGroupNameName
tableHumanResources.EmployeeDepartmentHistoryStartDatedatetime

View definition

CREATE VIEW [HumanResources].[vEmployeeDepartment] 
AS 
SELECT 
    e.[EmployeeID] 
    ,c.[Title] 
    ,c.[FirstName] 
    ,c.[MiddleName] 
    ,c.[LastName] 
    ,c.[Suffix] 
    ,e.[Title] AS [JobTitle] 
    ,d.[Name] AS [Department] 
    ,d.[GroupName] 
    ,edh.[StartDate] 
FROM [HumanResources].[Employee] e
    INNER JOIN [Person].[Contact] c 
    ON c.[ContactID] = e.[ContactID]
    INNER JOIN [HumanResources].[EmployeeDepartmentHistory] edh 
    ON e.[EmployeeID] = edh.[EmployeeID] 
    INNER JOIN [HumanResources].[Department] d 
    ON edh.[DepartmentID] = d.[DepartmentID] 
WHERE GETDATE() BETWEEN edh.[StartDate] AND ISNULL(edh.[EndDate], GETDATE());

Related objects

tablePerson.Contact
tableHumanResources.EmployeeDepartmentHistory
tableHumanResources.Department
tableHumanResources.Employee

View: HumanResources.vEmployeeDepartmentHistory

View name:HumanResources.vEmployeeDepartmentHistory
Description:Returns employee name and current and previous departments.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableHumanResources.EmployeeEmployeeIDint
tablePerson.ContactTitlenvarchar (8) Yes
tablePerson.ContactFirstNameName
tablePerson.ContactMiddleNameNameYes
tablePerson.ContactLastNameName
tablePerson.ContactSuffixnvarchar (10) Yes
tableShiftName
tableDepartmentName
tableHumanResources.DepartmentGroupNameName
tableHumanResources.EmployeeDepartmentHistoryStartDatedatetime
tableHumanResources.EmployeeDepartmentHistoryEndDatedatetimeYes

View definition

CREATE VIEW [HumanResources].[vEmployeeDepartmentHistory] 
AS 
SELECT 
    e.[EmployeeID] 
    ,c.[Title] 
    ,c.[FirstName] 
    ,c.[MiddleName] 
    ,c.[LastName] 
    ,c.[Suffix] 
    ,s.[Name] AS [Shift]
    ,d.[Name] AS [Department] 
    ,d.[GroupName] 
    ,edh.[StartDate] 
    ,edh.[EndDate]
FROM [HumanResources].[Employee] e
    INNER JOIN [Person].[Contact] c 
    ON c.[ContactID] = e.[ContactID]
    INNER JOIN [HumanResources].[EmployeeDepartmentHistory] edh 
    ON e.[EmployeeID] = edh.[EmployeeID] 
    INNER JOIN [HumanResources].[Department] d 
    ON edh.[DepartmentID] = d.[DepartmentID] 
    INNER JOIN [HumanResources].[Shift] s
    ON s.[ShiftID] = edh.[ShiftID];

Related objects

tablePerson.Contact
tableHumanResources.EmployeeDepartmentHistory
tableHumanResources.Shift
tableHumanResources.Department
tableHumanResources.Employee

View: HumanResources.vJobCandidate

View name:HumanResources.vJobCandidate
Description:Job candidate names and resumes.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableHumanResources.JobCandidateJobCandidateIDint
tableHumanResources.JobCandidateEmployeeIDintYes
tableName.Prefixnvarchar (30) Yes
tableName.Firstnvarchar (30) Yes
tableName.Middlenvarchar (30) Yes
tableName.Lastnvarchar (30) Yes
tableName.Suffixnvarchar (30) Yes
tableSkillsnvarcharYes
tableAddr.Typenvarchar (30) Yes
tableAddr.Loc.CountryRegionnvarchar (100) Yes
tableAddr.Loc.Statenvarchar (100) Yes
tableAddr.Loc.Citynvarchar (100) Yes
tableAddr.PostalCodenvarchar (20) Yes
tableEMailnvarcharYes
tableWebSitenvarcharYes
tableHumanResources.JobCandidateModifiedDatedatetime

View definition

CREATE VIEW [HumanResources].[vJobCandidate] 
AS 
SELECT 
    jc.[JobCandidateID] 
    ,jc.[EmployeeID] 
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (/Resume/Name/Name.Prefix)[1]', 'nvarchar(30)') AS [Name.Prefix] 
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume";
        (/Resume/Name/Name.First)[1]', 'nvarchar(30)') AS [Name.First] 
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (/Resume/Name/Name.Middle)[1]', 'nvarchar(30)') AS [Name.Middle] 
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (/Resume/Name/Name.Last)[1]', 'nvarchar(30)') AS [Name.Last] 
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (/Resume/Name/Name.Suffix)[1]', 'nvarchar(30)') AS [Name.Suffix] 
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (/Resume/Skills)[1]', 'nvarchar(max)') AS [Skills] 
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Address/Addr.Type)[1]', 'nvarchar(30)') AS [Addr.Type]
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Address/Addr.Location/Location/Loc.CountryRegion)[1]', 'nvarchar(100)') AS [Addr.Loc.CountryRegion]
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Address/Addr.Location/Location/Loc.State)[1]', 'nvarchar(100)') AS [Addr.Loc.State]
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Address/Addr.Location/Location/Loc.City)[1]', 'nvarchar(100)') AS [Addr.Loc.City]
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Address/Addr.PostalCode)[1]', 'nvarchar(20)') AS [Addr.PostalCode]
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (/Resume/EMail)[1]', 'nvarchar(max)') AS [EMail] 
    ,[Resume].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (/Resume/WebSite)[1]', 'nvarchar(max)') AS [WebSite] 
    ,jc.[ModifiedDate] 
FROM [HumanResources].[JobCandidate] jc 
CROSS APPLY jc.[Resume].nodes(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
    /Resume') AS Resume(ref);

Related objects

tableHumanResources.JobCandidate

View: HumanResources.vJobCandidateEducation

View name:HumanResources.vJobCandidateEducation
Description:Displays the content from each education related element in the xml column Resume in the HumanResources.JobCandidate table. The content has been localized into French, Simplified Chinese and Thai. Some data may not display correctly unless supplemental language support is installed.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableHumanResources.JobCandidateJobCandidateIDint
tableEdu.LevelnvarcharYes
tableEdu.StartDatedatetimeYes
tableEdu.EndDatedatetimeYes
tableEdu.Degreenvarchar (50) Yes
tableEdu.Majornvarchar (50) Yes
tableEdu.Minornvarchar (50) Yes
tableEdu.GPAnvarchar (5) Yes
tableEdu.GPAScalenvarchar (5) Yes
tableEdu.Schoolnvarchar (100) Yes
tableEdu.Loc.CountryRegionnvarchar (100) Yes
tableEdu.Loc.Statenvarchar (100) Yes
tableEdu.Loc.Citynvarchar (100) Yes

View definition

CREATE VIEW [HumanResources].[vJobCandidateEducation] 
AS 
SELECT 
    jc.[JobCandidateID] 
    ,[Education].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Edu.Level)[1]', 'nvarchar(max)') AS [Edu.Level]
    ,CONVERT(datetime, REPLACE([Education].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Edu.StartDate)[1]', 'nvarchar(20)') ,'Z', ''), 101) AS [Edu.StartDate] 
    ,CONVERT(datetime, REPLACE([Education].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Edu.EndDate)[1]', 'nvarchar(20)') ,'Z', ''), 101) AS [Edu.EndDate] 
    ,[Education].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Edu.Degree)[1]', 'nvarchar(50)') AS [Edu.Degree]
    ,[Education].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Edu.Major)[1]', 'nvarchar(50)') AS [Edu.Major]
    ,[Education].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Edu.Minor)[1]', 'nvarchar(50)') AS [Edu.Minor]
    ,[Education].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Edu.GPA)[1]', 'nvarchar(5)') AS [Edu.GPA]
    ,[Education].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Edu.GPAScale)[1]', 'nvarchar(5)') AS [Edu.GPAScale]
    ,[Education].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Edu.School)[1]', 'nvarchar(100)') AS [Edu.School]
    ,[Education].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Edu.Location/Location/Loc.CountryRegion)[1]', 'nvarchar(100)') AS [Edu.Loc.CountryRegion]
    ,[Education].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Edu.Location/Location/Loc.State)[1]', 'nvarchar(100)') AS [Edu.Loc.State]
    ,[Education].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Edu.Location/Location/Loc.City)[1]', 'nvarchar(100)') AS [Edu.Loc.City]
FROM [HumanResources].[JobCandidate] jc 
CROSS APPLY jc.[Resume].nodes(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
    /Resume/Education') AS [Education](ref);

Related objects

tableHumanResources.JobCandidate

View: HumanResources.vJobCandidateEmployment

View name:HumanResources.vJobCandidateEmployment
Description:Displays the content from each employement history related element in the xml column Resume in the HumanResources.JobCandidate table. The content has been localized into French, Simplified Chinese and Thai. Some data may not display correctly unless supplemental language support is installed.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableHumanResources.JobCandidateJobCandidateIDint
tableEmp.StartDatedatetimeYes
tableEmp.EndDatedatetimeYes
tableEmp.OrgNamenvarchar (100) Yes
tableEmp.JobTitlenvarchar (100) Yes
tableEmp.ResponsibilitynvarcharYes
tableEmp.FunctionCategorynvarcharYes
tableEmp.IndustryCategorynvarcharYes
tableEmp.Loc.CountryRegionnvarcharYes
tableEmp.Loc.StatenvarcharYes
tableEmp.Loc.CitynvarcharYes

View definition

CREATE VIEW [HumanResources].[vJobCandidateEmployment] 
AS 
SELECT 
    jc.[JobCandidateID] 
    ,CONVERT(datetime, REPLACE([Employment].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Emp.StartDate)[1]', 'nvarchar(20)') ,'Z', ''), 101) AS [Emp.StartDate] 
    ,CONVERT(datetime, REPLACE([Employment].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Emp.EndDate)[1]', 'nvarchar(20)') ,'Z', ''), 101) AS [Emp.EndDate] 
    ,[Employment].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Emp.OrgName)[1]', 'nvarchar(100)') AS [Emp.OrgName]
    ,[Employment].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Emp.JobTitle)[1]', 'nvarchar(100)') AS [Emp.JobTitle]
    ,[Employment].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Emp.Responsibility)[1]', 'nvarchar(max)') AS [Emp.Responsibility]
    ,[Employment].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Emp.FunctionCategory)[1]', 'nvarchar(max)') AS [Emp.FunctionCategory]
    ,[Employment].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Emp.IndustryCategory)[1]', 'nvarchar(max)') AS [Emp.IndustryCategory]
    ,[Employment].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Emp.Location/Location/Loc.CountryRegion)[1]', 'nvarchar(max)') AS [Emp.Loc.CountryRegion]
    ,[Employment].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Emp.Location/Location/Loc.State)[1]', 'nvarchar(max)') AS [Emp.Loc.State]
    ,[Employment].ref.value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
        (Emp.Location/Location/Loc.City)[1]', 'nvarchar(max)') AS [Emp.Loc.City]
FROM [HumanResources].[JobCandidate] jc 
CROSS APPLY jc.[Resume].nodes(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; 
    /Resume/Employment') AS Employment(ref);

Related objects

tableHumanResources.JobCandidate

View: Person.vAdditionalContactInfo

View name:Person.vAdditionalContactInfo
Description:Displays the contact name and content from each element in the xml column AdditionalContactInfo for that person.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tablePerson.ContactContactIDint
tablePerson.ContactFirstNameName
tablePerson.ContactMiddleNameNameYes
tablePerson.ContactLastNameName
tableTelephoneNumbernvarchar (50) Yes
tableTelephoneSpecialInstructionsnvarcharYes
tableStreetnvarchar (50) Yes
tableCitynvarchar (50) Yes
tableStateProvincenvarchar (50) Yes
tablePostalCodenvarchar (50) Yes
tableCountryRegionnvarchar (50) Yes
tableHomeAddressSpecialInstructionsnvarcharYes
tableEMailAddressnvarchar (128) Yes
tableEMailSpecialInstructionsnvarcharYes
tableEMailTelephoneNumbernvarchar (50) Yes
tablePerson.Contactrowguiduniqueidentifier
tablePerson.ContactModifiedDatedatetime

View definition

CREATE VIEW [Person].[vAdditionalContactInfo] 
AS 
SELECT 
    [ContactID] 
    ,[FirstName]
    ,[MiddleName]
    ,[LastName]
    ,[ContactInfo].ref.value(N'declare namespace ci="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo"; 
        declare namespace act="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes"; 
        (act:telephoneNumber)[1]/act:number', 'nvarchar(50)') AS [TelephoneNumber] 
    ,LTRIM(RTRIM([ContactInfo].ref.value(N'declare namespace ci="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo"; 
        declare namespace act="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes"; 
        (act:telephoneNumber/act:SpecialInstructions/text())[1]', 'nvarchar(max)'))) AS [TelephoneSpecialInstructions] 
    ,[ContactInfo].ref.value(N'declare namespace ci="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo"; 
        declare namespace act="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes";
        (act:homePostalAddress/act:Street)[1]', 'nvarchar(50)') AS [Street] 
    ,[ContactInfo].ref.value(N'declare namespace ci="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo"; 
        declare namespace act="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes"; 
        (act:homePostalAddress/act:City)[1]', 'nvarchar(50)') AS [City] 
    ,[ContactInfo].ref.value(N'declare namespace ci="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo"; 
        declare namespace act="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes"; 
        (act:homePostalAddress/act:StateProvince)[1]', 'nvarchar(50)') AS [StateProvince] 
    ,[ContactInfo].ref.value(N'declare namespace ci="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo"; 
        declare namespace act="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes"; 
        (act:homePostalAddress/act:PostalCode)[1]', 'nvarchar(50)') AS [PostalCode] 
    ,[ContactInfo].ref.value(N'declare namespace ci="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo"; 
        declare namespace act="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes"; 
        (act:homePostalAddress/act:CountryRegion)[1]', 'nvarchar(50)') AS [CountryRegion] 
    ,[ContactInfo].ref.value(N'declare namespace ci="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo"; 
        declare namespace act="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes"; 
        (act:homePostalAddress/act:SpecialInstructions/text())[1]', 'nvarchar(max)') AS [HomeAddressSpecialInstructions] 
    ,[ContactInfo].ref.value(N'declare namespace ci="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo"; 
        declare namespace act="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes"; 
        (act:eMail/act:eMailAddress)[1]', 'nvarchar(128)') AS [EMailAddress] 
    ,LTRIM(RTRIM([ContactInfo].ref.value(N'declare namespace ci="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo"; 
        declare namespace act="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes"; 
        (act:eMail/act:SpecialInstructions/text())[1]', 'nvarchar(max)'))) AS [EMailSpecialInstructions] 
    ,[ContactInfo].ref.value(N'declare namespace ci="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo"; 
        declare namespace act="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes"; 
        (act:eMail/act:SpecialInstructions/act:telephoneNumber/act:number)[1]', 'nvarchar(50)') AS [EMailTelephoneNumber] 
    ,[rowguid] 
    ,[ModifiedDate]
FROM [Person].[Contact]
OUTER APPLY [AdditionalContactInfo].nodes(
    'declare namespace ci="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo"; 
    /ci:AdditionalContactInfo') AS ContactInfo(ref) 
WHERE [AdditionalContactInfo] IS NOT NULL;

Related objects

tablePerson.Contact

View: Person.vStateProvinceCountryRegion

View name:Person.vStateProvinceCountryRegion
Description:Joins StateProvince table with CountryRegion table.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tablePerson.StateProvinceStateProvinceIDintClustered index on the view vStateProvinceCountryRegion.
tablePerson.StateProvinceStateProvinceCodenchar (3)
tablePerson.StateProvinceIsOnlyStateProvinceFlagFlag
tableStateProvinceNameName
tablePerson.StateProvinceTerritoryIDint
tablePerson.CountryRegionCountryRegionCodenvarchar (3)
tableCountryRegionNameName

View definition

CREATE VIEW [Person].[vStateProvinceCountryRegion] 
WITH SCHEMABINDING 
AS 
SELECT 
    sp.[StateProvinceID] 
    ,sp.[StateProvinceCode] 
    ,sp.[IsOnlyStateProvinceFlag] 
    ,sp.[Name] AS [StateProvinceName] 
    ,sp.[TerritoryID] 
    ,cr.[CountryRegionCode] 
    ,cr.[Name] AS [CountryRegionName]
FROM [Person].[StateProvince] sp 
    INNER JOIN [Person].[CountryRegion] cr 
    ON sp.[CountryRegionCode] = cr.[CountryRegionCode];

Related objects

tablePerson.CountryRegion
tablePerson.StateProvince

View: Production.vProductAndDescription

View name:Production.vProductAndDescription
Description:Product names and descriptions. Product descriptions are provided in multiple languages.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableProduction.ProductProductIDintClustered index on the view vProductAndDescription.
tableProduction.ProductNameName
tableProductModelName
tableProduction.ProductModelProductDescriptionCultureCultureIDnchar (6)
tableProduction.ProductDescriptionDescriptionnvarchar (400)

View definition

CREATE VIEW [Production].[vProductAndDescription] 
WITH SCHEMABINDING 
AS 
-- View (indexed or standard) to display products and product descriptions by language.
SELECT 
    p.[ProductID] 
    ,p.[Name] 
    ,pm.[Name] AS [ProductModel] 
    ,pmx.[CultureID] 
    ,pd.[Description] 
FROM [Production].[Product] p 
    INNER JOIN [Production].[ProductModel] pm 
    ON p.[ProductModelID] = pm.[ProductModelID] 
    INNER JOIN [Production].[ProductModelProductDescriptionCulture] pmx 
    ON pm.[ProductModelID] = pmx.[ProductModelID] 
    INNER JOIN [Production].[ProductDescription] pd 
    ON pmx.[ProductDescriptionID] = pd.[ProductDescriptionID];

Related objects

tableProduction.Product
tableProduction.ProductDescription
tableProduction.ProductModelProductDescriptionCulture
tableProduction.ProductModel

View: Production.vProductModelCatalogDescription

View name:Production.vProductModelCatalogDescription
Description:Displays the content from each element in the xml column CatalogDescription for each product in the Production.ProductModel table that has catalog data.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableProduction.ProductModelProductModelIDint
tableProduction.ProductModelNameName
tableSummarynvarcharYes
tableManufacturernvarcharYes
tableCopyrightnvarchar (30) Yes
tableProductURLnvarchar (256) Yes
tableWarrantyPeriodnvarchar (256) Yes
tableWarrantyDescriptionnvarchar (256) Yes
tableNoOfYearsnvarchar (256) Yes
tableMaintenanceDescriptionnvarchar (256) Yes
tableWheelnvarchar (256) Yes
tableSaddlenvarchar (256) Yes
tablePedalnvarchar (256) Yes
tableBikeFramenvarcharYes
tableCranksetnvarchar (256) Yes
tablePictureAnglenvarchar (256) Yes
tablePictureSizenvarchar (256) Yes
tableProductPhotoIDnvarchar (256) Yes
tableMaterialnvarchar (256) Yes
tableColornvarchar (256) Yes
tableProductLinenvarchar (256) Yes
tableStylenvarchar (256) Yes
tableRiderExperiencenvarchar (1024) Yes
tableProduction.ProductModelrowguiduniqueidentifier
tableProduction.ProductModelModifiedDatedatetime

View definition

CREATE VIEW [Production].[vProductModelCatalogDescription] 
AS 
SELECT 
    [ProductModelID] 
    ,[Name] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        declare namespace html="http://www.w3.org/1999/xhtml"; 
        (/p1:ProductDescription/p1:Summary/html:p)[1]', 'nvarchar(max)') AS [Summary] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        (/p1:ProductDescription/p1:Manufacturer/p1:Name)[1]', 'nvarchar(max)') AS [Manufacturer] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        (/p1:ProductDescription/p1:Manufacturer/p1:Copyright)[1]', 'nvarchar(30)') AS [Copyright] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        (/p1:ProductDescription/p1:Manufacturer/p1:ProductURL)[1]', 'nvarchar(256)') AS [ProductURL] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        declare namespace wm="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain"; 
        (/p1:ProductDescription/p1:Features/wm:Warranty/wm:WarrantyPeriod)[1]', 'nvarchar(256)') AS [WarrantyPeriod] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        declare namespace wm="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain"; 
        (/p1:ProductDescription/p1:Features/wm:Warranty/wm:Description)[1]', 'nvarchar(256)') AS [WarrantyDescription] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        declare namespace wm="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain"; 
        (/p1:ProductDescription/p1:Features/wm:Maintenance/wm:NoOfYears)[1]', 'nvarchar(256)') AS [NoOfYears] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        declare namespace wm="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain"; 
        (/p1:ProductDescription/p1:Features/wm:Maintenance/wm:Description)[1]', 'nvarchar(256)') AS [MaintenanceDescription] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        declare namespace wf="http://www.adventure-works.com/schemas/OtherFeatures"; 
        (/p1:ProductDescription/p1:Features/wf:wheel)[1]', 'nvarchar(256)') AS [Wheel] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        declare namespace wf="http://www.adventure-works.com/schemas/OtherFeatures"; 
        (/p1:ProductDescription/p1:Features/wf:saddle)[1]', 'nvarchar(256)') AS [Saddle] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        declare namespace wf="http://www.adventure-works.com/schemas/OtherFeatures"; 
        (/p1:ProductDescription/p1:Features/wf:pedal)[1]', 'nvarchar(256)') AS [Pedal] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        declare namespace wf="http://www.adventure-works.com/schemas/OtherFeatures"; 
        (/p1:ProductDescription/p1:Features/wf:BikeFrame)[1]', 'nvarchar(max)') AS [BikeFrame] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        declare namespace wf="http://www.adventure-works.com/schemas/OtherFeatures"; 
        (/p1:ProductDescription/p1:Features/wf:crankset)[1]', 'nvarchar(256)') AS [Crankset] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        (/p1:ProductDescription/p1:Picture/p1:Angle)[1]', 'nvarchar(256)') AS [PictureAngle] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        (/p1:ProductDescription/p1:Picture/p1:Size)[1]', 'nvarchar(256)') AS [PictureSize] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        (/p1:ProductDescription/p1:Picture/p1:ProductPhotoID)[1]', 'nvarchar(256)') AS [ProductPhotoID] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        (/p1:ProductDescription/p1:Specifications/Material)[1]', 'nvarchar(256)') AS [Material] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        (/p1:ProductDescription/p1:Specifications/Color)[1]', 'nvarchar(256)') AS [Color] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        (/p1:ProductDescription/p1:Specifications/ProductLine)[1]', 'nvarchar(256)') AS [ProductLine] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        (/p1:ProductDescription/p1:Specifications/Style)[1]', 'nvarchar(256)') AS [Style] 
    ,[CatalogDescription].value(N'declare namespace p1="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"; 
        (/p1:ProductDescription/p1:Specifications/RiderExperience)[1]', 'nvarchar(1024)') AS [RiderExperience] 
    ,[rowguid] 
    ,[ModifiedDate]
FROM [Production].[ProductModel] 
WHERE [CatalogDescription] IS NOT NULL;

Related objects

tableProduction.ProductModel

View: Production.vProductModelInstructions

View name:Production.vProductModelInstructions
Description:Displays the content from each element in the xml column Instructions for each product in the Production.ProductModel table that has manufacturing instructions.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableProduction.ProductModelProductModelIDint
tableProduction.ProductModelNameName
tableProduction.ProductModelInstructionsnvarcharYes
tableLocationIDintYes
tableSetupHoursdecimal (9.4) Yes
tableMachineHoursdecimal (9.4) Yes
tableLaborHoursdecimal (9.4) Yes
tableLotSizeintYes
tableStepnvarchar (1024) Yes
tableProduction.ProductModelrowguiduniqueidentifier
tableProduction.ProductModelModifiedDatedatetime

View definition

CREATE VIEW [Production].[vProductModelInstructions] 
AS 
SELECT 
    [ProductModelID] 
    ,[Name] 
    ,[Instructions].value(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions"; 
        (/root/text())[1]', 'nvarchar(max)') AS [Instructions] 
    ,[MfgInstructions].ref.value('@LocationID[1]', 'int') AS [LocationID] 
    ,[MfgInstructions].ref.value('@SetupHours[1]', 'decimal(9, 4)') AS [SetupHours] 
    ,[MfgInstructions].ref.value('@MachineHours[1]', 'decimal(9, 4)') AS [MachineHours] 
    ,[MfgInstructions].ref.value('@LaborHours[1]', 'decimal(9, 4)') AS [LaborHours] 
    ,[MfgInstructions].ref.value('@LotSize[1]', 'int') AS [LotSize] 
    ,[Steps].ref.value('string(.)[1]', 'nvarchar(1024)') AS [Step] 
    ,[rowguid] 
    ,[ModifiedDate]
FROM [Production].[ProductModel] 
CROSS APPLY [Instructions].nodes(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions"; 
    /root/Location') MfgInstructions(ref)
CROSS APPLY [MfgInstructions].ref.nodes('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions"; 
    step') Steps(ref);

Related objects

tableProduction.ProductModel

View: Purchasing.vVendor

View name:Purchasing.vVendor
Description:Vendor (company) names and addresses and the names of vendor employees to contact.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tablePurchasing.VendorVendorIDint
tablePurchasing.VendorNameName
tableContactTypeName
tablePerson.ContactTitlenvarchar (8) Yes
tablePerson.ContactFirstNameName
tablePerson.ContactMiddleNameNameYes
tablePerson.ContactLastNameName
tablePerson.ContactSuffixnvarchar (10) Yes
tablePerson.ContactPhonePhoneYes
tablePerson.ContactEmailAddressnvarchar (50) Yes
tablePerson.ContactEmailPromotionint
tablePerson.AddressAddressLine1nvarchar (60)
tablePerson.AddressAddressLine2nvarchar (60) Yes
tablePerson.AddressCitynvarchar (30)
tableStateProvinceNameName
tablePerson.AddressPostalCodenvarchar (15)
tableCountryRegionNameName

View definition

CREATE VIEW [Purchasing].[vVendor] AS 
SELECT 
    v.[VendorID]
    ,v.[Name]
    ,ct.[Name] AS [ContactType]
    ,c.[Title]
    ,c.[FirstName]
    ,c.[MiddleName]
    ,c.[LastName]
    ,c.[Suffix]
    ,c.[Phone]
    ,c.[EmailAddress]
    ,c.[EmailPromotion]
    ,a.[AddressLine1]
    ,a.[AddressLine2]
    ,a.[City]
    ,[StateProvinceName] = sp.[Name]
    ,a.[PostalCode]
    ,[CountryRegionName] = cr.[Name]
FROM [Purchasing].[Vendor] v
    INNER JOIN [Purchasing].[VendorContact] vc 
    ON vc.[VendorID] = v.[VendorID]
    INNER JOIN [Person].[Contact] c 
    ON c.[ContactID] = vc.[ContactID]
    INNER JOIN [Person].[ContactType] ct 
    ON vc.[ContactTypeID] = ct.[ContactTypeID]
    INNER JOIN [Purchasing].[VendorAddress] va 
    ON va.[VendorID] = v.[VendorID]
    INNER JOIN [Person].[Address] a 
    ON a.[AddressID] = va.[AddressID]
    INNER JOIN [Person].[StateProvince] sp 
    ON sp.[StateProvinceID] = a.[StateProvinceID]
    INNER JOIN [Person].[CountryRegion] cr 
    ON cr.[CountryRegionCode] = sp.[CountryRegionCode];

Related objects

tablePerson.Address
tablePerson.CountryRegion
tablePerson.StateProvince
tablePurchasing.VendorAddress
tablePurchasing.VendorContact
tablePerson.ContactType
tablePerson.Contact
tablePurchasing.Vendor

View: Sales.vIndividualCustomer

View name:Sales.vIndividualCustomer
Description:Individual customers (names and addresses) that purchase Adventure Works Cycles products online.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableSales.CustomerCustomerIDint
tablePerson.ContactTitlenvarchar (8) Yes
tablePerson.ContactFirstNameName
tablePerson.ContactMiddleNameNameYes
tablePerson.ContactLastNameName
tablePerson.ContactSuffixnvarchar (10) Yes
tablePerson.ContactPhonePhoneYes
tablePerson.ContactEmailAddressnvarchar (50) Yes
tablePerson.ContactEmailPromotionint
tableAddressTypeName
tablePerson.AddressAddressLine1nvarchar (60)
tablePerson.AddressAddressLine2nvarchar (60) Yes
tablePerson.AddressCitynvarchar (30)
tableStateProvinceNameName
tablePerson.AddressPostalCodenvarchar (15)
tableCountryRegionNameName
tableSales.IndividualDemographicsxmlYes

View definition

CREATE VIEW [Sales].[vIndividualCustomer] 
AS 
SELECT 
    i.[CustomerID]
    ,c.[Title]
    ,c.[FirstName]
    ,c.[MiddleName]
    ,c.[LastName]
    ,c.[Suffix]
    ,c.[Phone]
    ,c.[EmailAddress]
    ,c.[EmailPromotion]
    ,at.[Name] AS [AddressType]
    ,a.[AddressLine1]
    ,a.[AddressLine2]
    ,a.[City]
    ,[StateProvinceName] = sp.[Name]
    ,a.[PostalCode]
    ,[CountryRegionName] = cr.[Name]
    ,i.[Demographics]
FROM [Sales].[Individual] i
    INNER JOIN [Person].[Contact] c 
    ON c.[ContactID] = i.[ContactID]
    INNER JOIN [Sales].[CustomerAddress] ca 
    ON ca.[CustomerID] = i.[CustomerID]
    INNER JOIN [Person].[Address] a 
    ON a.[AddressID] = ca.[AddressID]
    INNER JOIN [Person].[StateProvince] sp 
    ON sp.[StateProvinceID] = a.[StateProvinceID]
    INNER JOIN [Person].[CountryRegion] cr 
    ON cr.[CountryRegionCode] = sp.[CountryRegionCode]
    INNER JOIN [Person].[AddressType] at 
    ON ca.[AddressTypeID] = at.[AddressTypeID]
WHERE i.[CustomerID] IN (SELECT [Sales].[Customer].[CustomerID] 
    FROM [Sales].[Customer] WHERE UPPER([Sales].[Customer].[CustomerType]) = 'I');

Related objects

tablePerson.Address
tableSales.Individual
tablePerson.StateProvince
tablePerson.CountryRegion
tableSales.Customer
tableSales.CustomerAddress
tablePerson.Contact
tablePerson.AddressType

View: Sales.vIndividualDemographics

View name:Sales.vIndividualDemographics
Description:Displays the content from each element in the xml column Demographics for each customer in the Sales.Individual table.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableSales.IndividualCustomerIDint
tableTotalPurchaseYTDmoneyYes
tableDateFirstPurchasedatetimeYes
tableBirthDatedatetimeYes
tableMaritalStatusnvarchar (1) Yes
tableYearlyIncomenvarchar (30) Yes
tableGendernvarchar (1) Yes
tableTotalChildrenintYes
tableNumberChildrenAtHomeintYes
tableEducationnvarchar (30) Yes
tableOccupationnvarchar (30) Yes
tableHomeOwnerFlagbitYes
tableNumberCarsOwnedintYes

View definition

CREATE VIEW [Sales].[vIndividualDemographics] 
AS 
SELECT 
    i.[CustomerID] 
    ,[IndividualSurvey].[ref].[value](N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
        TotalPurchaseYTD[1]', 'money') AS [TotalPurchaseYTD] 
    ,CONVERT(datetime, REPLACE([IndividualSurvey].[ref].[value](N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
        DateFirstPurchase[1]', 'nvarchar(20)') ,'Z', ''), 101) AS [DateFirstPurchase] 
    ,CONVERT(datetime, REPLACE([IndividualSurvey].[ref].[value](N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
        BirthDate[1]', 'nvarchar(20)') ,'Z', ''), 101) AS [BirthDate] 
    ,[IndividualSurvey].[ref].[value](N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
        MaritalStatus[1]', 'nvarchar(1)') AS [MaritalStatus] 
    ,[IndividualSurvey].[ref].[value](N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
        YearlyIncome[1]', 'nvarchar(30)') AS [YearlyIncome] 
    ,[IndividualSurvey].[ref].[value](N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
        Gender[1]', 'nvarchar(1)') AS [Gender] 
    ,[IndividualSurvey].[ref].[value](N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
        TotalChildren[1]', 'integer') AS [TotalChildren] 
    ,[IndividualSurvey].[ref].[value](N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
        NumberChildrenAtHome[1]', 'integer') AS [NumberChildrenAtHome] 
    ,[IndividualSurvey].[ref].[value](N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
        Education[1]', 'nvarchar(30)') AS [Education] 
    ,[IndividualSurvey].[ref].[value](N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
        Occupation[1]', 'nvarchar(30)') AS [Occupation] 
    ,[IndividualSurvey].[ref].[value](N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
        HomeOwnerFlag[1]', 'bit') AS [HomeOwnerFlag] 
    ,[IndividualSurvey].[ref].[value](N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
        NumberCarsOwned[1]', 'integer') AS [NumberCarsOwned] 
FROM [Sales].[Individual] i 
CROSS APPLY i.[Demographics].nodes(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey"; 
    /IndividualSurvey') AS [IndividualSurvey](ref) 
WHERE [Demographics] IS NOT NULL;

Related objects

tableSales.Individual

View: Sales.vSalesPerson

View name:Sales.vSalesPerson
Description:Sales representiatives (names and addresses) and their sales-related information.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableSales.SalesPersonSalesPersonIDint
tablePerson.ContactTitlenvarchar (8) Yes
tablePerson.ContactFirstNameName
tablePerson.ContactMiddleNameNameYes
tablePerson.ContactLastNameName
tablePerson.ContactSuffixnvarchar (10) Yes
tableJobTitlenvarchar (50)
tablePerson.ContactPhonePhoneYes
tablePerson.ContactEmailAddressnvarchar (50) Yes
tablePerson.ContactEmailPromotionint
tablePerson.AddressAddressLine1nvarchar (60)
tablePerson.AddressAddressLine2nvarchar (60) Yes
tablePerson.AddressCitynvarchar (30)
tableStateProvinceNameName
tablePerson.AddressPostalCodenvarchar (15)
tableCountryRegionNameName
tableTerritoryNameNameYes
tableTerritoryGroupnvarchar (50) Yes
tableSales.SalesPersonSalesQuotamoneyYes
tableSales.SalesPersonSalesYTDmoney
tableSales.SalesPersonSalesLastYearmoney

View definition

CREATE VIEW [Sales].[vSalesPerson] 
AS 
SELECT 
    s.[SalesPersonID]
    ,c.[Title]
    ,c.[FirstName]
    ,c.[MiddleName]
    ,c.[LastName]
    ,c.[Suffix]
    ,[JobTitle] = e.[Title]
    ,c.[Phone]
    ,c.[EmailAddress]
    ,c.[EmailPromotion]
    ,a.[AddressLine1]
    ,a.[AddressLine2]
    ,a.[City]
    ,[StateProvinceName] = sp.[Name]
    ,a.[PostalCode]
    ,[CountryRegionName] = cr.[Name]
    ,[TerritoryName] = st.[Name]
    ,[TerritoryGroup] = st.[Group]
    ,s.[SalesQuota]
    ,s.[SalesYTD]
    ,s.[SalesLastYear]
FROM [Sales].[SalesPerson] s
    INNER JOIN [HumanResources].[Employee] e 
    ON e.[EmployeeID] = s.[SalesPersonID]
    LEFT OUTER JOIN [Sales].[SalesTerritory] st 
    ON st.[TerritoryID] = s.[TerritoryID]
    INNER JOIN [Person].[Contact] c 
    ON c.[ContactID] = e.[ContactID]
    INNER JOIN [HumanResources].[EmployeeAddress] ea 
    ON e.[EmployeeID] = ea.[EmployeeID] 
    INNER JOIN [Person].[Address] a 
    ON ea.[AddressID] = a.[AddressID]
    INNER JOIN [Person].[StateProvince] sp 
    ON sp.[StateProvinceID] = a.[StateProvinceID]
    INNER JOIN [Person].[CountryRegion] cr 
    ON cr.[CountryRegionCode] = sp.[CountryRegionCode];

Related objects

tablePerson.Address
tablePerson.StateProvince
tableSales.SalesPerson
tableHumanResources.EmployeeAddress
tableSales.SalesTerritory
tableHumanResources.Employee
tablePerson.Contact
tablePerson.CountryRegion

View: Sales.vSalesPersonSalesByFiscalYears

View name:Sales.vSalesPersonSalesByFiscalYears
Description:Uses PIVOT to return aggregated sales information for each sales representative.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableSales.SalesOrderHeaderSalesPersonIDintYes
tableFullNamenvarchar (152) Yes
tableHumanResources.EmployeeTitlenvarchar (50)
tableSalesTerritoryName
table2002moneyYes
table2003moneyYes
table2004moneyYes

View definition

CREATE VIEW [Sales].[vSalesPersonSalesByFiscalYears] 
AS 
SELECT 
    pvt.[SalesPersonID]
    ,pvt.[FullName]
    ,pvt.[Title]
    ,pvt.[SalesTerritory]
    ,pvt.[2002]
    ,pvt.[2003]
    ,pvt.[2004] 
FROM (SELECT 
        soh.[SalesPersonID]
        ,c.[FirstName] + ' ' + COALESCE(c.[MiddleName], '') + ' ' + c.[LastName] AS [FullName]
        ,e.[Title]
        ,st.[Name] AS [SalesTerritory]
        ,soh.[SubTotal]
        ,YEAR(DATEADD(m, 6, soh.[OrderDate])) AS [FiscalYear] 
    FROM [Sales].[SalesPerson] sp 
        INNER JOIN [Sales].[SalesOrderHeader] soh 
        ON sp.[SalesPersonID] = soh.[SalesPersonID]
        INNER JOIN [Sales].[SalesTerritory] st 
        ON sp.[TerritoryID] = st.[TerritoryID] 
        INNER JOIN [HumanResources].[Employee] e 
        ON soh.[SalesPersonID] = e.[EmployeeID] 
        INNER JOIN [Person].[Contact] c 
        ON e.[ContactID] = c.ContactID 
    ) AS soh 
PIVOT 
(
    SUM([SubTotal]) 
    FOR [FiscalYear] 
    IN ([2002], [2003], [2004])
) AS pvt;

Related objects

tablePerson.Contact
tableSales.SalesOrderHeader
tableSales.SalesTerritory
tableHumanResources.Employee
tableSales.SalesPerson

View: Sales.vStoreWithDemographics

View name:Sales.vStoreWithDemographics
Description:Stores (names and addresses) that sell Adventure Works Cycles products to consumers.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Fields

Source Field name Data type Nullable Field description
tableSales.StoreContactCustomerIDint
tablePerson.AddressTypeNameName
tableContactTypeName
tablePerson.ContactTitlenvarchar (8) Yes
tablePerson.ContactFirstNameName
tablePerson.ContactMiddleNameNameYes
tablePerson.ContactLastNameName
tablePerson.ContactSuffixnvarchar (10) Yes
tablePerson.ContactPhonePhoneYes
tablePerson.ContactEmailAddressnvarchar (50) Yes
tablePerson.ContactEmailPromotionint
tableAddressTypeName
tablePerson.AddressAddressLine1nvarchar (60)
tablePerson.AddressAddressLine2nvarchar (60) Yes
tablePerson.AddressCitynvarchar (30)
tableStateProvinceNameName
tablePerson.AddressPostalCodenvarchar (15)
tableCountryRegionNameName
tableAnnualSalesmoneyYes
tableAnnualRevenuemoneyYes
tableBankNamenvarchar (50) Yes
tableBusinessTypenvarchar (5) Yes
tableYearOpenedintYes
tableSpecialtynvarchar (50) Yes
tableSquareFeetintYes
tableBrandsnvarchar (30) Yes
tableInternetnvarchar (30) Yes
tableNumberEmployeesintYes

View definition

CREATE VIEW [Sales].[vStoreWithDemographics] AS 
SELECT 
    s.[CustomerID] 
    ,s.[Name] 
    ,ct.[Name] AS [ContactType] 
    ,c.[Title] 
    ,c.[FirstName] 
    ,c.[MiddleName] 
    ,c.[LastName] 
    ,c.[Suffix] 
    ,c.[Phone] 
    ,c.[EmailAddress] 
    ,c.[EmailPromotion] 
    ,at.[Name] AS [AddressType]
    ,a.[AddressLine1] 
    ,a.[AddressLine2] 
    ,a.[City] 
    ,sp.[Name] AS [StateProvinceName] 
    ,a.[PostalCode] 
    ,cr.[Name] AS [CountryRegionName] 
    ,s.[Demographics].value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey"; 
        (/StoreSurvey/AnnualSales)[1]', 'money') AS [AnnualSales] 
    ,s.[Demographics].value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey"; 
        (/StoreSurvey/AnnualRevenue)[1]', 'money') AS [AnnualRevenue] 
    ,s.[Demographics].value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey"; 
        (/StoreSurvey/BankName)[1]', 'nvarchar(50)') AS [BankName] 
    ,s.[Demographics].value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey"; 
        (/StoreSurvey/BusinessType)[1]', 'nvarchar(5)') AS [BusinessType] 
    ,s.[Demographics].value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey"; 
        (/StoreSurvey/YearOpened)[1]', 'integer') AS [YearOpened] 
    ,s.[Demographics].value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey"; 
        (/StoreSurvey/Specialty)[1]', 'nvarchar(50)') AS [Specialty] 
    ,s.[Demographics].value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey"; 
        (/StoreSurvey/SquareFeet)[1]', 'integer') AS [SquareFeet] 
    ,s.[Demographics].value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey"; 
        (/StoreSurvey/Brands)[1]', 'nvarchar(30)') AS [Brands] 
    ,s.[Demographics].value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey"; 
        (/StoreSurvey/Internet)[1]', 'nvarchar(30)') AS [Internet] 
    ,s.[Demographics].value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey"; 
        (/StoreSurvey/NumberEmployees)[1]', 'integer') AS [NumberEmployees] 
FROM [Sales].[Store] s
    INNER JOIN [Sales].[StoreContact] sc 
    ON sc.[CustomerID] = s.[CustomerID]
    INNER JOIN [Person].[Contact] c 
    ON c.[ContactID] = sc.[ContactID]
    INNER JOIN [Person].[ContactType] ct 
    ON sc.[ContactTypeID] = ct.[ContactTypeID]
    INNER JOIN [Sales].[CustomerAddress] ca 
    ON ca.[CustomerID] = s.[CustomerID]
    INNER JOIN [Person].[Address] a 
    ON a.[AddressID] = ca.[AddressID]
    INNER JOIN [Person].[StateProvince] sp 
    ON sp.[StateProvinceID] = a.[StateProvinceID]
    INNER JOIN [Person].[CountryRegion] cr 
    ON cr.[CountryRegionCode] = sp.[CountryRegionCode]
    INNER JOIN [Person].[AddressType] at 
    ON ca.[AddressTypeID] = at.[AddressTypeID]
WHERE s.[CustomerID] IN (SELECT [Sales].[Customer].[CustomerID] 
    FROM [Sales].[Customer] WHERE UPPER([Sales].[Customer].[CustomerType]) = 'S');

Related objects

tableSales.StoreContact
tablePerson.Address
tablePerson.StateProvince
tableSales.Store
tableSales.Customer
tableSales.CustomerAddress
tablePerson.Contact
tablePerson.ContactType
tablePerson.CountryRegion
tablePerson.AddressType

Stored procedures

Stored procedure: dbo.uspGetBillOfMaterials

Stored procedure name:dbo.uspGetBillOfMaterials
Description:Stored procedure using a recursive query to return a multi-level bill of material for the specified ProductID.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
IN@StartProductIDintInput parameter for the stored procedure uspGetBillOfMaterials. Enter a valid ProductID from the Production.Product table.
IN@CheckDatedatetimeInput parameter for the stored procedure uspGetBillOfMaterials used to eliminate components not used after that date. Enter a valid date.

Stored procedure definition

CREATE PROCEDURE [dbo].[uspGetBillOfMaterials]
    @StartProductID [int],
    @CheckDate [datetime]
AS
BEGIN
    SET NOCOUNT ON;

    -- Use recursive query to generate a multi-level Bill of Material (i.e. all level 1 
    -- components of a level 0 assembly, all level 2 components of a level 1 assembly)
    -- The CheckDate eliminates any components that are no longer used in the product on this date.
    WITH [BOM_cte]([ProductAssemblyID], [ComponentID], [ComponentDesc], [PerAssemblyQty], [StandardCost], [ListPrice], [BOMLevel], [RecursionLevel]) -- CTE name and columns
    AS (
        SELECT b.[ProductAssemblyID], b.[ComponentID], p.[Name], b.[PerAssemblyQty], p.[StandardCost], p.[ListPrice], b.[BOMLevel], 0 -- Get the initial list of components for the bike assembly
        FROM [Production].[BillOfMaterials] b
            INNER JOIN [Production].[Product] p 
            ON b.[ComponentID] = p.[ProductID] 
        WHERE b.[ProductAssemblyID] = @StartProductID 
            AND @CheckDate >= b.[StartDate] 
            AND @CheckDate <= ISNULL(b.[EndDate], @CheckDate)
        UNION ALL
        SELECT b.[ProductAssemblyID], b.[ComponentID], p.[Name], b.[PerAssemblyQty], p.[StandardCost], p.[ListPrice], b.[BOMLevel], [RecursionLevel] + 1 -- Join recursive member to anchor
        FROM [BOM_cte] cte
            INNER JOIN [Production].[BillOfMaterials] b 
            ON b.[ProductAssemblyID] = cte.[ComponentID]
            INNER JOIN [Production].[Product] p 
            ON b.[ComponentID] = p.[ProductID] 
        WHERE @CheckDate >= b.[StartDate] 
            AND @CheckDate <= ISNULL(b.[EndDate], @CheckDate)
        )
    -- Outer select from the CTE
    SELECT b.[ProductAssemblyID], b.[ComponentID], b.[ComponentDesc], SUM(b.[PerAssemblyQty]) AS [TotalQuantity] , b.[StandardCost], b.[ListPrice], b.[BOMLevel], b.[RecursionLevel]
    FROM [BOM_cte] b
    GROUP BY b.[ComponentID], b.[ComponentDesc], b.[ProductAssemblyID], b.[BOMLevel], b.[RecursionLevel], b.[StandardCost], b.[ListPrice]
    ORDER BY b.[BOMLevel], b.[ProductAssemblyID], b.[ComponentID]
    OPTION (MAXRECURSION 25) 
END;

Related objects

tableProduction.BillOfMaterials
tableProduction.Product

Stored procedure: dbo.uspGetEmployeeManagers

Stored procedure name:dbo.uspGetEmployeeManagers
Description:Stored procedure using a recursive query to return the direct and indirect managers of the specified employee.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
IN@EmployeeIDintInput parameter for the stored procedure uspGetEmployeeManagers. Enter a valid EmployeeID from the HumanResources.Employee table.

Stored procedure definition

CREATE PROCEDURE [dbo].[uspGetEmployeeManagers]
    @EmployeeID [int]
AS
BEGIN
    SET NOCOUNT ON;

    -- Use recursive query to list out all Employees required for a particular Manager
    WITH [EMP_cte]([EmployeeID], [ManagerID], [FirstName], [LastName], [Title], [RecursionLevel]) -- CTE name and columns
    AS (
        SELECT e.[EmployeeID], e.[ManagerID], c.[FirstName], c.[LastName], e.[Title], 0 -- Get the initial Employee
        FROM [HumanResources].[Employee] e 
            INNER JOIN [Person].[Contact] c 
            ON e.[ContactID] = c.[ContactID]
        WHERE e.[EmployeeID] = @EmployeeID
        UNION ALL
        SELECT e.[EmployeeID], e.[ManagerID], c.[FirstName], c.[LastName], e.[Title], [RecursionLevel] + 1 -- Join recursive member to anchor
        FROM [HumanResources].[Employee] e 
            INNER JOIN [EMP_cte]
            ON e.[EmployeeID] = [EMP_cte].[ManagerID]
            INNER JOIN [Person].[Contact] c 
            ON e.[ContactID] = c.[ContactID]
    )
    -- Join back to Employee to return the manager name 
    SELECT [EMP_cte].[RecursionLevel], [EMP_cte].[EmployeeID], [EMP_cte].[FirstName], [EMP_cte].[LastName], 
        [EMP_cte].[ManagerID], c.[FirstName] AS 'ManagerFirstName', c.[LastName] AS 'ManagerLastName'  -- Outer select from the CTE
    FROM [EMP_cte] 
        INNER JOIN [HumanResources].[Employee] e 
        ON [EMP_cte].[ManagerID] = e.[EmployeeID]
        INNER JOIN [Person].[Contact] c 
        ON e.[ContactID] = c.[ContactID]
    ORDER BY [RecursionLevel], [ManagerID], [EmployeeID]
    OPTION (MAXRECURSION 25) 
END;

Related objects

tablePerson.Contact
tableHumanResources.Employee

Stored procedure: dbo.uspGetManagerEmployees

Stored procedure name:dbo.uspGetManagerEmployees
Description:Stored procedure using a recursive query to return the direct and indirect employees of the specified manager.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
IN@ManagerIDintInput parameter for the stored procedure uspGetManagerEmployees. Enter a valid ManagerID from the HumanResources.Employee table.

Stored procedure definition

CREATE PROCEDURE [dbo].[uspGetManagerEmployees]
    @ManagerID [int]
AS
BEGIN
    SET NOCOUNT ON;

    -- Use recursive query to list out all Employees required for a particular Manager
    WITH [EMP_cte]([EmployeeID], [ManagerID], [FirstName], [LastName], [RecursionLevel]) -- CTE name and columns
    AS (
        SELECT e.[EmployeeID], e.[ManagerID], c.[FirstName], c.[LastName], 0 -- Get the initial list of Employees for Manager n
        FROM [HumanResources].[Employee] e 
            INNER JOIN [Person].[Contact] c 
            ON e.[ContactID] = c.[ContactID]
        WHERE [ManagerID] = @ManagerID
        UNION ALL
        SELECT e.[EmployeeID], e.[ManagerID], c.[FirstName], c.[LastName], [RecursionLevel] + 1 -- Join recursive member to anchor
        FROM [HumanResources].[Employee] e 
            INNER JOIN [EMP_cte]
            ON e.[ManagerID] = [EMP_cte].[EmployeeID]
            INNER JOIN [Person].[Contact] c 
            ON e.[ContactID] = c.[ContactID]
        )
    -- Join back to Employee to return the manager name 
    SELECT [EMP_cte].[RecursionLevel], [EMP_cte].[ManagerID], c.[FirstName] AS 'ManagerFirstName', c.[LastName] AS 'ManagerLastName',
        [EMP_cte].[EmployeeID], [EMP_cte].[FirstName], [EMP_cte].[LastName] -- Outer select from the CTE
    FROM [EMP_cte] 
        INNER JOIN [HumanResources].[Employee] e 
        ON [EMP_cte].[ManagerID] = e.[EmployeeID]
        INNER JOIN [Person].[Contact] c 
        ON e.[ContactID] = c.[ContactID]
    ORDER BY [RecursionLevel], [ManagerID], [EmployeeID]
    OPTION (MAXRECURSION 25) 
END;

Related objects

tablePerson.Contact
tableHumanResources.Employee

Stored procedure: dbo.uspGetWhereUsedProductID

Stored procedure name:dbo.uspGetWhereUsedProductID
Description:Stored procedure using a recursive query to return all components or assemblies that directly or indirectly use the specified ProductID.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
IN@StartProductIDintInput parameter for the stored procedure uspGetWhereUsedProductID. Enter a valid ProductID from the Production.Product table.
IN@CheckDatedatetimeInput parameter for the stored procedure uspGetWhereUsedProductID used to eliminate components not used after that date. Enter a valid date.

Stored procedure definition

CREATE PROCEDURE [dbo].[uspGetWhereUsedProductID]
    @StartProductID [int],
    @CheckDate [datetime]
AS
BEGIN
    SET NOCOUNT ON;

    --Use recursive query to generate a multi-level Bill of Material (i.e. all level 1 components of a level 0 assembly, all level 2 components of a level 1 assembly)
    WITH [BOM_cte]([ProductAssemblyID], [ComponentID], [ComponentDesc], [PerAssemblyQty], [StandardCost], [ListPrice], [BOMLevel], [RecursionLevel]) -- CTE name and columns
    AS (
        SELECT b.[ProductAssemblyID], b.[ComponentID], p.[Name], b.[PerAssemblyQty], p.[StandardCost], p.[ListPrice], b.[BOMLevel], 0 -- Get the initial list of components for the bike assembly
        FROM [Production].[BillOfMaterials] b
            INNER JOIN [Production].[Product] p 
            ON b.[ProductAssemblyID] = p.[ProductID] 
        WHERE b.[ComponentID] = @StartProductID 
            AND @CheckDate >= b.[StartDate] 
            AND @CheckDate <= ISNULL(b.[EndDate], @CheckDate)
        UNION ALL
        SELECT b.[ProductAssemblyID], b.[ComponentID], p.[Name], b.[PerAssemblyQty], p.[StandardCost], p.[ListPrice], b.[BOMLevel], [RecursionLevel] + 1 -- Join recursive member to anchor
        FROM [BOM_cte] cte
            INNER JOIN [Production].[BillOfMaterials] b 
            ON cte.[ProductAssemblyID] = b.[ComponentID]
            INNER JOIN [Production].[Product] p 
            ON b.[ProductAssemblyID] = p.[ProductID] 
        WHERE @CheckDate >= b.[StartDate] 
            AND @CheckDate <= ISNULL(b.[EndDate], @CheckDate)
        )
    -- Outer select from the CTE
    SELECT b.[ProductAssemblyID], b.[ComponentID], b.[ComponentDesc], SUM(b.[PerAssemblyQty]) AS [TotalQuantity] , b.[StandardCost], b.[ListPrice], b.[BOMLevel], b.[RecursionLevel]
    FROM [BOM_cte] b
    GROUP BY b.[ComponentID], b.[ComponentDesc], b.[ProductAssemblyID], b.[BOMLevel], b.[RecursionLevel], b.[StandardCost], b.[ListPrice]
    ORDER BY b.[BOMLevel], b.[ProductAssemblyID], b.[ComponentID]
    OPTION (MAXRECURSION 25) 
END;

Related objects

tableProduction.BillOfMaterials
tableProduction.Product

Stored procedure: dbo.uspLogError

Stored procedure name:dbo.uspLogError
Description:Logs error information in the ErrorLog table about the error that caused execution to jump to the CATCH block of a TRY...CATCH construct. Should be executed from within the scope of a CATCH block otherwise it will return without inserting error information.
Creation date:26 Apr 2006
Last altered date:26 Oct 2008

Parameters

DirectionParameter nameData typeDescription
INOUT@ErrorLogIDintOutput parameter for the stored procedure uspLogError. Contains the ErrorLogID value corresponding to the row inserted by uspLogError in the ErrorLog table.

Stored procedure definition

-- uspLogError logs error information in the ErrorLog table about the 
-- error that caused execution to jump to the CATCH block of a 
-- TRY...CATCH construct. This should be executed from within the scope 
-- of a CATCH block otherwise it will return without inserting error 
-- information. 
CREATE PROCEDURE [dbo].[uspLogError] 
    @ErrorLogID [int] = 0 OUTPUT -- contains the ErrorLogID of the row inserted
AS                               -- by uspLogError in the ErrorLog table
BEGIN
    SET NOCOUNT ON;

    -- Output parameter value of 0 indicates that error 
    -- information was not logged
    SET @ErrorLogID = 0;

    BEGIN TRY
        -- Return if there is no error information to log
        IF ERROR_NUMBER() IS NULL
            RETURN;

        -- Return if inside an uncommittable transaction.
        -- Data insertion/modification is not allowed when 
        -- a transaction is in an uncommittable state.
        IF XACT_STATE() = -1
        BEGIN
            PRINT 'Cannot log error since the current transaction is in an uncommittable state. ' 
                + 'Rollback the transaction before executing uspLogError in order to successfully log error information.';
            RETURN;
        END

        INSERT [dbo].[ErrorLog] 
            (
            [UserName], 
            [ErrorNumber], 
            [ErrorSeverity], 
            [ErrorState], 
            [ErrorProcedure], 
            [ErrorLine], 
            [ErrorMessage]
            ) 
        VALUES 
            (
            CONVERT(sysname, CURRENT_USER), 
            ERROR_NUMBER(),
            ERROR_SEVERITY(),
            ERROR_STATE(),
            ERROR_PROCEDURE(),
            ERROR_LINE(),
            ERROR_MESSAGE()
            );

        -- Pass back the ErrorLogID of the row inserted
        SET @ErrorLogID = @@IDENTITY;
    END TRY
    BEGIN CATCH
        PRINT 'An error occurred in stored procedure uspLogError: ';
        EXECUTE [dbo].[uspPrintError];
        RETURN -1;
    END CATCH
END;

Related objects

stored proceduredbo.uspPrintError
tabledbo.ErrorLog

Objects that depend on dbo.uspLogError

stored procedureHumanResources.uspUpdateEmployeeHireInfo
stored procedureHumanResources.uspUpdateEmployeeLogin
stored procedureHumanResources.uspUpdateEmployeePersonalInfo
triggerProduction.iWorkOrder
triggerProduction.uWorkOrder
triggerPurchasing.dVendor
triggerPurchasing.iPurchaseOrderDetail
triggerPurchasing.uPurchaseOrderDetail
triggerPurchasing.uPurchaseOrderHeader
triggerSales.iduSalesOrderDetail
triggerSales.iStore
triggerSales.uSalesOrderHeader

Stored procedure: dbo.uspPrintError

Stored procedure name:dbo.uspPrintError
Description:Prints error information about the error that caused execution to jump to the CATCH block of a TRY...CATCH construct. Should be executed from within the scope of a CATCH block otherwise it will return without printing any error information.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Stored procedure definition

-- uspPrintError prints error information about the error that caused 
-- execution to jump to the CATCH block of a TRY...CATCH construct. 
-- Should be executed from within the scope of a CATCH block otherwise 
-- it will return without printing any error information.
CREATE PROCEDURE [dbo].[uspPrintError] 
AS
BEGIN
    SET NOCOUNT ON;

    -- Print error information. 
    PRINT 'Error ' + CONVERT(varchar(50), ERROR_NUMBER()) +
          ', Severity ' + CONVERT(varchar(5), ERROR_SEVERITY()) +
          ', State ' + CONVERT(varchar(5), ERROR_STATE()) + 
          ', Procedure ' + ISNULL(ERROR_PROCEDURE(), '-') + 
          ', Line ' + CONVERT(varchar(5), ERROR_LINE());
    PRINT ERROR_MESSAGE();
END;

Objects that depend on dbo.uspPrintError

dbo.ufnGetContactInformation
stored proceduredbo.uspLogError
triggerProduction.iWorkOrder
triggerProduction.uWorkOrder
triggerPurchasing.dVendor
triggerPurchasing.iPurchaseOrderDetail
triggerPurchasing.uPurchaseOrderDetail
triggerPurchasing.uPurchaseOrderHeader
triggerSales.iduSalesOrderDetail
triggerSales.iStore
triggerSales.uSalesOrderHeader

Stored procedure: HumanResources.uspUpdateEmployeeHireInfo

Stored procedure name:HumanResources.uspUpdateEmployeeHireInfo
Description:Updates the Employee table and inserts a new row in the EmployeePayHistory table with the values specified in the input parameters.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
IN@EmployeeIDintInput parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter a valid EmployeeID from the Employee table.
IN@Titlenvarchar (50) Input parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter a title for the employee.
IN@HireDatedatetimeInput parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter a hire date for the employee.
IN@RateChangeDatedatetimeInput parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter the date the rate changed for the employee.
IN@RatemoneyInput parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter the new rate for the employee.
IN@PayFrequencytinyintInput parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter the pay frequency for the employee.
IN@CurrentFlagbitInput parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter the current flag for the employee.

Stored procedure definition

CREATE PROCEDURE [HumanResources].[uspUpdateEmployeeHireInfo]
    @EmployeeID [int], 
    @Title [nvarchar](50), 
    @HireDate [datetime], 
    @RateChangeDate [datetime], 
    @Rate [money], 
    @PayFrequency [tinyint], 
    @CurrentFlag [dbo].[Flag] 
WITH EXECUTE AS CALLER
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        BEGIN TRANSACTION;

        UPDATE [HumanResources].[Employee] 
        SET [Title] = @Title 
            ,[HireDate] = @HireDate 
            ,[CurrentFlag] = @CurrentFlag 
        WHERE [EmployeeID] = @EmployeeID;

        INSERT INTO [HumanResources].[EmployeePayHistory] 
            ([EmployeeID]
            ,[RateChangeDate]
            ,[Rate]
            ,[PayFrequency]) 
        VALUES (@EmployeeID, @RateChangeDate, @Rate, @PayFrequency);

        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Related objects

stored proceduredbo.uspLogError
tableHumanResources.Employee
tableHumanResources.EmployeePayHistory

Stored procedure: HumanResources.uspUpdateEmployeeLogin

Stored procedure name:HumanResources.uspUpdateEmployeeLogin
Description:Updates the Employee table with the values specified in the input parameters for the given EmployeeID.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
IN@EmployeeIDintInput parameter for the stored procedure uspUpdateEmployeeLogin. Enter a valid EmployeeID from the Employee table.
IN@ManagerIDintInput parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter a valid ManagerID for the employee.
IN@LoginIDnvarchar (256) Input parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter a valid login for the employee.
IN@Titlenvarchar (50) Input parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter a title for the employee.
IN@HireDatedatetimeInput parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter a hire date for the employee.
IN@CurrentFlagbitInput parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter the current flag for the employee.

Stored procedure definition

CREATE PROCEDURE [HumanResources].[uspUpdateEmployeeLogin]
    @EmployeeID [int], 
    @ManagerID [int],
    @LoginID [nvarchar](256),
    @Title [nvarchar](50),
    @HireDate [datetime],
    @CurrentFlag [dbo].[Flag]
WITH EXECUTE AS CALLER
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        UPDATE [HumanResources].[Employee] 
        SET [ManagerID] = @ManagerID 
            ,[LoginID] = @LoginID 
            ,[Title] = @Title 
            ,[HireDate] = @HireDate 
            ,[CurrentFlag] = @CurrentFlag 
        WHERE [EmployeeID] = @EmployeeID;
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Related objects

stored proceduredbo.uspLogError
tableHumanResources.Employee

Stored procedure: HumanResources.uspUpdateEmployeePersonalInfo

Stored procedure name:HumanResources.uspUpdateEmployeePersonalInfo
Description:Updates the Employee table with the values specified in the input parameters for the given EmployeeID.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
IN@EmployeeIDintInput parameter for the stored procedure uspUpdateEmployeePersonalInfo. Enter a valid EmployeeID from the HumanResources.Employee table.
IN@NationalIDNumbernvarchar (15) Input parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter a national ID for the employee.
IN@BirthDatedatetimeInput parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter a birth date for the employee.
IN@MaritalStatusnchar (1) Input parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter a marital status for the employee.
IN@Gendernchar (1) Input parameter for the stored procedure uspUpdateEmployeeHireInfo. Enter a gender for the employee.

Stored procedure definition

CREATE PROCEDURE [HumanResources].[uspUpdateEmployeePersonalInfo]
    @EmployeeID [int], 
    @NationalIDNumber [nvarchar](15), 
    @BirthDate [datetime], 
    @MaritalStatus [nchar](1), 
    @Gender [nchar](1)
WITH EXECUTE AS CALLER
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        UPDATE [HumanResources].[Employee] 
        SET [NationalIDNumber] = @NationalIDNumber 
            ,[BirthDate] = @BirthDate 
            ,[MaritalStatus] = @MaritalStatus 
            ,[Gender] = @Gender 
        WHERE [EmployeeID] = @EmployeeID;
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Related objects

stored proceduredbo.uspLogError
tableHumanResources.Employee

User-defined functions

UDF: dbo.ufnGetAccountingEndDate

UDF name:dbo.ufnGetAccountingEndDate
Description:Scalar function used in the uSalesOrderHeader trigger to set the starting account date.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
OUTdatetime

User-defined function definition

CREATE FUNCTION [dbo].[ufnGetAccountingEndDate]()
RETURNS [datetime] 
AS 
BEGIN
    RETURN DATEADD(millisecond, -2, CONVERT(datetime, '20040701', 112));
END;

UDF: dbo.ufnGetAccountingStartDate

UDF name:dbo.ufnGetAccountingStartDate
Description:Scalar function used in the uSalesOrderHeader trigger to set the ending account date.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
OUTdatetime

User-defined function definition

CREATE FUNCTION [dbo].[ufnGetAccountingStartDate]()
RETURNS [datetime] 
AS 
BEGIN
    RETURN CONVERT(datetime, '20030701', 112);
END;

UDF: dbo.ufnGetContactInformation

UDF name:dbo.ufnGetContactInformation
Description:
Creation date:26 Apr 2006
Last altered date:26 Oct 2008

Parameters

DirectionParameter nameData typeDescription
IN@ContactIDintInput parameter for the table value function ufnGetContactInformation. Enter a valid ContactID from the Person.Contact table.

User-defined function definition

CREATE FUNCTION [dbo].[ufnGetContactInformation](@ContactID int)
RETURNS @retContactInformation TABLE 
(
    -- Columns returned by the function
    [ContactID] int PRIMARY KEY NOT NULL, 
    [FirstName] [nvarchar](50) NULL, 
    [LastName] [nvarchar](50) NULL, 
    [JobTitle] [nvarchar](50) NULL, 
    [ContactType] [nvarchar](50) NULL
)
AS 
-- Returns the first name, last name, job title and contact type for the specified contact.
BEGIN
    DECLARE 
        @FirstName [nvarchar](50), 
        @LastName [nvarchar](50), 
        @JobTitle [nvarchar](50), 
        @ContactType [nvarchar](50);

    -- Get common contact information
    SELECT 
        @ContactID = ContactID, 
        @FirstName = FirstName, 
        @LastName = LastName
    FROM [Person].[Contact] 
    WHERE [ContactID] = @ContactID;

    SET @JobTitle = 
        CASE 
            -- Check for employee
            WHEN EXISTS(SELECT * FROM [HumanResources].[Employee] e 
                WHERE e.[ContactID] = @ContactID) 
                THEN (SELECT [Title] 
                    FROM [HumanResources].[Employee] 
                    WHERE [ContactID] = @ContactID)

            -- Check for vendor
            WHEN EXISTS(SELECT * FROM [Purchasing].[VendorContact] vc 
                    INNER JOIN [Person].[ContactType] ct 
                    ON vc.[ContactTypeID] = ct.[ContactTypeID] 
                WHERE vc.[ContactID] = @ContactID) 
                THEN (SELECT ct.[Name] 
                    FROM [Purchasing].[VendorContact] vc 
                        INNER JOIN [Person].[ContactType] ct 
                        ON vc.[ContactTypeID] = ct.[ContactTypeID] 
                    WHERE vc.[ContactID] = @ContactID)

            -- Check for store
            WHEN EXISTS(SELECT * FROM [Sales].[StoreContact] sc 
                    INNER JOIN [Person].[ContactType] ct 
                    ON sc.[ContactTypeID] = ct.[ContactTypeID] 
                WHERE sc.[ContactID] = @ContactID) 
                THEN (SELECT ct.[Name] 
                    FROM [Sales].[StoreContact] sc 
                        INNER JOIN [Person].[ContactType] ct 
                        ON sc.[ContactTypeID] = ct.[ContactTypeID] 
                    WHERE [ContactID] = @ContactID)

            ELSE NULL 
        END;

    SET @ContactType = 
        CASE 
            -- Check for employee
            WHEN EXISTS(SELECT * FROM [HumanResources].[Employee] e 
                WHERE e.[ContactID] = @ContactID) 
                THEN 'Employee'

            -- Check for vendor
            WHEN EXISTS(SELECT * FROM [Purchasing].[VendorContact] vc 
                    INNER JOIN [Person].[ContactType] ct 
                    ON vc.[ContactTypeID] = ct.[ContactTypeID] 
                WHERE vc.[ContactID] = @ContactID) 
                THEN 'Vendor Contact'

            -- Check for store
            WHEN EXISTS(SELECT * FROM [Sales].[StoreContact] sc 
                    INNER JOIN [Person].[ContactType] ct 
                    ON sc.[ContactTypeID] = ct.[ContactTypeID] 
                WHERE sc.[ContactID] = @ContactID) 
                THEN 'Store Contact'

            -- Check for individual consumer
            WHEN EXISTS(SELECT * FROM [Sales].[Individual] i 
                WHERE i.[ContactID] = @ContactID) 
                THEN 'Consumer'
        END;

    -- Return the information to the caller
    IF @ContactID IS NOT NULL 
    BEGIN
		EXECUTE [dbo].[uspPrintError];
        INSERT @retContactInformation
        SELECT @ContactID, @FirstName, @LastName, @JobTitle, @ContactType;
    END;

    RETURN;
END;

Related objects

stored proceduredbo.uspPrintError
tableSales.StoreContact
tablePerson.Contact
tablePurchasing.VendorContact
tablePerson.ContactType
tableHumanResources.Employee
tableSales.Individual

UDF: dbo.ufnGetDocumentStatusText

UDF name:dbo.ufnGetDocumentStatusText
Description:Scalar function returning the text representation of the Status column in the Document table.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
OUTnvarchar (16)
IN@StatustinyintInput parameter for the scalar function ufnGetDocumentStatusText. Enter a valid integer.

User-defined function definition

CREATE FUNCTION [dbo].[ufnGetDocumentStatusText](@Status [tinyint])
RETURNS [nvarchar](16) 
AS 
-- Returns the sales order status text representation for the status value.
BEGIN
    DECLARE @ret [nvarchar](16);

    SET @ret = 
        CASE @Status
            WHEN 1 THEN N'Pending approval'
            WHEN 2 THEN N'Approved'
            WHEN 3 THEN N'Obsolete'
            ELSE N'** Invalid **'
        END;
    
    RETURN @ret
END;

UDF: dbo.ufnGetProductDealerPrice

UDF name:dbo.ufnGetProductDealerPrice
Description:Scalar function returning the dealer price for a given product on a particular order date.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
OUTmoney
IN@ProductIDintInput parameter for the scalar function ufnGetProductDealerPrice. Enter a valid ProductID from the Production.Product table.
IN@OrderDatedatetimeInput parameter for the scalar function ufnGetProductDealerPrice. Enter a valid order date.

User-defined function definition

CREATE FUNCTION [dbo].[ufnGetProductDealerPrice](@ProductID [int], @OrderDate [datetime])
RETURNS [money] 
AS 
-- Returns the dealer price for the product on a specific date.
BEGIN
    DECLARE @DealerPrice money;
    DECLARE @DealerDiscount money;

    SET @DealerDiscount = 0.60  -- 60% of list price

    SELECT @DealerPrice = plph.[ListPrice] * @DealerDiscount 
    FROM [Production].[Product] p 
        INNER JOIN [Production].[ProductListPriceHistory] plph 
        ON p.[ProductID] = plph.[ProductID] 
            AND p.[ProductID] = @ProductID 
            AND @OrderDate BETWEEN plph.[StartDate] AND COALESCE(plph.[EndDate], CONVERT(datetime, '99991231', 112)); -- Make sure we get all the prices!

    RETURN @DealerPrice;
END;

Related objects

tableProduction.Product
tableProduction.ProductListPriceHistory

UDF: dbo.ufnGetProductListPrice

UDF name:dbo.ufnGetProductListPrice
Description:Scalar function returning the list price for a given product on a particular order date.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
OUTmoney
IN@ProductIDintInput parameter for the scalar function ufnGetProductListPrice. Enter a valid ProductID from the Production.Product table.
IN@OrderDatedatetimeInput parameter for the scalar function ufnGetProductListPrice. Enter a valid order date.

User-defined function definition

CREATE FUNCTION [dbo].[ufnGetProductListPrice](@ProductID [int], @OrderDate [datetime])
RETURNS [money] 
AS 
BEGIN
    DECLARE @ListPrice money;

    SELECT @ListPrice = plph.[ListPrice] 
    FROM [Production].[Product] p 
        INNER JOIN [Production].[ProductListPriceHistory] plph 
        ON p.[ProductID] = plph.[ProductID] 
            AND p.[ProductID] = @ProductID 
            AND @OrderDate BETWEEN plph.[StartDate] AND COALESCE(plph.[EndDate], CONVERT(datetime, '99991231', 112)); -- Make sure we get all the prices!

    RETURN @ListPrice;
END;

Related objects

tableProduction.Product
tableProduction.ProductListPriceHistory

UDF: dbo.ufnGetProductStandardCost

UDF name:dbo.ufnGetProductStandardCost
Description:Scalar function returning the standard cost for a given product on a particular order date.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
OUTmoney
IN@ProductIDintInput parameter for the scalar function ufnGetProductStandardCost. Enter a valid ProductID from the Production.Product table.
IN@OrderDatedatetimeInput parameter for the scalar function ufnGetProductStandardCost. Enter a valid order date.

User-defined function definition

CREATE FUNCTION [dbo].[ufnGetProductStandardCost](@ProductID [int], @OrderDate [datetime])
RETURNS [money] 
AS 
-- Returns the standard cost for the product on a specific date.
BEGIN
    DECLARE @StandardCost money;

    SELECT @StandardCost = pch.[StandardCost] 
    FROM [Production].[Product] p 
        INNER JOIN [Production].[ProductCostHistory] pch 
        ON p.[ProductID] = pch.[ProductID] 
            AND p.[ProductID] = @ProductID 
            AND @OrderDate BETWEEN pch.[StartDate] AND COALESCE(pch.[EndDate], CONVERT(datetime, '99991231', 112)); -- Make sure we get all the prices!

    RETURN @StandardCost;
END;

Related objects

tableProduction.Product
tableProduction.ProductCostHistory

UDF: dbo.ufnGetPurchaseOrderStatusText

UDF name:dbo.ufnGetPurchaseOrderStatusText
Description:Scalar function returning the text representation of the Status column in the PurchaseOrderHeader table.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
OUTnvarchar (15)
IN@StatustinyintInput parameter for the scalar function ufnGetPurchaseOrdertStatusText. Enter a valid integer.

User-defined function definition

CREATE FUNCTION [dbo].[ufnGetPurchaseOrderStatusText](@Status [tinyint])
RETURNS [nvarchar](15) 
AS 
-- Returns the sales order status text representation for the status value.
BEGIN
    DECLARE @ret [nvarchar](15);

    SET @ret = 
        CASE @Status
            WHEN 1 THEN 'Pending'
            WHEN 2 THEN 'Approved'
            WHEN 3 THEN 'Rejected'
            WHEN 4 THEN 'Complete'
            ELSE '** Invalid **'
        END;
    
    RETURN @ret
END;

UDF: dbo.ufnGetSalesOrderStatusText

UDF name:dbo.ufnGetSalesOrderStatusText
Description:Scalar function returning the text representation of the Status column in the SalesOrderHeader table.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
OUTnvarchar (15)
IN@StatustinyintInput parameter for the scalar function ufnGetSalesOrderStatusText. Enter a valid integer.

User-defined function definition

CREATE FUNCTION [dbo].[ufnGetSalesOrderStatusText](@Status [tinyint])
RETURNS [nvarchar](15) 
AS 
-- Returns the sales order status text representation for the status value.
BEGIN
    DECLARE @ret [nvarchar](15);

    SET @ret = 
        CASE @Status
            WHEN 1 THEN 'In process'
            WHEN 2 THEN 'Approved'
            WHEN 3 THEN 'Backordered'
            WHEN 4 THEN 'Rejected'
            WHEN 5 THEN 'Shipped'
            WHEN 6 THEN 'Cancelled'
            ELSE '** Invalid **'
        END;
    
    RETURN @ret
END;

UDF: dbo.ufnGetStock

UDF name:dbo.ufnGetStock
Description:Scalar function returning the quantity of inventory in LocationID 6 (Miscellaneous Storage)for a specified ProductID.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
OUTint
IN@ProductIDintInput parameter for the scalar function ufnGetStock. Enter a valid ProductID from the Production.ProductInventory table.

User-defined function definition

CREATE FUNCTION [dbo].[ufnGetStock](@ProductID [int])
RETURNS [int] 
AS 
-- Returns the stock level for the product. This function is used internally only
BEGIN
    DECLARE @ret int;
    
    SELECT @ret = SUM(p.[Quantity]) 
    FROM [Production].[ProductInventory] p 
    WHERE p.[ProductID] = @ProductID 
        AND p.[LocationID] = '6'; -- Only look at inventory in the misc storage
    
    IF (@ret IS NULL) 
        SET @ret = 0
    
    RETURN @ret
END;

Related objects

tableProduction.ProductInventory

UDF: dbo.ufnLeadingZeros

UDF name:dbo.ufnLeadingZeros
Description:Scalar function used by the Sales.Customer table to help set the account number.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Parameters

DirectionParameter nameData typeDescription
OUTvarchar (8)
IN@ValueintInput parameter for the scalar function ufnLeadingZeros. Enter a valid integer.

User-defined function definition

CREATE FUNCTION [dbo].[ufnLeadingZeros](
    @Value int
) 
RETURNS varchar(8) 
WITH SCHEMABINDING 
AS 
BEGIN
    DECLARE @ReturnValue varchar(8);

    SET @ReturnValue = CONVERT(varchar(8), @Value);
    SET @ReturnValue = REPLICATE('0', 8 - DATALENGTH(@ReturnValue)) + @ReturnValue;

    RETURN (@ReturnValue);
END;

Objects that depend on dbo.ufnLeadingZeros

tableSales.Customer

User-defined types

UDT name Base type Nullable Description
AccountNumbernvarchar (15) null
Flagbitnot null
Namenvarchar (50) null
NameStylebitnot null
OrderNumbernvarchar (25) null
Phonenvarchar (25) null

XML Schemas

XML schema: HumanResources.HRResumeSchemaCollection

XML schema name:HumanResources.HRResumeSchemaCollection
Description:Collection of XML schemas for the Resume column in the HumanResources.JobCandidate table.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Components

Component nameTypeDerivationNamespace
AddressTypeCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
EducationTypeCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
EmploymentTypeCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
LocationTypeCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
NameTypeCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
ResumeTypeCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
TelephoneTypeCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Addr.LocationELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Addr.OrgNameELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Addr.PostalCodeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Addr.StreetELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Addr.TelephoneELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Addr.TypeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
AddressELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
EMailELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Edu.DegreeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Edu.EndDateELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Edu.GPAELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Edu.GPAAlternateELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Edu.GPAScaleELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Edu.LevelELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Edu.LocationELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Edu.MajorELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Edu.MinorELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Edu.SchoolELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Edu.StartDateELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
EducationELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Emp.EndDateELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Emp.FunctionCategoryELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Emp.IndustryCategoryELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Emp.JobTitleELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Emp.LocationELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Emp.OrgNameELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Emp.ResponsibilityELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Emp.StartDateELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
EmploymentELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Loc.CityELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Loc.CountryRegionELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Loc.StateELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
LocationELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
NameELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Name.FirstELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Name.LastELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Name.MiddleELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Name.PrefixELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Name.SuffixELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
ResumeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
SkillsELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Tel.AreaCodeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Tel.ExtensionELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Tel.IntlCodeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Tel.NumberELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
Tel.TypeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
TelephoneELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume
WebSiteELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume

XML schema: Person.AdditionalContactInfoSchemaCollection

XML schema name:Person.AdditionalContactInfoSchemaCollection
Description:Collection of XML schemas for the AdditionalContactInfo column in the Person.Contact table.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Components

Component nameTypeDerivationNamespace
dateATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactRecord
addressTypeCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
eMailTypeCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
phoneNumberTypeCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
specialInstructionsTypeCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
AdditionalContactInfoELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactInfo
CityELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
ContactRecordELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactRecord
CountryRegionELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
PostalCodeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
SpecialInstructionsELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
SpecialInstructionsELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
SpecialInstructionsELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
StateProvinceELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
StreetELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
eMailELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
eMailAddressELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
facsimileTelephoneNumberELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
homePostalAddressELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
internationaliSDNNumberELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
mobileELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
numberELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
pagerELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
physicalDeliveryOfficeNameELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
registeredAddressELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
telephoneNumberELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes
telexNumberELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ContactTypes

XML schema: Production.ManuInstructionsSchemaCollection

XML schema name:Production.ManuInstructionsSchemaCollection
Description:Collection of XML schemas for the Instructions column in the Production.ProductModel table.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Components

Component nameTypeDerivationNamespace
LaborHoursATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
LocationIDATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
LotSizeATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
MachineHoursATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
SetupHoursATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
StepTypeCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
LocationELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
blueprintELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
diagELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
materialELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
rootELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
specsELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
stepELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions
toolELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions

XML schema: Production.ProductDescriptionSchemaCollection

XML schema name:Production.ProductDescriptionSchemaCollection
Description:Collection of XML schemas for the CatalogDescription column in the Production.ProductModel table.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Components

Component nameTypeDerivationNamespace
ProductModelIDATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
ProductModelNameATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
CategoryCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
FeaturesCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
ManufacturerCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
PictureCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
ProductDescriptionCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
SpecificationsCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
SummaryCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
AngleELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
CategoryELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
CodeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
CopyrightELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
CopyrightURLELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
DescriptionELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
DescriptionELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain
DescriptionELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain
FeaturesELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
MaintenanceELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain
ManufacturerELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
NameELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
NameELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
NoOfYearsELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain
PictureELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
ProductDescriptionELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
ProductPhotoIDELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
ProductURLELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
SizeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
SpecificationsELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
SummaryELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
TaxonomyELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription
WarrantyELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain
WarrantyPeriodELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain

XML schema: Sales.IndividualSurveySchemaCollection

XML schema name:Sales.IndividualSurveySchemaCollection
Description:Collection of XML schemas for the Demographics column in the Sales.Individual table.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Components

Component nameTypeDerivationNamespace
BirthDateELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
CommentsELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
CommuteDistanceELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
DateFirstPurchaseELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
EducationELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
GenderELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
HobbyELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
HomeOwnerFlagELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
IndividualSurveyELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
MaritalStatusELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
NumberCarsOwnedELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
NumberChildrenAtHomeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
OccupationELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
TotalChildrenELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
TotalPurchaseYTDELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
YearlyIncomeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
MileRangeTypeSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey
SalaryTypeSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey

XML schema: Sales.StoreSurveySchemaCollection

XML schema name:Sales.StoreSurveySchemaCollection
Description:Collection of XML schemas for the Demographics column in the Sales.Store table.
Creation date:26 Apr 2006
Last altered date:26 Apr 2006

Components

Component nameTypeDerivationNamespace
AnnualRevenueELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
AnnualSalesELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
BankNameELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
BrandsELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
BusinessTypeELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
CommentsELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
ContactNameELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
InternetELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
JobTitleELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
NumberEmployeesELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
SpecialtyELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
SquareFeetELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
StoreSurveyELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
YearOpenedELEMENTNONEhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
BrandTypeSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
BusinessTypeSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
InternetTypeSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey
SpecialtyTypeSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey

XML schema: sys.sys

XML schema name:sys.sys
Description:
Creation date:14 Oct 2005
Last altered date:14 Oct 2005

Components

Component nameTypeDerivationNamespace
anySimpleTypeANY_SIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
anyTypeANY_TYPENONEhttp://www.w3.org/2001/XMLSchema
baseATTRIBUTENONEhttp://www.w3.org/XML/1998/namespace
clrTypeNameATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
langATTRIBUTENONEhttp://www.w3.org/XML/1998/namespace
localeIdATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
maxLengthATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
precisionATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
scaleATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
spaceATTRIBUTENONEhttp://www.w3.org/XML/1998/namespace
sqlCollationVersionATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
sqlCompareOptionsATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
sqlDbTypeATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
sqlSortIdATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
sqlTypeAliasATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
xmlSchemaCollectionATTRIBUTENONEhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
xmlCOMPLEX_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
ENTITIESLIST_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
IDREFSLIST_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
NMTOKENSLIST_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
sqlCompareOptionsListLIST_TYPENONEhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
NOTATIONPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
QNamePRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
anyURIPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
base64BinaryPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
booleanPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
datePRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
dateTimePRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
decimalPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
doublePRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
durationPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
floatPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
gDayPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
gMonthPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
gMonthDayPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
gYearPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
gYearMonthPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
hexBinaryPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
stringPRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
timePRIMITIVE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
ENTITYSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
IDSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
IDREFSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
NCNameSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
NMTOKENSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
NameSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
bigintSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
binarySIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
bitSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
byteSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
charSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
datetimeSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
dbobjectSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
decimalSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
floatSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
imageSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
intSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
intSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
integerSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
languageSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
longSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
moneySIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
ncharSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
negativeIntegerSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
nonNegativeIntegerSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
nonPositiveIntegerSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
normalizedStringSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
ntextSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
numericSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
nvarcharSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
positiveIntegerSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
realSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
shortSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
smalldatetimeSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
smallintSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
smallmoneySIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
sqlCompareOptionsEnumSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
sqlDbTypeEnumSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
textSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
timestampSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
timestampNumericSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
tinyintSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
tokenSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
uniqueidentifierSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
unsignedByteSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
unsignedIntSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
unsignedLongSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
unsignedShortSIMPLE_TYPERESTRICTIONhttp://www.w3.org/2001/XMLSchema
varbinarySIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
varcharSIMPLE_TYPERESTRICTIONhttp://schemas.microsoft.com/sqlserver/2004/sqltypes
xmlSpaceEnumSIMPLE_TYPERESTRICTIONhttp://www.w3.org/XML/1998/namespace

Users

User nameLogin nameCreation dateUser rolesUser description
dbosa08 Apr 2003db_owner
TestUserpanel03 Jun 2008db_ownerzxcv

Roles

Role nameIs appplication roleUsers in this roleRole description
db_accessadmin
db_backupoperator
db_datareader
db_datawriter
db_ddladmin
db_denydatareader
db_denydatawriter
db_ownerdbo, TestUser
db_securityadmin
public