2

出于某种原因,我不断收到错误“单词'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;
4

2 回答 2

4

With语句采用以下结构:

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

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

于 2013-07-22T14:00:34.227 回答
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;
于 2013-07-22T14:40:11.073 回答