Solution:NIIT/GNIIT Sonugiri0032@gmail.com

Saturday, January 02, 2016

SQL LAB at Home 7

SQL LAB at Home 7. 




01. Write a query to retrieve the details of the product locations where cost rate is greater than 12. In addition, the locations need to be grouped into three groups, and then ranked based on the cost rate in descending order.

select LocationID, name,CostRate,
Availability, ntile(3) over(order by CostRate desc)
as
Rank from Production.Location
Where CostRate>=12

02. Display SalesOrderID, OrderQty, and UnitPrice from the SalesOrderDetail table where a similar unit price needs to be marked with an identical value.

select salesOrderID,OrderQty,UnitPrice,Dense_Rank()
Over(Order by UnitPrice ASC)
as
Rank from sales.salesOrderDetail

03. Write a query to return the current year price and the previous year price of a product with the Product ID, 715, over subsequent years.

select ProductID, Year(StarDate)
as
salesYear, ListPrice as CurrentPrice, LAG(ListPrice,1,0)
Over(Order by year(startDate))
as PreviousPrice from Production.ProductListPriceHistory
where ProductID=715






Alter Table Country
Alter Column Country char(2)

05. Delete the Recipient table from the NarrowFabrics database.

drop table Employee

06. The following statement was used to remove the Category table: DELETE TABLE Category The preceding statement displays an error and aborts. Identify the error and rectify it.

Use NarrowFabrice
go
Drop table NewProduct
Drop table Category

07. Consider the following table structures.


  Refer the preceding table structures for the following requirements:
1. Create the Category table in the NarrowFabrics database. Enforce the following data integrity
rules while creating the table:
The CategoryId should be the primary key.
The Category attribute should be unique but not the primary key.
The Description attribute can allow storage of NULL values.
2. Create the ProductBrand table in the NarrowFabrics database. Enforce the following data
integrity rules while creating the table:
The BrandId should be the primary key.
The BrandName should be unique but not the primary key.
3. Create the NewProduct table with the following data integrity rules in the NarrowFabrics
database:
The ProductId should be the primary key.
The Qoh of the product should be between 0 and 200.
The Photo and ProductImgPath attributes can allow storage of NULL values.
The ProductName and ProductDescription attributes should not allow NULL values.
The values of the CategoryId attribute should be present in the Category table.
4. Modify the NewProduct table to enforce the following data integrity rule in the NarrowFabrics
database:
The values entered in the BrandId attribute should be present in the ProductBrand table.







 create table category
(
categoryID char(3) constraint pkategoryID primary key,
category char(20) constraint unqCategory unique,
Description varchar(100)Null
)






create table ProductBrand
(
BrandID char (3) constraint pkBrandID primary key,
BrandName char(20) constraint unqBrandName Unique,
)






create table New Product
(
ProductID char(6)Constraint pkProductID primary key,
ProductName varchar(20) not null,
ProductDescription varchar(200) not null,
categoryID char(3)constraint fkCategoryID
foreign key references Category(categoryID),
ProductRate money,
BrandID char(3),
photo image Null,
Qoh smallint constraint chkQoh check (Qoh Between 0 and 200),
productImgPath vatchar(40)Null
)








create table PictureDetail
(
EventPicID Uniqueidentifier Rowguidcol Not Null
Event Name varchar(30)not null,
Pic carbinary(Max) not null,
)

09. Create a table named LeaveDetail in the AdventureWorks database. The following table shows the structure of the LeaveDetail table.









create table LeaveDetail
(
Name varchar(50)not null,
Reason varchar(100)not null,
Number_of_days int constraint chknoday
check(Number_of_days <3)
)

10. Write a query to display the structure of the Department table.

sp_Help 'HumanResources.department'

Alter table LeaveDetail
Nocheck constraint chknoday

Insert into LeaveDetail valus('Tom','fever',4)

Alter table LeaveDetail
check constraint chknoday

12. Write a query to display the details of all the salespersons by using synonyms.

create Synonym spersonDetail

for Adventureworks.sales.salesperson




selrct * from spersonDetail

13. Write a query to create a rule on the GroupName column of the Department table to accept only three values: Research and Development, Sales and Marketing, and Manufacturing.

