我有一个存储过程,它给了我一个意外的令牌;当我尝试执行它时,当我接近结束语时,ORDER期待分号。
从#temp中选择年份,其中年份不为空ORDER BY年份DESC;
如果我删除 ORDER BY年DESC; ,此过程可以正常运行。
我已尽可能以降序对结果表进行排序。我对SQL很新,所以我确信它很简单。 TIA。
// ---------完整存储过程------ //
ALTER PROCEDURE GetYearForExhaustCatalog
(
CatCodeString Memo,
Year CHAR ( 4 ) OUTPUT
)
BEGIN
/*
EXECUTE PROCEDURE GetYearForExhaustCatalog('(e.catalogcode= ''2182'')');
EXECUTE PROCEDURE GetYearForExhaustCatalog('');
*/
DECLARE @CatCodeString string;
DECLARE @SQL string;
@CatCodeString = (SELECT CatCodeString FROM __input);
if @CatCodeString IS NULL or @CatCodeString = '' then
select e2.year,
(SELECT top 1 e2.year
FROM eenginecatalog e LEFT JOIN exhaustengine e2 ON e2.app_no=e.app_no)
as year
into #temp
from Exhaustengine e2;
select year from #temp where year is not null
GROUP BY year
ORDER BY year DESC;
else
@SQL =
'select e2.year, '+
'(SELECT top 1 e2.year '+
'FROM eenginecatalog e LEFT JOIN exhaustengine e2 ON e2.app_no=e.app_no and '+
@CatCodeString +' ) '+
'as year '+
'into #temp '+
'from Exhaustengine e2; '+
'select year from #temp where year is not null '+
'GROUP BY year '+
'ORDER BY year DESC ';
execute immediate @SQL;
end;
insert into __output
select year from #temp where year is not null ORDER BY year;
drop table #temp;
END;
答案 0 :(得分:1)
在插入特殊ORDER BY
表时,似乎ADS不喜欢__output
子句。
这不起作用:
CREATE PROCEDURE MyProcedure(Year INTEGER OUTPUT)
BEGIN
CREATE TABLE #tmp ("Year" INTEGER);
INSERT INTO #tmp ("Year") VALUES (2019);
INSERT INTO #tmp ("Year") VALUES (2017);
INSERT INTO #tmp ("Year") VALUES (2018);
INSERT INTO
__output
SELECT
"Year"
FROM #tmp
ORDER BY
"Year";
DROP TABLE #tmp;
END;
它失败并显示相同的错误消息:
poQuery: Error 7200: AQE Error: State = 42000; NativeError = 2117; [SAP][Advantage SQL Engine]Unexpected token: ORDER -- Expecting semicolon. -- Location of error in the SQL statement is: 269 (line: 15 column: 1)
作为一种解决方法,您可以创建另一个结果已排序的临时表:
CREATE PROCEDURE MyProcedure(Year INTEGER OUTPUT)
BEGIN
CREATE TABLE #tmp ("Year" INTEGER);
INSERT INTO #tmp ("Year") VALUES (2019);
INSERT INTO #tmp ("Year") VALUES (2017);
INSERT INTO #tmp ("Year") VALUES (2018);
SELECT
*
INTO #sorted
FROM #tmp
ORDER BY
"Year"
;
INSERT INTO
__output
SELECT
"Year"
FROM #sorted;
DROP TABLE #sorted;
DROP TABLE #tmp;
END;
这没有错误,数据已经过排序。
答案 1 :(得分:0)
__ output表不是罪魁祸首。在SQL标准中,通常不允许在子查询中使用ORDER BY。原因是在查询的内部解析期间排序一组行应该没有效果。它仅在最终结果中有用。在纯SQL意义上,保证结果排序的唯一操作是最终结果的ORDER BY。
如果您遵循此逻辑,可能的替代方法是不尝试按排序顺序将数据放入__output表,而是使用以下内容对最终输出进行排序:
SELECT * FROM (EXECUTE PROCEDURE MyProcedure(inParam)) t ORDER BY t.year