Tải bản đầy đủ (.docx) (7 trang)

Code SQL Batch Function

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (44.31 KB, 7 trang )

use AdventureWorks2008R2
--1) Viết một batch khai báo biến @tongsoHD chứa tổng số hóa đơn của sản
phẩm có ProductID=’778’,
--nếu @tongsoHD>500 thì in ra chuỗi “San pham 778 có trên 500 đơn hàng”,
ngược lại tin ra chuỗi “San pham 778 co it don dat hang”
declare @tongsoHD int
select @tongsoHD=COUNT(SalesOrderID)
from Sales.SalesOrderDetail
where ProductID=778
if @tongsoHD>100 print N'Sản phẩm 778 có trên 500 đơn hàng'
else print N'Ko có sp nào hết'
go
--2) Viết một đoạn Batch với tham số @makh và @n chứa số hóa đơn của
khách hàng @makh, tham số @nam chứa năm lập hóa đơn (ví dụ @nam=2008),
--nếu @n>0 thì in ra chuỗi:”Khách hàng có @n hóa đơn trong năm 2008”
ngược lại nếu @n=0 thì in ra chuỗi “Khách hàng không có hóa đơn nào trong
năm 2008”
declare @makh int, @n int,@nam int
set @makh=75115
set @nam=2008
select @n=COUNT(SalesOrderID)
from Sales.SalesOrderHeader
where CustomerID=@makh and year(OrderDate)=@nam
if @n>0 print N'Khách hàng có ' +convert(char(5),@n)+N'trong năm 2008'
else print N'Ko có'
select *from Sales.SalesOrderHeader
--3) Viết một batch tính số tiền giảm cho những hóa đơn (SalesOrderID)
có tổng tiền>100000, thông tin gồm [SalesOrderID],
Subtotal=sum([LineTotal]),
--Discount (tiền giảm), với Discount được tính như sau:
--Những hóa đơn có Subtotal<100000 thì không giảm,


--Subtotal từ 100000 đến <120000 thì giảm 5% của Subtotal
--Subtotal từ 120000 đến <150000 thì giảm 10% của Subtotal
--Subtotal từ 150000 trở lên thì giảm 15% của Subtotal
select SalesOrderID,Subtotal=sum(LineTotal),
discount=case
when sum(LineTotal)<10000 then 0
when sum(LineTotal)<12000 then 0.05*sum(LineTotal)
when sum(LineTotal)<15000 then 0.1*sum(LineTotal)
else 0.15*sum(LineTotal)
end
from Sales.SalesOrderDetail
group by SalesOrderID
--4) Viết một Batch với 3 tham số: @mancc, @masp, @soluongcc, chứa giá
trị của các field [ProductID],[BusinessEntityID],[OnOrderQty],
--với giá trị truyền cho các biến @mancc, @masp (vd: @mancc=1650,
@masp)=4, thì chương trình sẽ gán giá trị tương ứng của field
[OnOrderQty]
--cho biến @soluongcc, nếu @soluongcc trả về giá trị là null thì in ra
chuỗi “Nha cung cap 1650 khong cung cap san pham 4”, ngược lại (vd:
@soluongcc=5)
--thì in chuỗi “Nha cung cap 1650 cung cap san pham 4 với số lượng là
5”(Gợi ý: Dữ liệu lấy từ [Purchasing].[ProductVendor])
declare @mancc int, @masp int, @soluongcc int


set @mancc=1580
set @masp=1
select @soluongcc=OnOrderQty
from Purchasing.ProductVendor
where ProductID=@masp and BusinessEntityID=@mancc

if @soluongcc is null print N'Nhà cung cấp '+convert(char(5),@mancc)
+N'ko cung cấp sản phẩm '+convert(char(5),@masp)
else print N'Nhà cung cấp '+convert(char(5),@mancc) +N'cung cấp sản phẩm
'+convert(char(5),@masp) +N' với số lượng là :
'+convert(char(5),@soluongcc)
select * from Purchasing.ProductVendor
--5)Viết một batch thực hiện tăng lương giờ (Rate) của nhân viên trong
[HumanResources].[EmployeePayHistory] theo điều kiện sau:
-- Khi tổng lương giờ của tất cả nhân viên Sum(Rate)<6000 thì cập nhật
tăng lương giờ lên 10%,
--nếu sau khi cập nhật mà lương giờ cao nhất của nhân viên >150 thì dừng.
while (select sum(Rate) from HumanResources.EmployeePayHistory)<6000
begin
update HumanResources.EmployeePayHistory
set Rate=Rate+Rate*0.1
if(select MAX(rate) from HumanResources.EmployeePayHistory)>150
break
else
continue
end
---Function
--1) Viết hàm tên countofEmplyees (dạng scalar function) với tham số
@mapb, giá trị truyền vào lấy từ field [DepartmentID], hàm trả về số nhân
viên trong
--phòng ban tương ứng. Áp dụng hàm đã viết vào câu truy vấn liệt kê danh
sách các phòng ban với số nhân viên của mỗi phòng ban,
--thông tin gồm: [DepartmentID], Name, countOfEmp với countOfEmp=
countofEmplyees([DepartmentID]).
--(Dữ liệu lấy từ bảng [HumanResources].[EmployeeDepartmentHistory] và
[HumanResources].[Department])

