Scalar SQL function for checking if input value is integer

Viewed 37

Scalar SQL function for checking if input value is integer number or not. If not then throw error. Help me on this.

2 Answers

Please check this in SQL I believe it works for you.

DECLARE @Value NVARCHAR(100) = '1.5'
IF ISNUMERIC(@Value) = 0
BEGIN 
    RAISERROR('Value must be integer or decimal',16,1)
END
ELSE
BEGIN
    SELECT @Value
END

Result

  1. Integer enter image description here

  2. Decimal enter image description here

  3. String -> Error occurred in string. enter image description here

Just add the above logic into your script it's work.

Note: In this, you can handle decimals and integers.

Please check this updated for you

CREATE FUNCTION [dbo].[Numeric_validation] 
(
    @P_InputValues NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
BEGIN
    DECLARE @Value NVARCHAR(MAX) = NULL
    IF @P_InputValues LIKE '%[^0-9]%'
    BEGIN 
        RETURN CAST('Value must be integer' AS INT);
    END
    ELSE
    BEGIN
        SET @Value = @P_InputValues
    END
RETURN   @Value;
END
SELECT [dbo].[Numeric_validation] ('10')
SELECT [dbo].[Numeric_validation] ('10.50')
SELECT [dbo].[Numeric_validation] ('TEST')

the function will check if the input value is an integer or not ..if not then it will throw an error.

ALTER FUNCTION [dbo].[Numeric_validation] 
(
    @P_InputValues NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
BEGIN

RETURN   NULL;
END
GO

I have to put the logic within this

Related