【问题标题】:SSMS collecting several variables from stringSSMS 从字符串中收集多个变量
【发布时间】:2020-05-06 08:20:39
【问题描述】:

我正在使用 SQL Server 2008 和 SSMS,我正在尝试从一个字符串中收集多个变量值。

此方法仅在存在 ONE 变量时有效:

字符串:

There are 2 dogs walking the park in the summer and there are 4 dogs walking the park in the winter
SELECT 
    SUBSTRING(@txt, CHARINDEX('are', @txt), 
                    CHARINDEX('dogs', @txt) - CHARINDEX('are', @txt) + LEN('dogs')) 

这里的结果将是 2。我正在寻找一种方法来获得 2 或 4,或者总共 6。

如果我的信息不完整,请发表评论。

【问题讨论】:

  • 那么你是不是实际上说你想得到一个字符串中所有数字的总和使用T-SQL...?老实说,哪个与变量或 SSMS 无关? 旁注:SQL Server 2008 已停止支持几乎整整一年,如果您正在学习该语言,您应该查看升级路径或使用受支持的版本。
  • 这就是我想要的。数字可以不同。这就是为什么我称它为变量。
  • variable完全不同的东西。

标签: sql sql-server-2008 ssms


【解决方案1】:

这在最近的受支持版本的 SQL Server 中要简单得多。在 SQL Server 2008 中,您可以使用递归 CTE:

with cte as (
      select convert(varchar(max), 'There are 2 dogs walking the park in the summer and there are 4 dogs walking the park in the winter') as rest,
             convert(varchar(max), null) as val, 1 as lev
      union all
      select stuff(v.val, 1, patindex('%[^0-9]%', v.val + ' ') - 1, ''),
             left(v.val, patindex('%[^0-9]%', v.val + ' ')), lev + 1
      from cte cross apply
           (values (stuff(cte.rest, 1, patindex('%[0-9]%', cte.rest) - 1, ''))) v(val)
      where cte.rest like '%[0-9]%' 
     )
select val
from cte
where val is not null;

Here 是一个 dbfiddle。

【讨论】:

    【解决方案2】:

    一种方法是根据空格的位置将字符串分成单独的部分,然后找出哪些是整数,然后SUM那些。由于您使用的是不受支持的 SQL Server 版本,因此您无权访问 TRY_CONVERT,这会使这种方式更容易,但是,您至少可以使用 DelimitedSplit8K,这会导致像这样:

    SELECT SUM(CONVERT(int,DS.Item))
    FROM (VALUES('There are 2 dogs walking the park in the summer and there are 4 dogs walking the park in the winte'))V(YourString)
         CROSS APPLY dbo.DelimitedSplit8K(V.YourString,' ') DS
    WHERE DS.Item NOT LIKE '%[^0-9]%';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多