create function countofEmployees(@mapb int)
returns int
as
begin
return (select COUNT(*) from
HumanResources.EmployeeDepartmentHistory
where DepartmentID=@mapb)
end
declare @mapb int
set @mapb=12
select DepartmentID,Name,countofEmp=dbo.countofEmployees(@mapb)
from HumanResources.Department
where DepartmentID=@mapb
select * from HumanResources.EmployeeDepartmentHistory
--2) Viết hàm tên là InventoryProd (dạng scalar function) với tham số
vào là @ProductID và @locationID trả về số lượng tồn kho của sản phẩm
trong khu vực


-- tương ứng với giá trị của tham số (Dữ liệu lấy từ bảng[Production].
[ProductInventory])
create function InventoryProd(@ProductID int, @locationID int)
returns int
as
begin
return(select Quantity from Production.ProductInventory where
ProductID=@ProductID and LocationID=@locationID)
end
declare @productID int,@locationID int
set @productID=1

set @locationID=1
select ProductID,LocationID,QUantity=dbo.InventoryProd(@ProductID ,
@locationID )
from Production.ProductInventory where ProductID=@ProductID and
LocationID=@locationID
select * from Production.ProductInventory
--3) Viết hàm tên SubTotalOfEmp (dạng scalar function) trả về tổng doanh
thu của một nhân viên trong một tháng tùy ý trong một năm tùy ý,
--với tham số vào @EmplID, @MonthOrder, @YearOrder (Thông tin lấy từ bảng
[Sales].[SalesOrderHeader])
create function SubtotalOfEmp(@empID int,@month int, @year int)
returns int
as
begin
return(select SUM(SubTotal) from Sales.SalesOrderHeader where
SalesPersonID=@empID and (MONTH( OrderDate)=@month and
year( OrderDate)=@month ))
end
declare @empID int,@month int, @year int
set @empID=279
set @month=07
set @year=2005
select SalesPersonID,MONTH(OrderDate) as monthOD,year(OrderDate) as
yearOD ,sumSuubTotal=dbo.SubtotalOfEmp(@empID ,@month ,@year)
from Sales.SalesOrderHeader where SalesPersonID=@empID and
MONTH(OrderDate)=@month and year(OrderDate)=@year
select * from Sales.SalesOrderHeader
--table
--4) Viết hàm sumofOrder với hai tham số @thang và @nam trả về danh sách
các hóa đơn (SalesOrderID) lặp trong tháng và năm được truyền vào từ 2

