Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005 Convert VARCHAR to INT but default on invalid type

I have a varchar(100) column in a table that contains a mix of integers (as strings) and non-integer strings. E.g.

| dimension varchar(100) |
| '5'                    |
| '17'                   |
| '3'                    |
| 'Pyramids'             |
| 'Western Bypass'       |
| '15'                   |

How can I write an expression to, e.g. sum up all the values that are valid integers? If I were to try:

-- should return 5 + 17 + 3 + 15 = 40
SELECT
    SUM( CONVERT( INT, dimension ) )
FROM
    mytable

I would receive a Conversion failed when converting the varchar value 'Pyramids' to data type int. error.

Is there a test I can use in my expression, much like the ISNULL() function, that permits me to specify a default value if the field is not a number?

like image 296
PP. Avatar asked Mar 10 '10 18:03

PP.


People also ask

Can we convert varchar to int in SQL?

SQL Server's CAST() and CONVERT() methods can be used to convert VARCHAR to INT. We'll also look at the more efficient and secure approach to transform values from one data type to another.

Can we convert int to varchar?

Converting int to string/varchar using Cast() So, in the above example, we have declared a variable of integer data type and assigned a value to the variable. After this, we are using the Cast() function to convert the variable to the varchar data type of length 10.

Can you convert varchar to float?

If you are planning to convert varchar to float you should know that these two data types are not compatible with each other. In the earlier versions of SQL Server you had to use CASE, ISNUMERIC & CONVERT to convert varchar to float but in SQL Server 2012, you can do it with just one function TRY_CONVERT.


Video Answer


1 Answers

Try this:

SELECT
    SUM(CASE ISNUMERIC(dimension) 
           WHEN 1 THEN CONVERT( INT, dimension ) 
           ELSE 0  
        END)
FROM
    mytable

The CASE should check whether dimension is numeric - if so, return that value. If it's not numeric, return a default value (here: 0)

Is you need to query that quite frequently, you could also add a persisted, computed column to your table which encapsulates this computation and stores the value. This way, when summing and so on, you're not always re-computing the value:

ALTER TABLE mytable
  ADD NumericValue AS CASE ISNUMERIC(dimension) 
      WHEN 1 THEN CONVERT( INT, dimension ) ELSE 0 END PERSISTED

Now, you can SELECT dimension, numericvalue FROM mytable and get both values without any computation having to be executed.

like image 158
marc_s Avatar answered Sep 20 '22 19:09

marc_s