9

I've a query like below:-

DECLARE @rptID VARCHAR(8)
SET @rptID = (SELECT reportID FROM Reports)

In general @rptID contains numeric digits like '00001234' etc. But is there any way to validate if the variable @rptID contains any non-numeric value in it.

For ex.

IF (@rptID contains non-numeric value)
            THEN throw Error
Kings
  • 1,551
  • 12
  • 32
  • 52
  • possible duplicate of [How to detect if a string contains atleast a number?](http://stackoverflow.com/questions/2558825/how-to-detect-if-a-string-contains-atleast-a-number) – ebram khalil May 11 '14 at 15:40
  • Relevant: https://stackoverflow.com/q/28370295/1369235 – Himanshu Aug 18 '21 at 10:28

2 Answers2

26

Check for any characters that are not in the range 0 to 9

^ is not in LIKE expressions

IF @rptID LIKE '%[^0-9]%'
   --throw error 
gbn
  • 422,506
  • 82
  • 585
  • 676
0

There is also an ISNUMERIC function in MSSQL if you're using version 2008 or later.

mentioned link

IF (not ISNUMERIC(@rptID) = 1)
    THEN throw Error
Hasan
  • 1,243
  • 12
  • 27