tham số
--@thang và @nam, có tổng tiền >70000, thông tin gồm SalesOrderID,
Orderdate, SubTotal, trong đó SubTotal =sum(OrderQty*UnitPrice).
create function sumOfOD(@thang datetime,@nam datetime)
returns table
as
return(select
sod.SalesOrderID,OrderDate,SubTotal=SUM(OrderQty*UnitPrice)
from Sales.SalesOrderHeader soh join Sales.SalesOrderDetail sod
on soh.SalesOrderID=sod.SalesOrderID
where MONTH(OrderDate)=@thang and YEAR(OrderDate)=@nam


group by sod.SalesOrderID,OrderDate
having SUM(OrderQty*UnitPrice)>7000)
select * from Sales.SalesOrderHeader
select*from sumOfOD(07,2005)
--5) Viết hàm tên NewBonus tính lại tiền thưởng (Bonus) cho nhân viên
bán hàng (SalesPerson), dựa trên tổng doanh thu của mỗi nhân viên,
-- mức thưởng mới bằng mức thưởng hiện tại tăng thêm 1% tổng doanh thu,
thông tin bao gồm [SalesPersonID], NewBonus (thưởng mới), sumofSubTotal.
--Trong đó:
-SumofSubTotal =sum(SubTotal),
--NewBonus = Bonus+ sum(SubTotal)*0.01
create function NewBonus ()
returns table
as
return (select
SalesPersonID,SumofSub=sum(SubTotal),newbonus=Bonus+sum(SubTotal)*0.01
from Sales.SalesPerson sp join Sales.SalesOrderHeader soh on

sp.TerritoryID=soh.TerritoryID
group by SalesPersonID,Bonus)
select*from NewBonus()
--6) Viết hàm tên SumofProduct với tham số đầu vào là @MaNCC (VendorID),
hàm dùng để tính tổng số lượng (sumOfQty) và tổng trị giá (SumofSubtotal)
-- của các sản phẩm do nhà cung cấp @MaNCC cung cấp, thông tin gồm
ProductID, SumofProduct, SumofSubtotal
--(sử dụng các bảng [Purchasing].[Vendor] [Purchasing].
[PurchaseOrderHeader] và [Purchasing].[PurchaseOrderDetail])
create function SumofPro(@mancc int)
returns table
as
return(select BusinessEntityID,
pv.ProductID,sumofPro=sum(OrderQty),sumofSub=sum(OrderQty*UnitPrice)
from Purchasing.ProductVendor pv join
Purchasing.PurchaseOrderHeader poh on pv.BusinessEntityID=poh.VendorID
join Purchasing.PurchaseOrderDetail pod on
poh.PurchaseOrderID=pod.PurchaseOrderID
where VendorID=@mancc
group by BusinessEntityID, pv.ProductID)
select * from SumofPro(1580)
select*from Purchasing.ProductVendor
--7) Viết hàm tên Discount_func tính số tiền giảm trên các hóa đơn
(SalesOrderID), thông tin gồm SalesOrderID, [SubTotal], Discount, trong
đó, Discount
--được tính như sau:
--[SubTotal]<1000 thì Discount=0
--1000>=[SubTotal]<5000 thì Discount = 5%[SubTotal]
--5000>=[SubTotal]<10000 thì Discount = 10%[SubTotal]
--[SubTotal>=10000 thì Discount = 15%[SubTotal]

create function discount()
returns table
as
return (select SalesOrderID,SubTotal,discount=case


when
when
when
else

SubTotal<1000 then 0
SubTotal<5000 then 0.05*SubTotal
SubTotal<10000 then 0.1*SubTotal
0.15*SubTotal

end
from Sales.SalesOrderHeader)
select*from discount()
--8) Viết hàm TotalOfEmp với tham số @MonthOrder, @YearOrder để tính
tổng doanh thu của các nhân viên bán
-- hàng (SalePerson) trong tháng và năm được truyền và 2 tham số, thông
tin gồm [SalesPersonID], Total, với Total=Sum([SubTotal])
create function totalEmp (@monthOD datetime,@yearOD datetime)
returns table
as
return (select SalesPersonID,Total=sum(SubTotal) from
Sales.SalesOrderHeader
where MONTH(OrderDate)=@monthOD and YEAR(OrderDate)=@yearOD
group by SalesPersonID)

select * from totalEmp(7,2005)
--9/5)
Viết hàm tên NewBonus tính lại tiền thưởng (Bonus) cho nhân
viên bán hàng (SalesPerson), dựa trên tổng doanh thu của mỗi nhân viên,
-- mức thưởng mới bằng mức thưởng hiện tại tăng thêm 1% tổng doanh thu,
thông tin bao gồm [SalesPersonID], NewBonus (thưởng mới), sumofSubTotal.
--Trong đó:
-SumofSubTotal =sum(SubTotal),
--NewBonus = Bonus+ sum(SubTotal)*0.01
create function newbonus2(@manv int)
returns @newbonus2
table(manv int,newBonus money,sumofSub money)
as
begin
if @manv is not null
insert @newbonus2
select SalesPersonID,newBonus=Bonus
+sum(SubTotal)*0.1,sumofSub=Sum(SubTotal)
from Sales.SalesOrderHeader soh join Sales.SalesPerson sp
on soh.SalesPersonID=sp.BusinessEntityID
where SalesPersonID=@manv
group by SalesPersonID,Bonus
return
end
select * from newbonus2(282)
--6) Viết hàm tên SumofProduct với tham số đầu vào là @MaNCC (VendorID),
hàm dùng để tính tổng số lượng (sumOfQty) và tổng trị giá (SumofSubtotal)
-- của các sản phẩm do nhà cung cấp @MaNCC cung cấp, thông tin gồm
ProductID, SumofProduct, SumofSubtotal
--(sử dụng các bảng [Purchasing].[Vendor] [Purchasing].

[PurchaseOrderHeader] và [Purchasing].[PurchaseOrderDetail])
create function sumofPr2(@mancc int)
returns @sumofPr2
table(mancc int,tongsl int,tongtrigia money)
as
begin


