SQL:将+分隔列表转换为整数

时间:2016-04-07 14:06:38

标签: sql sql-server tsql

我们的数据库中有一列包含+个字符串的字符串。无论如何选择每一行的总和?也就是说,我们有5212667+5212662;我想选择10425329

我试过了CONVERT(INT, ColumnAddList),但这并没有奏效。

2 个答案:

答案 0 :(得分:5)

如果您使用SQL Server,则可以拆分并计算总和:

CREATE TABLE tab(ID INT IDENTITY(1,1), col VARCHAR(1000));

INSERT INTO tab(col) VALUES('5212667+5212662'),('1+2+3'),('2'), (NULL), ('1+-1');

SELECT *
FROM tab
CROSS APPLY (
    SELECT [result] = SUM( Split.a.value('.', 'BIGINT'))
    FROM (SELECT [X] = CAST ('<M>'+REPLACE(col, '+', '</M><M>') + '</M>' AS XML)) AS A 
    CROSS APPLY X.nodes ('/M') AS Split(a)
) AS s;

LiveDemo

输出:

╔════╦═════════════════╦══════════╗
║ ID ║       col       ║  result  ║
╠════╬═════════════════╬══════════╣
║  1 ║ 5212667+5212662 ║ 10425329 ║
║  2 ║ 1+2+3           ║ 6        ║
║  3 ║ 2               ║ 2        ║
║  4 ║ NULL            ║ NULL     ║
║  5 ║ 1+-1            ║ 0        ║
╚════╩═════════════════╩══════════╝

正确的方法是规范化表格架构。

答案 1 :(得分:3)

CREATE FUNCTION dbo.fnSplit(
@sInputList VARCHAR(8000) -- List of delimited items
 , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
 ) RETURNS @List TABLE (item VARCHAR(8000))

BEGIN
 DECLARE @sItem VARCHAR(8000)
 WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
  BEGIN
    SELECT
     @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX
      (@sDelimiter,@sInputList,0)-1))),  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX
      (@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))

  IF LEN(@sItem) > 0
    INSERT INTO @List SELECT @sItem
  END

 IF LEN(@sInputList) > 0
     INSERT INTO @List SELECT @sInputList -- Put the last item in
     RETURN
  END
GO

declare @table table (Val varchar(2000))
insert into @table values('1+1+1+')
insert into @table values('2+2+2+')
insert into @table values('3+3+3+')
insert into @table values('4+4+4+')
select Val, (select sum(convert(decimal(10,2),item)) from dbo.fnSplit(val,'+') ) as summ from @table

希望这有帮助!!!

快乐编码!!!