如何计算SQL中行的值?

时间:2015-03-25 06:31:28

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

我想在行中添加值,如下面代码中所述。

enter image description here

我在这里发布了一些示例代码。

Create Table #temp1
(
  ID int,
  Value Varchar(MAX)
)

Insert into #temp1 Values
(1,'0.1+0.26'),
(2,'1.1+7.25-4.65'),
(3,'2.1+6.24*3.3'),
(4,'3.14+5.23*2.2'),
(5,'0.143+4.22/3.4')

Select * from #temp1

Drop Table #temp1


Select 1 ID,0.1+0.26 [Value]
Union ALL
Select 2 ID,1.1+7.25-4.65 [Value]
Union ALL
Select 3 ID,2.1+6.24*3.3 [Value]
Union ALL
Select 4 ID,3.14+5.23*2.2 [Value]
Union ALL
Select 5 ID,0.143+4.22/3.4 [Value]

任何人都可以建议我解决这个问题。

1 个答案:

答案 0 :(得分:3)

使用Dynamic query。试试这个。

SELECT *,
       0 AS t
INTO   #pars_temp -- Intermediate table for parsing each row
FROM   #temp1

DECLARE @sql NVARCHAR(max),
        @id  INT,
        @val VARCHAR(5000)

WHILE EXISTS(SELECT 1
             FROM   #pars_temp
             WHERE  t = 0)-- To check the existence of unparsed row 
  BEGIN
      SELECT TOP 1 @val = value,
                   @id = id
      FROM   #pars_temp
      WHERE  t = 0

      SET @sql ='update #temp1 set value  = ' + @val
                + ' where id = ' + CONVERT(VARCHAR(10), @id) -- update the values

      EXEC Sp_executesql @sql

      UPDATE #pars_temp
      SET    t = 1
      WHERE  id = @id -- To remove the parsed row
  END

SELECT *
FROM   #temp1