views:

33

answers:

1

Hi all, is there any way of accomplishing something like the following:

CREATE FUNCTION GetQtyFromID 
(
    @oricod varchar(15),
    @ccocod varchar(15),
    @ocmnum int,
    @oinnum int,
    @acmnum int,
    @acttip char(2),
    @unisim varchar(15)
)
AS
RETURNS DECIMAL(18,8)
BEGIN
    DECLARE @Result decimal(18,8)
    DECLARE @SQLString nvarchar(max);
    DECLARE @ParmDefinition nvarchar(max);

    --I need to execute a query stored in a cell which returns the calculated qty.
    --i.e of AcuQry: select @cant = sum(smt) from table where oricod = @oricod and ...

    SELECT     @SQLString = AcuQry
    FROM       OinActUni
    WHERE     (OriCod = @oricod) AND (ActTipCod = @acttip) AND (UniSim = @unisim) AND (AcuEst > 0)

    SET @ParmDefinition = N'
        @oricod varchar(15), 
        @ccocod varchar(15),
        @ocmnum int,
        @oinnum int,
        @acmnum int,
        @cant decimal(18,8) output';

    EXECUTE sp_executesql @SQLString, @ParmDefinition, 
            @oricod = @oricod, 
            @ccocod = @ccocod, 
            @ocmnum = @ocmnum, 
            @oinnum = @oinnum,
            @acmnum = @acmnum,
            @cant = @result OUTPUT;

    RETURN @Result

END

The problem with this approach is that it is prohibited to execute sp_excutesql in a function...

What I need is to do something like:

select id, getQtyFromID(id) as qty
from table

The main idea is to execute a query stored in a table cell, this is because the qty of something depends on it's unit. the unit can be days or it can be metric tons, so there is no relation between the units, therefore the need of a specific query for each unit.

+3  A: 

What about using an if then or case expression in a stored procedure to check the unit, then perform specific calculations based on the type of unit?

Zachary
+1: My thoughts exactly
OMG Ponies
@woolardz. I could but the SP would be like 1000 LOC. If there is no other way i guess i will have to go that way...
Unlimited071
(+1) @Unlimited071: Let's see: a single 1000 LOC s'proc, versus having an unknown number of queries stored as data in records. If table definition changes, all of those queries need to be tracked down and updated. If security changes, well, your screwed. If there are duplicate (most likely) types that use the same query, well, you get the picture. A single s'proc is MUCH more maintainable.
Chris Lively
Ok. I think that if something like this has not been resolved in tsql has to be for a reason, be that reason any of the above or not, I don't know; But I know it has to be a very good reason. Thank you all for your responses and time, I guess I'll go with the enormous s'proc. I will leave the question unanswered for the day just for the sake of hearing other options (if any).
Unlimited071