0

当我尝试运行以下查询时

DECLARE @QUERY1 VARCHAR(MAX)
SET @QUERY1=(SELECT [ResponsibleEngineerID],[ResponsibleEngineer],DocType
FROM tblResponsibleEngineer 
WHERE ResponsibleEngineer NOT IN ('(Select a Responsible Engineer...)')
ORDER BY [ResponsibleEngineer] ASC
)
EXEC(@QUERY1)

我得到了错误

ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效,除非还指定了 TOP 或 FOR XML。

为什么会出现这个错误?我需要完全按照上述格式编写sql查询。比如将查询分配给一个变量,然后执行

4

3 回答 3

0

尝试这个:

  DECLARE @QUERY1 VARCHAR(MAX)

    SET @QUERY1='SELECT [ResponsibleEngineerID],[ResponsibleEngineer],DocType
    FROM tblResponsibleEngineer 
    WHERE REPLACE(Responsible Engineer,'''','''''') NOT IN (Select a REPLACE(Responsible   Engineer,'''','''''')...)
    ORDER BY [ResponsibleEngineer] ASC'

    EXEC(@QUERY1)
于 2012-08-06T07:02:59.627 回答
0

您将查询结果分配给@QUERY1,而不是实际的查询文本。

据我了解,这就是您想要的;

DECLARE @QUERY1 VARCHAR(MAX)

SET @QUERY1='SELECT [ResponsibleEngineerID],[ResponsibleEngineer],DocType
FROM tblResponsibleEngineer 
WHERE ResponsibleEngineer NOT IN (Select a Responsible Engineer...)
ORDER BY [ResponsibleEngineer] ASC'

EXEC(@QUERY1)
于 2012-08-06T07:03:43.000 回答
0

您没有将查询分配给变量然后执行它 - 您正在执行查询并尝试将该查询的结果分配给变量。

如果您的查询不包含子查询的非法表达式,您将收到有关子查询返回多个列的错误。

声明变量:

DECLARE @QUERY1 VARCHAR(MAX)

将查询结果分配给变量:

SET @QUERY1=(SELECT [ResponsibleEngineerID],[ResponsibleEngineer],DocType
FROM tblResponsibleEngineer 
WHERE ResponsibleEngineer NOT IN ('(Select a Responsible Engineer...)')
ORDER BY [ResponsibleEngineer] ASC
)

您可能的意图是:

DECLARE @QUERY1 VARCHAR(MAX)

SET @QUERY1='SELECT [ResponsibleEngineerID],[ResponsibleEngineer],DocType
FROM tblResponsibleEngineer 
WHERE ResponsibleEngineer NOT IN (''(Select a Responsible Engineer...)'')
ORDER BY [ResponsibleEngineer] ASC'

EXEC(@QUERY1)

(请注意,我现在将字符串中的引号加倍了)

于 2012-08-06T07:04:46.160 回答