如何在SQL Server中由原子建立分子查询
2007-05-15 09:29:05 来源:WEB开发网核心提示: 列表C-- -- Template generated from Template Explorer using:-- Create Inline Function (New Menu).SQL Use the Specify Values for Template Parameters-
列表C
-- ================================================
-- Template generated from Template Explorer using:
-- Create Inline Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Arthur Fuller
-- Create date: 23 Aug 2006
-- Description: Return total sales by Customer
-- Example:
-- SELECT CustomerID, CustomerTotal
-- FROM DBO.CustomerGrandTotal_fnt(null)
-- SELECT CustomerID, CustomerTotal
-- FROM DBO.CustomerGrandTotal_fnt('VINET')
-- SELECT CustomerID, CustomerTotal
-- FROM DBO.CustomerGrandTotal_fnt('VINET')
-- =============================================
CREATEFUNCTION CustomerGrandTotal_fnt
(
@CustomerID varchar(5)
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
SELECTTOP 100 PERCENT
CustomerID,
SUM(TotalAmount)AS CustomerTotal
FROM dbo.CustomerOrderTotals_fnt(@CustomerID)
WHERE dbo.CustomerOrderTotals_fnt.CustomerID = @CustomerID
OR @CustomerID ISNULL
GROUPBY CustomerID
ORDERBY CustomerID
)
GO
列表D
更深入一步,我每个顾客打印一行,用一列显示每名顾客的总销售额。查看列表D。并不是所有项目都得到组合。在最外层,我能够以两种方式调用这个函数:提交合法CustomerID或UNLL。以下是它们各自的实例:SELECT CustomerID, CustomerTotal
FROM DBO.CustomerGrandTotal_fnt(null)
SELECT CustomerID, CustomerTotal
FROM DBO.CustomerGrandTotal_fnt('VINET')
现在你有了一组精确的工具来帮助你挖掘适当层次的细节。计算列OrderDetails.ExtendedAmount隐藏了一个复杂层次,从那我又深入到我希望隐藏的细节。这就是我把这些对象叫做原子和分子查询的原因。我使用“查询”一词来概括这样一个事实,即讨论的对象是视图还是表格UDF并不重要。(虽然由于命名规则,suffix _fnt表示一个表格UDF,而suffix _vue表示一个视图。)
必须承认,Northwind数据库中没有大量的行,但我认为这种技巧可以得到很好地扩充。更为重要的是,我喜欢它提供的粒度。我能够做我想做的,并按要求重新使用或重新组合原子。
赞助商链接