通过在存储过程中将逗号分隔的整数作为字符串传递来查找最大值

时间:2017-10-18 08:52:07

标签: sql-server

String = '45,12,37,89,10,107,64,97' 

创建一个以逗号分隔值的过程,我们可以说数字数组并查找 最大值。

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作。

创建一个提取数据的函数

CREATE FUNCTION [dbo].[fnSplitString]
(
      @str as varchar(max),
      @delimiter as varchar(1)
)
RETURNS @TableReturn table(ID integer)
AS
BEGIN
    IF (@str IS NULL or @str ='')
        BEGIN
              INSERT INTO @TableReturn SELECT 0
        END
    ELSE
        WHILE (charindex(@delimiter,@str)>0)
        BEGIN
            INSERT INTO @TableReturn
            SELECT SUBSTRING (@str,1,charindex(@delimiter,@str)-1)
            SET @str = SUBSTRING (@str,charindex(@delimiter,@str)+1, len(@str))
        END
        IF (@str <> '' and @str <> ',' )
        BEGIN
            INSERT INTO @TableReturn SELECT @str
        END
    RETURN 
END

然后叫它:

SELECT TOP(1)* FROM dbo.fnSplitString('45,12,37,89,10,107,64,97', ',') ORDER BY ID DESC

否则:

SELECT MAX(ID) FROM dbo.fnSplitString('45,12,37,89,10,107,64,97', ',')

答案 1 :(得分:0)

我将此方法加入书签。不记得来源,但它就像魅力一样。已为您修改过。试试:

Create table #Testdata(Data varchar(max))
Insert #Testdata select '45,12,37,89,10,107,64'


;with tmp(DataItem, Data) as (
select LEFT(Data, CHARINDEX(',',Data+',')-1),
       STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from #Testdata
union all
select LEFT(Data, CHARINDEX(',',Data+',')-1),
       STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from tmp
where Data > ''
)
select  max(cast(DataItem as int))
from tmp
OPTION (maxrecursion 0)