使用sql中不同表的公式除

时间:2015-01-23 09:00:07

标签: sql sql-server sql-server-2008

我需要在sql server 2008中评估一个公式

表1包含

Entity  Value
A       2424053.500000
B       1151425.412500
C       484810.700000

表2包含

Entity  Formula
A       (2100*(1-0.0668)*24*mday*10) 
B       (1000*(1-0.0575)*24*mday*10)
C       (1260*(1-0.09)*24*mday*10)

其中mday是用户的天数。 Formula的数据类型是一个字符串。

我需要计算每个实体的值/公式的输出 你可以提供相同的查询

1 个答案:

答案 0 :(得分:0)

SQL Server 2008的示例解决方案,根据需要进行调整...

IF EXISTS (SELECT * FROM sys.tables WHERE object_id = object_id('EntityValue'))
BEGIN
    DROP TABLE EntityValue;
END;

CREATE TABLE EntityValue
(
    Id CHAR(1),
    mdayValue DECIMAL(13, 6)
)

INSERT INTO EntityValue
    VALUES ('1', 2424053.500000)
    , ('2', 1151425.412500)
    , ('3', 484810.700000)

IF EXISTS (SELECT * FROM sys.tables WHERE object_id = object_id('EntityFormula'))
BEGIN
    DROP TABLE EntityFormula;
END;

CREATE TABLE EntityFormula
(
    Id CHAR(1),
    Formula NVARCHAR(MAX)
)

INSERT INTO EntityFormula
    VALUES ('1', '(2100*(1-0.0668)*24*mday*10)')
    , ('2', '(1000*(1-0.0575)*24*mday*10)')
    , ('3', '(1260*(1-0.09)*24*mday*10)')


DECLARE @FormulaTable AS TABLE
    (
        RowId INT IDENTITY(1,1)
        ,Formula NVarchar(max)
    );

INSERT INTO @FormulaTable (Formula)
SELECT Formula = REPLACE(eFormula.Formula, 'mday', CAST(eValue.mdayValue AS NVARCHAR(MAX)))
FROM EntityFormula AS eFormula
    INNER JOIN EntityValue AS eValue ON eValue.ID = eFormula.ID;

DECLARE @TSql NVarchar(max), @CurrentRowId INT;
SET @CurrentRowId = 1;
WHILE(1=1)
BEGIN

    SELECT @TSql = 'SELECT ' + Formula
    FROM @FormulaTable
    WHERE RowID = @CurrentRowId

    IF(@@ROWCOUNT = 0)
    BEGIN
        BREAK;
    END

    EXEC sp_executesql @Tsql

    SET @CurrentRowId = @CurrentRowId + 1;
END