如何计算公式字段到SQL Server中的其他列

时间:2019-04-27 10:02:42

标签: sql-server formula

我有一个SQL Server列,其中包含以下数据:

formula    amount  ficheno
-----------------------------
100*444    100     6555
10*698     698     6555

我已经尝试过将SQL Server的varchar转换为两次出错。

需要将公式字段添加到结果字段...

2 个答案:

答案 0 :(得分:0)

您可以使用动态SQL评估表达式:

declare @sql nvarchar(max) = (
    select  string_agg(cast(
            'select ' + formula + ', ' + str(amount) + ', ' + str(ficheno)
            as nvarchar(max)), ';')
    from    YourTable
);
declare @temp table (id int, amount int, ficheno int);
insert @temp exec(@sql);
select * from @temp;

-->

id      amount  ficheno
44400   100     6555
6980    698     6555

Working example at db<>fiddle.

答案 1 :(得分:0)

我一直关注您的查询并获得成功,非常感谢@Andomar。审查了可在具有东西功能的sql server <2017上工作的代码。如果有人在寻找答案;

  declare @sql nvarchar(max) = (

 SELECT  STUFF( (SELECT ' select ' + str([LOGICALREF])  + ', ' + str([LOGICALREFI])  + ', ' + REPLACE( Formül,',','.') +';'

               from BM_211_URETIM_PLANLANAN t

               for xml path ('')

              ), 1, 1, '' )

  )

    declare @temp table ( [LOGICALREF] int, [LOGICALREFI] int, [Planlanan Miktar] FLOAT);

    insert @temp exec(@sql);