动态SQL和函数

时间:2010-06-08 16:27:25

标签: tsql stored-procedures function dynamic-sql

有没有办法完成以下内容:

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

这种方法的问题是禁止在函数中执行sp_excutesql ...

我需要做的事情是:

select id, getQtyFromID(id) as qty
from table

主要思想是执行存储在表格单元格中的查询,这是因为某些东西的数量取决于它的单位。单位可以是天或者可以是公吨,因此单位之间没有关系,因此需要对每个单位进行特定查询。

1 个答案:

答案 0 :(得分:3)

如何在存储过程中使用if then或case表达式检查单元,然后根据单元类型执行特定计算?