Search code examples
sql-serverstored-proceduresisnumeric

IsNumeric does not work in SQL server


Getting very annoyed with this simple query...
I need to add an offset to a varchar, if it's a number and do nothing is it is not.
For this reason I've created the following function in SQL-server. I then extract the answer with: select dbo.OffsetKPL("100",200)

However this does not work, I get the error

Msg 207, Level 16, State 1, Line 1
Invalid column name '100'.

The code for the function is as follows...

ALTER FUNCTION [dbo].[OffsetKPL](
  @kpl varchar(20)
  ,@offset int = 0
)
RETURNS varchar(20)
AS
BEGIN   
  DECLARE @uitkomst varchar(20);

  set @uitkomst = @kpl;
  if not(@offset = 0) begin
    if (IsNumeric(@uitkomst) = 1) begin
      set @uitkomst = cast((cast(@kpl as int) + @offset) as varchar);
    end;
end;

RETURN @uitkomst;

END

What's wrong? nowhere does it state that IsNumeric does not accept a variable.


Solution

  • Use single quotes for strings!

    select dbo.OffsetKPL('100',200)
    

    If you have QUOTED_IDENTIFIER on (the default) things in double quotes are expected to be object names.

    isnumeric may not be what you need though as all kinds of unexpected things return 1 for this.

    SELECT ISNUMERIC('$'), ISNUMERIC('.'), 
           ISNUMERIC('12d5'), ISNUMERIC(','), ISNUMERIC('1e1')
    

    See IsNumeric() Broken? Only up to a point for some discussion on this point.