2

Consider the following TSQL code:

declare @a nvarchar(500) = N''
select try_convert(float, @a)

The output is:

0

I need the output to be NULL.

I can do this:

declare @a nvarchar(500) = N''
select case @a
           when '' then null
           else try_convert(float, @a)
       end

and it works just fine.

However, this is just a mock-up. In my real life scenario, instead of @a, there are over 200 NVARCHAR(500) columns, either floats or zero length strings. I need a quick way of converting zero-length strings to NULL (and everything else to float), possibly without having to build 200 separate CASE statements.

1
  • 1
    For a zero-length string there is an implicit conversion from varchar to int. Commented Jun 12, 2018 at 7:39

2 Answers 2

4

I'm not really thrilled with relying the rather inexplicable differences between try_parse() and try_convert()/try_cast(). Instead, I would go for:

try_convert(float, nullif(@a, ''))

This also has the advantage of being quite explicit in what you are trying to accomplish.

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

Comments

3

You should use Try_parse instead

declare @a nvarchar(500) = N''
select try_parse( @a as float)

returns

NULL

See working demo

Comments

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.