查询可以单独使用,但在函数中使用时会出错

时间:2017-05-09 15:13:34

标签: sql-server sql-order-by union

我有这个简单的查询工作正常(我的实际查询比这复杂得多,我只是创建了这个作为一个例子):

select mc_id, mc_referencia
from movcuentas1
where tm_id = 1 and mc_concepto = 'Amort Int'
UNION 
select mc_id, mc_referencia
from movcuentas2
where tm_id = 2 and mc_concepto = 'Amort Capital'
order by mc_referencia

但是当我尝试在诸如此类的函数中使用它时:

USE [dozfin]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION [dbo].[SampleF] (@mes as integer, @anio as integer)
RETURNS TABLE 
AS
RETURN 
(
select mc_id, mc_referencia
from movcuentas
where tm_id = 1 and mc_concepto = 'Amort Int'
UNION 
select mc_id, mc_referencia
from movcuentas
where tm_id = 2 and mc_concepto = 'Amort Capital'
order by mc_referencia
)

当保存时,它会给我这个错误:" Msg 1033,Level 15,State 1,Procedure SampleF,Line 15 除非还指定了TOP或FOR XML,否则ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效。"

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

消息错误很明显,使用ORDER BY为句子添加TOP子句。

ALTER FUNCTION [dbo].[SampleF] (@mes as integer, @anio as integer)
RETURNS TABLE 
AS
RETURN 
(
    select mc_id, mc_referencia
    from movcuentas
    where tm_id = 1 and mc_concepto = 'Amort Int'
    UNION 
    select top 100 percent mc_id, mc_referencia
    from movcuentas
    where tm_id = 2 and mc_concepto = 'Amort Capital'
    order by mc_referencia
)

只是一个示例

create table foo (id int identity, val int);
insert into foo values (1),(2),(3),(4);
create function dbo.test(@id int)
returns table
as
return
    select id, val from foo where id = @id
    union
    select top 100 percent id, val from foo where id > 3 order by val desc;

GO
select * from dbo.test(2);
GO
id | val
-: | --:
 2 |   2
 4 |   4

dbfiddle here