我是否认为您无法创建局部变量?

时间:2017-11-01 09:06:54

标签: sql sql-server sql-server-2008 tsql

只是想知道我不断收到下面的错误,但脚本的其余部分正常工作。

CREATE VIEW View_I_Want AS 

DECLARE @MinDate AS DATE

SET @MinDate = 
    (SELECT MIN(Full_Date) AS First_Date
    FROM tbl.Calendar
    WHERE [Fin_Year] = 
        (SELECT [Fin_Year] - 1
        FROM tbl.Calendar
        WHERE Full_Date = CAST(GETDATE() AS DATE)))


SELECT DISTINCT MIN(CAST(Data_Table_Date_Column AS DATE)) AS Min_Date,
    MAX(CAST(Data_Table_Date_Column AS DATE)) AS Max_Date



FROM data_Table
WHERE CAST(Data_Table_Date_Column AS DATE) >= @MinDate
  

Msg 156,Level 15,State 1,Procedure how,Line 3语法不正确   在关键字'DECLARE'附近。

2 个答案:

答案 0 :(得分:1)

您无法在视图定义中声明variables。但另一种方式是:

CREATE VIEW View_I_Want
AS
     SELECT DISTINCT
            MIN(CAST(Data_Table_Date_Column AS DATE)) AS Min_Date,
            MAX(CAST(Data_Table_Date_Column AS DATE)) AS Max_Date
     FROM data_Table
     WHERE CAST(Data_Table_Date_Column AS DATE) >=
     (
         SELECT MIN(Full_Date) AS First_Date
         FROM tbl.Calendar
         WHERE [Fin_Year] =
         (
             SELECT [Fin_Year] - 1
             FROM tbl.Calendar
             WHERE Full_Date = CAST(GETDATE() AS DATE)
         )
     );

答案 1 :(得分:0)

您是否希望将变量作为存储过程的参数?在这种情况下,你不要使用'声明'但如果要将其作为过程中的变量,请指定数据类型使用Declare @variableName AS数据类型

CREATE PROCEDURE dbo.YourStoredProcedure (
@parameter INT )
AS
BEGIN
DECLARE @variable1 AS INT
DECLARE @variable2 AS INT

....

END