CREATE FUNCTION GetLastRate(
	@Duration int,
	@Currency1 varchar(30),
	@Currency2 varchar(30),
	@ExchangeId int) RETURNS @Result TABLE(RateDate datetime, Rate decimal(22, 8))
	 
AS
Begin
	INSERT INTO @Result(RateDate, Rate) 
	SELECT TOP 1 CRT.CRTD_CreationDate, CAST(CRT.CRTD_BidClosingValue AS decimal(22, 8))
		FROM [Knoks_Prices].[dbo].[CRT_Data_LiveChart] CRT 
		WHERE CRT.CRTD_PairSymbol = @Currency1 + @Currency2 AND CRT.ExchangeId = @ExchangeId
		AND CRT.CRTD_CreationDate <= GETUTCDATE() 
		ORDER BY CRT.CRTD_CreationDate DESC
	RETURN;
End
GO 