2017-05-09 71 views
0

我有这个简单的查询工作正常(我的实际查询比这要复杂得多,我刚刚创建的这个为例):查询工作正常作为独立,但在功能使用时给出了一个错误

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 
) 

当特林保存,它给了我这个错误:“消息1033,级别15,状态1,过程SampleF,第15行 ORDER BY子句在视图,内联函数,派生表,子查询和公共ta中无效ble表达式,除非TOP或FOR XML也被指定。“

任何想法?

+1

当你使用你的函数时,你应该真的使用'ORDER BY',而不是在里面:'SELECT * FROM [dbo]。[SampleF](1,2017)ORDER BY mc_referencia'或类似的东西 – Lamak

+0

下一个命令在你的功能中是没有意义的。这并不意味着任何使用这个查询的查询将按照该顺序返回。如果你想订购结果,它必须在最终查询中。这没有解决的办法。 –

+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

+1

在函数中添加'ORDER BY'有什么意义?用“TOP 100”黑客攻击没有任何意义。 –

相关问题