2

Is it possible to do something like this?

declare @ShouldBeNumber as varchar(10)
set @ShouldBeNumber = 1

declare @Number as varchar(10)

select @Number = case when ISNUMERIC(@ShouldBeNumber) then @Number = @ShouldBeNumber else @Number = '' end

i.e. only assign the variable if it is numeric. I have spent the last hour Googling this and have not found anything.

For example, I have looked here: How to check if a variable has a value in a SQL Server 2008 stored procedure

1
  • Does your code not work? Can you provide sample data and desired results? Commented Apr 16, 2020 at 14:15

2 Answers 2

1

I think you just want:

select @Number = (case when ISNUMERIC(@ShouldBeNumber) = 1
                       then @ShouldBeNumber else @Number
                  end)

I assume isnumeric() does what you want, although it might have some unwanted behavior depending on your needs (accepting negative numbers, decimals, and exponential notation for instance). The else clause is a no-op; it just assigns the existing value back to @Number.

Sign up to request clarification or add additional context in comments.

3 Comments

@w0051977 Just make sure this does what you want. This will result in @ number being null if @ ShouldBeNumber is not a number. Your post made it look like you want it to be a empty string
@Kevin, thanks. I changed my code to: else Number (with an @ sign at the beginning) after I reviewed the answer earlier today.
are you able to take a look at my other question here: stackoverflow.com/questions/61273521/… ?
1

You can also use the try_cast() function as shown below.

DECLARE @ShouldBeNumber AS VARCHAR(10)
SET @ShouldBeNumber = 'A'
DECLARE @number AS VARCHAR(10)

Select @number = isnull(cast(try_cast(@ShouldBeNumber as float) as varchar(10)),'')

SELECT @number

Live db<>fiddle demo.

2 Comments

you don't really need the case statement. you can just do select @ number = isnull(cast(try_cast(@ShouldBeNumber as int) as varchar),'')
@Kevin Changed as per your suggestion to improve the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.