if @mancc is not null
insert @sumofPr2
select VendorID,sumofQty=SUM(OrderQty),sunofSub=SUM(SubTotal)
from Purchasing.PurchaseOrderHeader poh join
Purchasing.ProductVendor pv
on poh.VendorID=pv.BusinessEntityID join
Purchasing.PurchaseOrderDetail pod
on poh.PurchaseOrderID=pod.PurchaseOrderID
where VendorID=@mancc
group by VendorID
return
end
--7) Viết hàm tên Discount_func tính số tiền giảm trên các hóa đơn
(SalesOrderID), thông tin gồm SalesOrderID, [SubTotal], Discount, trong
đó, Discount
--được tính như sau:
--[SubTotal]<1000 thì Discount=0
--1000>=[SubTotal]<5000 thì Discount = 5%[SubTotal]
--5000>=[SubTotal]<10000 thì Discount = 10%[SubTotal]
--[SubTotal>=10000 thì Discount = 15%[SubTotal]
create function discount_func2(@manv int)
returns @discount2

table(manv int,Subtotal money,discount money)
as
begin
if @manv is not null
insert @discount2
select SalesPersonID,Subtotal=sum(SubTotal),discount=case
when sum(SubTotal)<1000 then 0
when sum(SubTotal)<5000 then 0.05*sum(SubTotal)
when sum(SubTotal)<10000 then 0.1*sum(SubTotal)
else 0.15*sum(SubTotal)
end
from Sales.SalesOrderHeader
where SalesPersonID=@manv
group by SalesPersonID
return
end
select * from discount_func2(282)
--8) Viết hàm TotalOfEmp với tham số @MonthOrder, @YearOrder để tính
tổng doanh thu của các nhân viên bán
-- hàng (SalePerson) trong tháng và năm được truyền và 2 tham số, thông
tin gồm [SalesPersonID], Total, với Total=Sum([SubTotal])
create function TotalofEm (@monthOD datetime,@yearOD datetime)
returns @Total
table(manv int,thang int,nam int,tong money )
as
begin
if @monthOD is not null and @yearOD is not null
insert @Total
select SalesPersonID,MONTH(OrderDate) as monthOD,YEAR(OrderDate) as
yearOD,Total=SUM(SubTotal)

from Sales.SalesOrderHeader
where @monthOD= MONTH(OrderDate) and YEAR(OrderDate)=@yearOD


group by SalesPersonID,MONTH(OrderDate),YEAR(OrderDate)
return
end
select *from TotalofEm(7,2005)
--10) Viết hàm tên SalaryOfEmp trả về kết quả là bảng lương của nhân
viên, với tham số vào là @MaNV (giá trị của [BusinessEntityID]), thông
tin gồm
-- BusinessEntityID, Fname, Lname, Salary (giá trị của cột Rate).
--Nếu giá trị của tham số truyền vào là Mã nhân viên khác Null thì kết
quả là bảng lương của nhân viên đó.
--Ví dụ thực thi hàm: select*from SalaryOfEmp(288)
--
Nếu giá trị truyền vào là Null thì kết quả là bảng lương của tất cả
nhân viên
--Ví dụ: thực thi hàm select*from SalaryOfEmp(Null)
create function salaryofEm (@manv int)
returns @salary
table(manv int,fName nvarchar(50),lName nvarchar(50),salary money)
as
begin
if @manv is not null
begin
insert @salary
select eph.BusinessEntityID,FirstName,LastName,Rate
from HumanResources.EmployeePayHistory eph join
Person.Person p

on eph.BusinessEntityID=p.BusinessEntityID
where eph.BusinessEntityID=@manv
return
end
else
begin
insert @salary
select eph.BusinessEntityID,FirstName,LastName,Rate
from HumanResources.EmployeePayHistory eph join
Person.Person p
on eph.BusinessEntityID=p.BusinessEntityID
return
end
return
end
select *from salaryofEm(282)
select * from salaryofEm(null)



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×