views:

32

answers:

2

I´m trying to create a VIEW in SQL Server 2005.

The SQL code is working as such (I´m using it in VS2008), but in SQL Server I´m unable to save it, as error message "Declare the scalar variable @StartDate" and "Declare the scalar variable @EndDate" pops up.

Here is the code:

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

And my question is of course - exactly how should I declare them?

I tried to put the following first in the code:

DECLARE @StartDate smalldatetime
DECLARE @EndDate smalldatetime

But that didn´t do the trick, just as I expected - it only gave me another pop-up message:

"The Declare cursor SQL construct or statement is not supported."

A: 

If by VIEW you mean an SQL Server native view (CREATE VIEW ...) then you cannot use local variables at all (you would use a table-valued udf instead).

If you mean something else, then adding DECLARE @StartDate DATETIME, @EndDate DATETIME makes that statement parse fine, is it the entirety of the SQL?

Alex K.
I mean that I in the SQL Server Management Studio right clicks on the "Views" folder and selects "New View..." - I´ve created other views this way, and then I use them in Visual Studio 2008 (C#) to use them when creating "TableAdapters", for example. Well, what is a table-valued udf? Where and how do I create it, do you know?
Jack Johnstone
A: 

As Alex K has mentioned, you should write it as a inline table valued function. Here is the article that describes about it.

In short, syntax would be something like

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

You can have one select query (however complex, can use CTE). And then you will use it as

SELECT * FROM dbo.GetForPeriod('1-Jan-2010', '31-Jan-2010')
VinayC
Nice, gonna test that out - I see it as an acceptable answer :-)
Jack Johnstone