小编典典

如何在Sql Server(2005)的VIEW中“声明标量变量”

sql

我试图在 SQL Server* 2005中创建一个 VIEW*

SQL代码按这种方式工作(在VS2008中使用I麓m),但是在SQL
Server中无法保存它,因为弹出错误消息“声明标量变量@StartDate”和“声明标量变量@EndDate”向上。

这是代码:

WITH Calendar AS (SELECT     CAST(@StartDate AS datetime) AS Date
     UNION ALL
     SELECT     DATEADD(d, 1, Date) AS Expr1
     FROM         Calendar AS Calendar_1
     WHERE     (DATEADD(d, 1, Date) < @EndDate))
    SELECT     C.Date, C2.Country, COALESCE (SUM(R.[Amount of people per day needed]), 0) AS [Allocated testers]
     FROM         Calendar AS C CROSS JOIN
                            dbo.Country AS C2 LEFT OUTER JOIN
                            dbo.Requests AS R ON C.Date BETWEEN R.[Start date] AND R.[End date] AND R.CountryID = C2.CountryID
     GROUP BY C.Date, C2.Country

我的问题当然是-我应该究竟如何申报呢?

我尝试将以下代码放在第一位:

DECLARE @StartDate smalldatetime
DECLARE @EndDate smalldatetime

但是,这并没有达到预期的效果,正如我所期望的那样-它只给了我另一个弹出消息:

“不支持声明游标SQL构造或语句。”


阅读 226

收藏
2021-04-07

共1个答案

小编典典

如Alex K所述,您应该将其编写为内联表值函数。这是描述它的文章

简而言之,语法将类似于

CREATE FUNCTION dbo.GetForPeriod
    ( @StartDate datetime, @EndDate datetime) 
RETURNS TABLE 
RETURN 
   SELECT  [[ your column list ]]
   FROM    [[ table list]
   WHERE   [[some column] BETWEEN @StartDate AND @EndDate

您可以有一个选择查询(但是很复杂,可以使用CTE)。然后您将其用作

SELECT * FROM dbo.GetForPeriod('1-Jan-2010', '31-Jan-2010')
2021-04-07