create Rule groupType
as
@gType in ('Research and Development',
'sales and Marketing',
'Manufacturing')
go
sp_bindrule 'groupType', 'HumanResorces.Department.
GroupName'

14. Write a statement to create a user-defined data type named quality. This data type should be varchar(100) and should not contain NULL values.

create type quality
from varchar(50) not null;

15. AdventureWorks, Inc. has set up a new store. Insert the data into the database as shown in the following table.






Insert into sales.Customervalus(7,'s',Default, Default)



Insert into sales.store valus(29484,'car store',285,
'<StoreSurvey XMLnas="htty://schemas.microsoft.com/sqlserver/2004/07/adventure-
works/StoreSurvey">'
<AnnualSales>350000</AnnualSales><AnnualRevenue>35000</AnnualRevenue>
<BankName>International Bank</BankName><BusinessType>BM</BusinessType>
<YearOpened>1980</YearOpened><Specialty>Road</Specialty>
<SquareFeet>7500</SquareFeet><Brands>AW</Brands><Internet>T1</Internet>
<NumberEmployees>7</NumberEmployees></storeSurvey>',Default,Default)

16. Insert the data shown in the following table into the ProductBrand table of the NarrowFabrics database.








Inser into ProductBrand valus('B01','Lee')
Inser into ProductBrand valus('B02','Wike')
Inser into ProductBrand valus('B03','Reebok')

17. The address of a vendor, Comfort Road Bicycles, has changed. You need to update the data, as shown in the following table, in the AdventureWorks database.






Update purchasing.VendorAddress
set AddressID=(select Address from Person,Address where AddressLinel='4151 Olivera'
and City='Atlanta')
from Purchasing.VendorAddress va,Purchasing.Vendor v
where va.VendorID=v.VendorID and
v.Name='Confort Road Bicycles'
Share:

SQL LAB at Home 8

 SQL LAB at Home 8


01. Delete all the records from the ProductBrand table in the NarrowFabrics database. Ensure that you do not delete the table.

Truncate table ProductBrand

02. Write an SQL statement to insert a record into the PictureDetails table, which is created in the PictureLibrary database. The following table shows the data to be inserted into the PictureDetails table.

03. Write an SQL statement to insert a record into the OfficeLocation table, which is created in the PictureLibrary database. The following table shows the data to be inserted into the OfficeLocation table.





Use PictureLibrary
go
Insert into OfficeLocation(Office_ID,
Office_Manager,Office_Location)
Values(1001,'Max',Geography: : Parse('Point(-83.0086 39.95954)'))

04. The production of a bicycle at AdventureWorks involves a number of phases. In each phase, the bicycle is moved to a different work center. The details of all the work centers are stored in the Production.ProductModel table. Bicycles of different types pass through different work centers, depending on the components that need to be fitted. The management wants a list of all the types of bicycles that go through work center 10. How will you generate this list?

With
XMLNamespaces('http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/
ProductModelManulnstructions'as pd)
select ProductModelID from Production.ProductModel
Where Instructions.exist('pd:root/pd:Location[@LocationID=10]')=1

05. The EmployeeDetails table contains the records of the employees. Write a query to delete the records of those employees who are designated as clerk. In addition, ensure that all the deleted rows are displayed after the execution of the query.

Delete EmployeeDetails output
deleted.*Where Designation='Clerk'

06. The users of AdventureWorks need to publish the details of all the customers and their address on the organization's website. To perform this task, you need to retrieve the data in the XML format.

select c.CustomerID,TerritoryID,AccountNumber,CustomerType,
 City, StateprovinceID,PostalCode from Sales.Customer c
Join Sales.CustomerAddress ca on c.CustomerID=ca.CustomerID
join Person.Address a on ca.AddressID=a.AddressID for XML Path('Customer')

07.Delete all the records from the Employee table in the AdventureWorks database where the department ID is 5.

select * from HumanResources.EmployeeDepartmentHistory
delete from HumanResources.EmployeeDepartmentHistory
where DepartmentID=3

08. The management of AdventureWorks requires a list containing the skills of all the candidates who have applied for a vacancy. The details of all the candidates are stored in the XML format in the HumanResources.JobCandidate table. How will you display the list?

select jobCandidateID,Resume.value('declare namesPace
ns="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume";
(/ns:Resume/ns:name/ns:name.First)[1]','nverchar(20)')
as [first name], Resume.value('declare namespace
ns="http://schemas.microsoft.com/sqlserver/2004/07/adventure-work/Resume";
(/ns:Resume/ns:name/ns:name.Last)[1]','nvarchar(20)')
as [Last name],Resume.value('declare namespace
ns="http://schemas.microsoft.com/sqlserver/2004/07/adventure-work/Resume";
(/ns:Resume/ns:Skills[1]','nvarchar(max)')
as [Skills]from HumanResources.JobCandidate

09. The details of the two employees designated as clerk have been removed from the EmployeeDetails table. Write the SQL statement to reflect these changes made in the EmployeeDetails_Backup table.

Merge EmployeeDetail_Backup
as Target using EmployeeDetail
as Source on (Target.EmployeeID= Source.EmployeeID)
When Matched and
Target.Designation <> Source.Designation
Then Update set Target.Designation= source.Designation
when Not Matched then
Insert Values(Source.EmployeeID,
Source.EmpName,source.designation,
Source.salary,Source.DeptNo)
When Not Matched by Source Then Delete;

10. There is a change in the production process of the bicycle with the product model ID 7. Due to this change, the bicycle will not be going to work center 10. You need to update this change in the database. How will you perform this task?

With
XMLNamespaces('http://schemas.microsoft.com/sqlserver/2004/07/adventure-work/productModelManulnstructions'
as pd)
Update Production.ProductModel SET
Instructions.modify('delete (/pd:root/pd:Location)[1]')
where ProductModelID = 7

11. Write a query to copy the records of sales with unit price greater than $ 2024.994 in a new table named Sales_od.

select * from Sales.SalesOrderDetail
select * into sales_od from Sales.SalesOrderDetail
Where UnitPrice> 2024.994

12. Insert a record with the following address in the Address table of the AdventureWorks database: 2125 Yan Street, Bothell-79, Postal Code-98011

Insert Person.Address (AddressLine1,City,StateProvinceID,
PostalCode) Values('2135 yan street',79,'98011')

13.You need to create a table named Student_Details to store the details of students in the database. The structure is shown in the following table.






create XML Schema Collection StudentInfo as
'<schema xmlns="http://www.w3.org/201/xmlschema">
<Element name ="StudentName"Type="string"/>
<Element name ="Address" type="string"/>
<Element name ="ContactNumber"type="int"/>
</schema>'
Share:

SQL LAB at Home 9

SQL LAB at Home 9

01. The SalesOrderDetail and SalesOrderHeader tables store the details of the sales orders. You have created a backup of the SalesOrderDetail and SalesOrderHeader tables in the SalesOrderDetail_Backup and SalesOrderHeader_Backup tables. To generate a report displaying the sales order ID and the total amount of all the products purchased against an order, you are using the following query: SELECT sd.SalesOrderID, SUM(LineTotal) AS [Total Amount] FROM Sales.SalesOrderDetail_Backup sd JOIN Sales.SalesOrderHeader_Backup sh ON sd.SalesOrderID = sh.SalesOrderID GROUP BY sd.SalesOrderID The table contains a large amount of data. Suggest a solution to optimize the execution of this query.


++++=======================++++

++++=======================++++

02. The Store table is often queried. The queries are based on the CustomerID attribute and take a long time to execute. Optimize the execution of the queries. In addition, ensure that the CustomerID attribute does not contain duplicate values.

select * from Sales.Store
create Unique nonclustered index
IDx_CustomerID on sales.Stare(CustomerID)
========================================
========================================

03. A view has been defined as shown in the following statement: CREATE VIEW vwSalesOrderDetail AS SELECT oh.SalesOrderID, TerritoryID, TotalDue, OrderQty, ProductID FROM Sales.SalesOrderHeader oh JOIN Sales.SalesOrderDetail od ON oh.SalesOrderID = od.SalesOrderID The following UPDATE statement gives an error when you update the OrderQty and TerritoryID attributes: UPDATE vwSalesOrderDetail SET OrderQty = 2, TerritoryID = 4 FROM vwSalesOrderDetail WHERE SalesOrderID = 43659 Identify the problem and provide the solution.

update vwSalesOrderDetail
set OrderQty = 2
from vwSalesOrderDetail
Where SalesOrderID=43659

Update vwSalesOrderDetail
SET TerritoryID=4
from vwSalesOrderDetail
Where SalesOrderID=43659
==========================================
==========================================

04. The SalesOrderDetail table is often queried. The queries are based on the SalesOrderDetailID and SalesOrderID attributes. The execution of the queries takes a long time. Optimize the execution of the queries. In addition, check the performance of the query before and after optimizing the execution of the queries.

create nonclustered Index
 Idx_salesOrderID_salesOrderDetailID
 on sales.salesorderdetail(salesorderid,salesorderdetailid)

============================================
============================================

05. The Store table contains the details of all the stores. The HR Manager of AdventureWorks, Inc. frequently queries the Store table based on the names of the stores. He wants to create the following reports: A report containing the details of all the stores that contain the word 'bike' in their names. A report displaying the names of all the stores containing the phrase 'Bike Store'. Write the query so that the result set is retrieved quickly.

select * from Sales.Store
where contains (Name,'"Bike store"')

===========================================
===========================================

06. Display the details of all the credit cards that are of type SuperiorCard. The CreditCard table contains a large amount of data. Therefore, the query takes a long time to retrieve the details of the credit card. You need to optimize the execution of the query so that the result set does not take too much time to be retrieved.

select * from sales.CreditCard
Where Contains(CardType,'SuperiorCard')

===========================================
===========================================

07. Display the details of all the currencies that contain the words New and Dollar in their names. These words can be included in any order. In addition, you need to make sure that the query does not take too much time to execute.

select * from Sales.Currency
Where FreeText (Name,'"New" and "Dollar"')
===============================================
===============================================

08. The manager of the production department wants to analyze the products that contain the exact word 'road' in their description. Write a query so that the result set does not take a long time to execute.

select * from Production.ProductDescription
Where Contains(Description,'Road')
==============================================
==============================================

09. You need to create a report displaying the details of all the products that contain the word 'top' near the word 'line' in their description. Write a query to retrieve the desired output. Write the query such that it does not take a long time to execute.

select Description, ProductDescriptionID
from Production.ProductDescription
Where Contains (Description,'"Top" near "Line"')
==============================================
==============================================

10. The Store table is often queried. The queries are based on the Demographics attribute and take a long time to execute. Optimize the execution of these queries.

create XML Index Sdx_Sales_Demographics_path
on Sales.Store(Demographics)
Using XML Index PXML_Store_Demographics
for path
===============================================
===============================================

11. The DepartmentHistory table of employees is often queried. The queries are based on the EmployeeID attribute and take a long time to execute. Optimize the execution of these queries.

create Nonclustered index Idx_EmployeeID
on HumanResources.EmployeeDepartmentHistory(EmployeeID)
================================================
================================================

12. Display the details of all the stores having the word 'bike' in their name. In addition, ensure that the report contains the details of those stores that have the sales person ID as 277. You need to write a query so that the result set does not take a long time to be retrieved.

select * from Sales.Store
Where SalesPersonID=277
and Contains(Name,'Bike')
==============================================
==============================================

13. Create a view to retrieve SalesOrderId and Price of the Product along with the corresponding Product Name.

create View vwsales
as
select P.Name, S.SalesOrderID,S.UnitPrice
from Production.Product P inner join
Sales.SalesOrderDetail S
on P.ProductID = ProductID
go
================================================
================================================

14. Create a view to retrieve the employee IDs along with the corresponding Group Name.

create View Disp_Detail
as
select E.EmployeeID,D.GroupName
from HumanResources.Department d
Inner join
HumanResources.EmployeePayHistory E
on D.DepartmentID=E.EmployeeID
==================================================
==================================================

15. Create a view to display SalesOrderId, CustomerId, OrderQty, UnitPrice, SubTotal, and TotalDue of the orders placed.

create view vwsale as
select H.CustomerID, H.SubTotal, H.TotalDue,
D.SalesOrderID,D.OrderQty,D.UnitPrice
from Sales.SalesOrderHeader as H
join sales.salesOrderDetail as D on
H.salesOrderID=d.salesOrderID
select * from Sales.SalesOrderDetail

Share:

Friday, January 01, 2016

GNIITSOLUTION GNIIT SOLUTION. Powered by Blogger.

Translate

Blog Archive

Unordered List