我有一种情况,如果我使用一个函数,我可以在查询中保存大量重复的文本,但是在这个网站上我没有权利在服务器上创建一个函数。
有没有办法在查询正文中定义一个函数,然后从查询本身调用它?
希望我正确发布以下精简代码。真正的查询调用两个函数,按年计算,按年计算收入。
-- Function
alter function PetRockCountByYear
(@Company varchar(50), @DateFrom varchar(20), @DateTo varchar(20))
RETURNS varchar(50)
AS
begin
return (select isnull( SUM( transact.qty ), 0)
from TRANSACT
inner join CATALOG on transact.ITEM_NO = catalog.ITEM_NO
where transact.TRAN_DATE >= @DateFrom
and transact.TRAN_DATE <= @DateTo
and transact.ITEM_NO = 'PetRock'
and @Company = transact.company
and transact.ITEM_NO = catalog.ITEM_NO)
end
-- Simplified Query Below
select distinct
company.account, company.COMPANY,
company.STATUS, company.code,
-- Report counts from 1970 - 2015
(select dbo.PetRockCountByYear(company.COMPANY, '01/01/1970', '12/31/1970') ) as '#1970',
(select dbo.PetRockCountByYear( company.COMPANY , '01/01/1971', '12/31/1971') ) as '#1971'
from
TRANSACT
Inner join
invoices on transact.inv_no = invoices.inv_no
Inner join
COMPANY on invoices.COMPANY = company.company
where
ITEM_NO = 'PetRock'
order by
company.ACCOUNT
答案 0 :(得分:0)
SQL-Server T-SQL中没有临时函数,您需要拥有CREATE FUNCTION
数据库权限:https://msdn.microsoft.com/en-us/library/ms178569.aspx#Anchor_2和https://msdn.microsoft.com/en-us/library/ms191320.aspx#Anchor_0