单词'DECLARE'附近的语法不正确

时间:2013-07-22 13:57:17

标签: sql sql-server-2008

出于某种原因,我不断收到错误'单词'DECLARE''附近的语法不正确。我应该在哪里声明我的变量,以便它不会抛出错误?我无法解决这个问题,因为我没有找到使用'WITH AS'语句并尝试声明变量的人。

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;

2 个答案:

答案 0 :(得分:4)

也许这样的东西就是你要找的东西?

CREATE PROCEDURE qryKeysValues(@KeyValue varchar(5))
AS
BEGIN

  DECLARE @SQL varchar(1500);

  SELECT * INTO #tbl1 FROM FN_qryMethods();

  SET @SQL = 'SELECT ' + @KeyValue+ ' AS fldCode
                 , tbl' +@KeyValue+ 'Key.fldID
                 , #tbl1.fldID
              FROM tbl' + @KeyValue + 'Key, #tbl1';

  EXEC(@SQL);
END;

答案 1 :(得分:3)

With语句采用结构:

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

你不能把Declare放在你放的地方。允许的值为SELECTINSERTUPDATEDELETEMERGE(contrib @alex k)。