SQL Server Check if a variable string contains only certain characters

2fjabf4q  于 2023-04-19  发布在  其他
关注(0)|答案(1)|浏览(155)

I have a stored procedure with an input variable that I would like check if it only contains numbers or commas, and if it doesn't, throw an error. Ex's of the what the variable string could be:

@inputvariable = 489
@inputvariable = 489,504

I'm trying to do something like:

IF (@inputvariable NOT LIKE '%[0-9]%' OR @inputvariable NOT LIKE '%,%')
BEGIN
    RAISERROR ('@inputvariable can only contain numbers and commas', 18, 1)
    RETURN
END

If the variable contains at least 1 number or 1 comma, it doesn't through an error even if there are "invalid" characters. What am I doing wrong?

6ss1mwsb

6ss1mwsb1#

You may use the pattern [^0-9,] :

IF (@inputvariable LIKE '%[^0-9,]%')
    BEGIN RAISERROR ('@inputvariable can only contain numbers and commas', 18, 1)
    RETURN
END

The above would raise an error whenever the input variable contains a character which is not a digit or comma.

相关问题