2017-05-09 17 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」黑客攻擊沒有任何意義。 –

相關問題