Getting error Incorrect syntax near the keyword 'DECLARE'.

  • CREATE VIEW [dbo].[vwstudent]

    AS

    DECLARE @Date datetime2

    SELECT @Date = value

    FROM dbo.configuraiton

    WHERE text = 'PivotValue'

    SELECT ID

    , StudentId

    , CASE WHEN STD.EfDate <= @Date THEN DATEADD(MONTH,-2,STD.EfDate)

    ELSE STD.EfDate

    END

    , CreatedDate

    FROM dbo.Student STD

    GO

  • You cannot use variables in a view.

     

    Either re-wrtie it as a single statement, or create a stored procedure.

  • How to rewrite as single statement with out variable?

     

     

  • mcfarlandparkway wrote:

    How to rewrite as single statement with out variable?

    I don't know your table structures or data types.  I also do not have any sample data to work with.

    So the following 2 options are merely untested guesses

    WITH cteDate AS (
    SELECT TheDate = cast(value as datetime2)
    FROM dbo.configuraiton
    WHERE text = 'PivotValue'
    )
    SELECT ID
    , StudentId
    , CASE
    WHEN STD.EfDate <= cte.TheDate THEN DATEADD(MONTH, -2, STD.EfDate)
    ELSE STD.EfDate
    END
    , CreatedDate
    FROM dbo.Student STD
    CROSS JOIN cteDate AS cte;

     

    SELECT ID
    , StudentId
    , CASE
    WHEN STD.EfDate <= D.TheDate THEN DATEADD(MONTH, -2, STD.EfDate)
    ELSE STD.EfDate
    END
    , CreatedDate
    FROM dbo.Student STD
    CROSS APPLY ( SELECT TheDate = cast(value as datetime2)
    FROM dbo.configuraiton
    WHERE text = 'PivotValue'
    ) AS D;

     

  • thank you, it worked

  • CREATE VIEW [dbo].[vwstudent]
    AS
    SELECT STD.ID,
    STD.StudentId,
    CASE WHEN STD.EfDate <= c.value THEN DATEADD(MONTH, -2, STD.EfDate)
    ELSE STD.EfDate
    END,
    STD.CreatedDate
    FROM dbo.Student STD
    INNER JOIN dbo.configuraiton c
    ON c.text = 'PivotValue'
    GO

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply