我将这段代码拼凑在一起,以根据每个经销商的发票小计总和创建一个支点。它有效,并产生正确的结果。但是,当我尝试将其转换为存储过程时,臭名昭著的波浪形红线出现在 SQL Server 管理工作室的“CREATE VIEW Revenues”下,并且错误显示:
'CREATE VIEW 必须是批处理中的唯一语句',我不知道足够的 T-SQL 来继续,因为我需要能够从 ASP.NET/C# Web 应用程序执行它。
我正在尝试通过放置来创建一个 SP:
1)
USE [Sherwood]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[usp_GetRevenues]
@StartDate AS DateTime = '20120301',
@EndDate AS DateTime = '20120401'
AS
SET NOCOUNT ON;
BEGIN
在前面,最后有一个 END 语句。
2)参数是能够过滤数据几个月的必要条件,但我似乎无法通过代码传递参数或使用变量。
提前致谢。
代码如下 - 显示我需要在哪里过滤变量。该代码仅适用于 where 子句中格式为“1/1/2012”的日期,但需要能够传递变量,如图所示。
--=================================
CREATE VIEW Revenues
AS
SELECT
i.DateOrdered
,LTRIM(STR(DATEPART(MONTH,i.DateOrdered))) AS [Month]
,LTRIM(STR(YEAR(i.Dateordered))) AS [Year]
,c.CustomerCode
,SUM(i.Jobprice) AS Subtotal
FROM Invoices i
JOIN
Customers c
ON i.CustomerID = c.ID
WHERE i.DateOrdered >= @StartDate
AND i.DateOrdered <= @EndDate **<-- and here.**
GROUP BY ROLLUP (YEAR(i.DateOrdered),
MONTH(i.DateOrdered), i.DateOrdered, c.CustomerCode);
GO
IF OBJECT_ID('Revenues2') IS NOT NULL
DROP VIEW Revenues2
GO
CREATE VIEW Revenues2
AS
SELECT
LTRIM(STR([YEAR])) + '-' + STUFF([Month],1,0, REPLICATE('0', 2 - LEN([Month])))
AS [Date]
,Subtotal
,CustomerCode
FROM Revenues
WHERE CustomerCode IS NOT NULL
GO
DECLARE @query VARCHAR(4000)
DECLARE @years VARCHAR(2000)
SELECT @years = STUFF(( SELECT DISTINCT
'],[' + [Date]
FROM Revenues2
ORDER BY '],[' + [Date]
FOR XML PATH('')
), 1, 2, '') + ']'
SET @query =
'SELECT * FROM
(
SELECT Subtotal,[Date],CustomerCode
FROM Revenues2
)t
PIVOT (SUM(Subtotal) FOR [Date]
IN ('+ @years +')) AS pvt'
EXECUTE (@query)
--===========================================
问候
悬崖