搜索字符串信用卡数值

时间:2014-10-01 07:30:55

标签: sql sql-server tsql

我想在sql字符串中找到信用卡数值。

例如

;

DECLARE @value1 NVARCHAR(MAX) = 'The payment is the place 1234567812345678'
DECLARE @value2 NVARCHAR(MAX) = 'The payment is the place 123456aa7812345678'
DECLARE @value3 NVARCHAR(MAX) = 'The payment1234567812345678is the place'

结果应为:

@value1Result 1234567812345678
@value2Result NULL
@value3Result 1234567812345678

16位必须在一起,没有空格。

如何在sql脚本或函数中执行此操作?

编辑: 如果我想找到这2张信用卡价值。

@value4 = 'card 1 is : 4034349183539301 and the other one is 3456123485697865'

我该如何实现脚本?

4 个答案:

答案 0 :(得分:4)

您可以将PathIndex用作

PATINDEX('%[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', yourStr) 

如果结果为0,则它​​不包含其他16位数字。

可以根据您的需要使用Where声明或Select声明

答案 1 :(得分:1)

你可以写成:

SELECT case when Len(LEFT(subsrt, PATINDEX('%[^0-9]%', subsrt + 't') - 1)) = 16
                 then LEFT(subsrt, PATINDEX('%[^0-9]%', subsrt + 't') - 1)
                 else ''
                 end
FROM (
    SELECT subsrt = SUBSTRING(string, pos, LEN(string))
    FROM (
        SELECT string, pos = PATINDEX('%[0-9]%', string)
        FROM table1
    ) d
) t

Demo

答案 2 :(得分:1)

DECLARE @ value1 NVARCHAR(MAX)='卡1是:4034349183539301,另一个是3456123485697865' DECLARE @Lenght INT     ,@ Count INT     ,@ Candidate CHAR     ,@ cNum INT     ,@ result VARCHAR(16)

SELECT @Count = 1

SELECT @cNum = 0

SELECT @result =''

SELECT @Lenght = LEN(@ value1)

WHILE @Count< = @Lenght 开始     SELECT @Candidate = SUBSTRING(@ value1,@ Count,1)

IF @Candidate != ' '
    AND ISNUMERIC(@Candidate) = 1
BEGIN
    SET @cNum = @cNum + 1
    SET @result = @result + @Candidate
END
ELSE
BEGIN
    SET @cNum = 1
    SET @result = ''
END

IF @cNum > 16
BEGIN
    SELECT @result 'Credit Number'
END

SET @Count = @Count + 1

END

答案 3 :(得分:0)

先生,你先去了。

 DECLARE 
    @value3 NVARCHAR(MAX) = 'The payment1234567812345678is the place',
    @MaxCount int,
    @Count int,
    @Numbers NVARCHAR(100)

SELECT @Count = 1
SELECT @Numbers = ''
SELECT @MaxCount = LEN(@value3)


WHILE @Count <= @MaxCount
BEGIN

    IF (UNICODE(SUBSTRING(@value3,@Count,1)) >= 48 AND UNICODE(SUBSTRING(@value3,@Count,1)) <=57)
        SELECT @Numbers = @Numbers + SUBSTRING(@value3,@Count,1)

    SELECT @Count = @Count + 1


END
PRINT @Numbers

如果您计划大量使用它,可以将其作为一项功能。