【问题标题】:How to do an EVAL expression in SQL如何在 SQL 中执行 EVAL 表达式
【发布时间】:2018-07-30 06:55:46
【问题描述】:

我有一个表格,其中有一列以逗号分隔的数字。我想将每条记录的所有数字加在一起。使用 spexecuteSQL 我已经做到了这一点,但它仍然没有评估该领域。我该怎么做?

eg. 字段是 '4,5,5' 转置为 4+5+5 但想要评估并得到 ---> 14

declare @com as nvarchar(100)
set @com= 'select replace(class_historyTY,'','',''+'') from #aety1'

exec sp_executesql @com

【问题讨论】:

  • 创建一个“4+5+5”的“数学字符串”是行不通的。您必须四处搜索拆分函数以获取“4,5,5”并将其设为 3 行,然后在该列上使用 sum()
  • 你只想ADD 对吧?或者您有更复杂的哮喘要执行?

标签: sql sql-server


【解决方案1】:

如果您有 SQL Server 2016,以下应该可以工作:

select name, sum(cast(t.value as int)) from
(select name, cs.Value
from details
cross apply STRING_SPLIT (name, ',') cs) t
group by name

我的桌子的样子:

details
---------------
name
--------------
1,2,3,4
---------------
10,20,30

结果:

 name | 
 1,2,3,4 | 10
 10,20,30 | 60

【讨论】:

    【解决方案2】:

    由于 Josef 建议的交叉应用是这样做的正确方法,因此您使用 sp_executesql 提供了一个解决方案:

    Declare @s nvarchar(max) = 'select ' 
                    + (select replace(class_historyTY,',','+')  from #aety1) 
    exec sp_executesql  @s
    

    这里的想法是首先创建您的 sum 字符串 4+5+5,然后将其包装在 select 语句中,然后将表达式 select 4+5+5 传递给 sp_executesql

    【讨论】:

      猜你喜欢
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 2019-12-30
      相关资源
      最近更新 更多