简体   繁体   中英

search in a string creditcard numeric value

I want to find a credit card numeric value in a sql string.

for example;

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'

The result should be :

@value1Result 1234567812345678
@value2Result NULL
@value3Result 1234567812345678

16 digits must be together without space.

How to do this in a sql script or a function?

edit : if I want to find these 2 credit card value.

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

how should I implement the scripts?

You can use PathIndex as

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) 

if the result is 0 then it doesnt containg 16 digits other was it contains.

It can be used withing a Where statement or Select statement based on your needs

You can write as:

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

DECLARE @value1 NVARCHAR(MAX) = 'card 1 is : 4034349183539301 and the other one is 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 BEGIN 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

There you go kind sir.

 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

You can make this as a function if you are planning to use it a lot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM