Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect syntax near word 'DECLARE'

For some reason I keep getting the error 'Incorrect syntax near word 'DECLARE''. Where should I declare my variable so that it doesn't throw an error? I haven't been able to figure this out as I haven't found someone using a 'WITH AS' statement and also trying to declare a variable.

CREATE PROCEDURE qryKeysValues(@KeyValue varchar(5))
    AS
    BEGIN
    WITH tbl1 AS    
        (SELECT * FROM FN_qryMethods())

    DECLARE @SQL varchar(1500)
    SET @SQL = 'SELECT ' + @KeyValue+ ' AS fldCode, tbl' +@KeyValue+ 'Key.fldID, tbl1.fldID
               FROM tbl' + @KeyValue + 'Key', tbl1
        EXEC(@SQL)
    END;
like image 570
codingManiac Avatar asked Sep 14 '26 20:09

codingManiac


1 Answers

The With statement takes the structure:

WITH CTE_Name
AS
(
    Select column from table
)
Select column from CTE_Name

You can't put Declare where you are putting it. Allowed values are SELECT, INSERT, UPDATE, DELETE and MERGE (contrib @alex k).

like image 154
gregpakes Avatar answered Sep 16 '26 21:09

gregpakes