You're on the right track, but I think this is an easier way to do it.
PB SCRIPT:
long rate_rank2 string sp_id double a_identity double b_identity long vehicle_type sp_id = 'F10600' a_identity = 23864 b_identity = 4018 vehicle_type = 1 select dbo.ft_fn_RankAffiliateRate2(:sp_id, :a_identity, :b_identity, :vehicle_type) into :rate_rank2 using sqlca; IF SQLCA.SQLCode <> 0 THEN MessageBox ( "Error", "Select failed" ) RETURN -1 END IF commit using sqlca; messagebox("Rate Rank","Rate Rank for " + sp_id + " is: " + string(rate_rank2))
MSSQL:
CREATE FUNCTION dbo.ft_fn_RankAffiliateRate2(@sp_id char(10), @a_identity numeric, @b_identity numeric, @vehicle_type int)
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
-- create the table variable
declare @raterank table (sp_id char(10) not null,
a_identity numeric not null,
b_identity numeric not null,
ar_vehicle_type int not null,
ar_total_from_airport money not null,
rate_rank int not null);
-- create a variable to hold the rank to be returned declare
@rtn int;
insert into @raterank (sp_id,
a_identity,
b_identity,
ar_vehicle_type,
ar_total_from_airport,
rate_rank)
select sp_id,
a_identity,
b_identity,
ar_vehicle_type,
ar_total_from_airport,
DENSE_RANK() OVER(ORDER BY ar_total_from_airport) rate_rank
from ft_affiliate_rate_staged WITH (NOLOCK)
where ft_affiliate_rate_staged.a_identity = @a_identity and
ft_affiliate_rate_staged.b_identity = @b_identity and
ft_affiliate_rate_staged.ar_vehicle_type = @vehicle_type;
-- guarantee a single result row (although there should only be one)
select top 1 @rtn = rate_rank from @raterank where sp_id = @sp_id order by rate_rank;
return (@rtn);
END;
To test it, go to PB DB Painter, and use this:
select dbo.ft_fn_RankAffiliatRate2('F10600', 23864, 4018, 1) as rate_rank;
It should return a single column called "rate_rank" with the appropriate value;
You can now also call this function directly from PB code (select dbo.ft_fn_....(:sp_id, :....) into :int_result_var using sqlca;)
OR you can use it directly in your original SQL Statement and replace your rank column (empty) with a call to the function.
IMO: stored procs are good when you need multiple rows/columsn to be returned while a function is easier to use when there's a single return value.
Hope this helps.
(note: I'm not a daily MSSQL user, so this is all untested code, but I think the concept is solid)
edit: original submit screwed up the formatting