在SQL函数中添加两个查询

时间:2016-04-12 09:58:25

标签: sql-server

我试图创建一个类似下面的函数,基本上我需要查询两个货币值然后将它们加在一起并返回结果。这可能吗?

由于

CREATE function [dbo].[fn_manualpricing2-NEW](@type varchar(50),@capid int,@milespa int, @maintained bit, @term int, @product varchar(50), @funder varchar(50))
returns money
as
BEGIN

RETURN (
SELECT TOP 1 price FROM tblPricing WHERE [type]=@type AND term=@term AND milespa=@milespa AND capid=@capid AND maintained=@maintained AND source=@funder and product=@product ORDER BY price
+
SELECT TOP 1 addonpricevalue FROM [dbWebsiteLO3-PRICING].[dbo].[AddonPrices] WHERE VehicleType=1 AND term=@term AND miles=@milespa AND source=@funder
)
END

GO

2 个答案:

答案 0 :(得分:0)

试试这样..

CREATE function [dbo].[fn_manualpricing2-NEW](@type varchar(50),@capid int,@milespa int, @maintained bit, @term int, @product varchar(50), @funder varchar(50))
returns money
as
BEGIN

DECLARE @variable money
SET @variable = (SELECT TOP 1 price FROM tblPricing WHERE [type]=@type AND term=@term AND milespa=@milespa AND capid=@capid AND maintained=@maintained AND source=@funder and product=@product ORDER BY price)
+
(SELECT TOP 1 addonpricevalue FROM [dbWebsiteLO3-PRICING].[dbo].[AddonPrices] WHERE VehicleType=1 AND term=@term AND miles=@milespa AND source=@funder)

return @variable 

END

GO

答案 1 :(得分:0)

这可以用更少的代码来完成,但是这给了你一般的想法:

CREATE FUNCTION dbo.ufn_AddTwoValues()
RETURNS Money
WITH EXECUTE AS CALLER
AS
-- place the body of the function here
BEGIN
    DECLARE @ValOne money;
    DECLARE @ValTwo money;
    DECLARE @Result money;

    SET @ValOne = (SELECT 1);
    SET @ValTwo = (SELECT 2);

    SET @Result = @ValOne + @ValTwo;

    RETURN @Result;
END
GO

select dbo.ufn_AddTwoValues()