WEB开发网
开发学院数据库MSSQL Server 如何在SQL Server中由原子建立分子查询 阅读

如何在SQL Server中由原子建立分子查询

 2007-05-15 09:29:05 来源:WEB开发网   
核心提示: 列表A列表A中包含建立这个新表格的新建(Create)语句,我用这个命令将它和值从原始表格中迅速移植出来:INSERT INTO [Northwind_New].[dbo].[OrderDetails_New]SELECT * FROM [Northwind_New].[dbo].[Ord

列表A

列表A中包含建立这个新表格的新建(Create)语句。我用这个命令将它和值从原始表格中迅速移植出来:INSERT INTO [Northwind_New].[dbo].[OrderDetails_New]
SELECT * FROM [Northwind_New].[dbo].[Order Details]

既然我有一个多行的表格,是时候开始实验了。(一旦新列ExtendedAmount被计算,其值会自动移植。)最初,我想用OrderID计算ExtendedAmount列的总数。我建立一个视图,如列表B所示。USE [Northwind_New]
GO
/****** Object:?View [dbo].
[OrderDetailsSumByOrderID_vue]Script Date: 08/23/2006 16:31:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[OrderDetailsSumByOrderID_vue]
AS
SELECT TOP 100 PERCENT OrderID,
SUM(ExtendedAmount) AS TotalAmount
FROM?dbo.OrderDetails_New
GROUP BY OrderID
ORDER BY OrderID

列表B

我每行得到一个OrderID,ExtendedAmount的列数得到总计。(称之为OrderAmount,将航运,税收等相加得到OrderTotal)。

我会在等式中引入一个表格UDF,如列表C所示。注意,我可以用两种方法调用函数:提交CustomerID将表格限定为那个顾客的订单,或提交一个NULL获得所有顾客订单列表。如果我提交CustomerID,那么订单列表就出现在OrderDate中;如果我提交NULL,列表就被分组并在CustomerID中由OrderDate排序。set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
-- =============================================
-- Author:    Arthur Fuller
-- Create date: 23 Aug 2006
-- Description:  Table UDF to return Order Totals by Customer
-- Example: SELECT * FROM dbo.CustomerOrderTotals_fnt('VINET')
-- Example: SELECT * FROM dbo.CustomerOrderTotals_fnt(NULL)
-- Notes:    This udf is designed to serve two
-- purposes. Pass a CustomerID to limit the rows to
-- that customer, or pass nothing to get all customers
-- =============================================
ALTERFUNCTION [dbo].[CustomerOrderTotals_fnt]
(  
   -- Add the parameters for the function here
   @CustomerID varchar(5)=NULL
)
RETURNS TABLE
AS
RETURN
  (
   -- Add the SELECT statement with parameter references here
  SELECTTOP 100 PERCENT
    dbo.Customers.CustomerID,
    dbo.Customers.CompanyName,
    dbo.Orders.OrderID,
    dbo.Orders.OrderDate,
    dbo.OrderDetailsSumByOrderID_vue.TotalAmount
  FROM 
    dbo.Customers
  INNERJOIN
    dbo.Orders ON dbo.Customers.CustomerID = dbo.Orders.CustomerID
  INNERJOIN
    dbo.OrderDetailsSumByOrderID_vue
    ON dbo.Orders.OrderID = dbo.OrderDetailsSumByOrderID_vue.OrderID
  WHERE 
    dbo.Customers.CustomerID = @CustomerID
    OR @CustomerID ISNULL
  ORDERBY dbo.Orders.OrderDate
  )
--try it with these:
--SELECT * FROM dbo.CustomerOrderTotals_fnt('VINET')
--SELECT * FROM dbo.CustomerOrderTotals_fnt(NULL)

Tags:如何 SQL Server

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接