SQL:从字符串返回第一个非空值

时间:2016-02-05 15:23:14

标签: sql sql-server tsql

问题:我想从字符串中检索第一个非空值,子字符串用,作为分隔符分隔。

场景:

字符串1 - ,1002682657

字符串2 - 1002682683,

String 3 - ,, 1002682684

字符串4 - ,,,

String 5 - 1002682664,1002682663

预期结果

ResultString 1 - 1002682657

ResultString 2 - 1002682683

ResultString 3 - 1002682684

ResultString 4 - 空值

ResultString 5 - 1002682664

所以要检索这个我写的函数是脚本

CREATE FUNCTION [dbo].[Return_first_NonNull_Value_From_list]
(
    @List NvarChar(MAX)
)
RETURNS NVarChar
AS
BEGIN
-- Declare the return variable here
DECLARE @ReturnListPart NvarChar(max)
DECLARE @Start INT
DECLARE @End INT
DECLARE @Length INT
DECLARE @Length_String INT

SET @Start = 1
SET @End = CHARINDEX(',',@List,@Start) 
SET @Length = (@End - @Start) + 1
SET @Length_String= (@END-@Start)+1

SET @pos = 0
SET @nextpos = 1

WHILE @Start>0 and @End>0 and @Length_String>0
    BEGIN
        IF (SUBSTRING(@List, @Start, 1) <> '') AND (SUBSTRING(@List, @Start,2) <>'')
            BEGIN                   
                SET @ReturnListPart = SUBSTRING(@List,@Start,@Length)
                SET @Length_String= LEN(@ReturnListPart)
                IF @Length_String > 1
                    BEGIN
                        SET @Length_String =0
                    END
            END

        ELSE
            BEGIN
            -- Replace the string with null value if null
                SET @List = LTRIM(RTRIM(STUFF(@List,@Start,@Length,'')))
                SET @Length_String = LEN(@List)
            END             
    END

RETURN RTRIM(LTRIM(@ReturnListPart))

END

但是这个函数没有返回预期的结果。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

根据你的问题有两个假设,你可以很容易地做到这一点。看起来你的数字都是10个字符长,而且它们只有数字(没有字符)。

考虑到这一点,你可以用这样的模式匹配来做到这一点:

SELECT CASE WHEN [Value] LIKE '%[0-9]%' THEN SUBSTRING([Value], PATINDEX('%[0-9]%', [Value]), 10)
         ELSE NULL
       END [Value]
  FROM [#Test]

我们可以直接折扣任何没有数字字符的行并返回null,其余的我们会查找第一个数字字符并获得接下来的10个字符。

在sql server中运行的完整示例将是:

CREATE TABLE [#Test]
(
  [Value] NVARCHAR(1000)
)

INSERT INTO [#Test] ( [Value] ) VALUES  ( N',1002682657')
INSERT INTO [#Test] ( [Value] ) VALUES  ( N'1002682683,')
INSERT INTO [#Test] ( [Value] ) VALUES  ( N',,1002682684')
INSERT INTO [#Test] ( [Value] ) VALUES  ( N',,,')
INSERT INTO [#Test] ( [Value] ) VALUES  ( N',1002682664,1002682663')

SELECT CASE WHEN [Value] LIKE '%[0-9]%' THEN SUBSTRING([Value], PATINDEX('%[0-9]%', [Value]), 10)
         ELSE NULL
       END [Value]
FROM [#Test]

DROP TABLE [#Test]
相关问题