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;
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With