SQL Server Calculation – How to Perform Calculations with VARCHAR

sql serversql-server-2008-r2t-sql

I am attempting to do a calculation in SQL Server 2008 R2 but I keep getting an error of

Msg 245, Level 16, State 1, Line 10
Conversion failed when converting the varchar value '.05' to data type int.

Altering table structure is not an option, is there a way I can alter the query so that this will succesfully execute?

DECLARE @Test1 TABLE
(
  field1 VARCHAR(10),
  field2 INT
);

INSERT INTO @Test1 ( field1, field2 )
    VALUES ( '.05', 12 );

SELECT field1 / field2 
FROM @Test1;

Best Answer

Is this what you want to happen?

DECLARE @Test1 TABLE
(
  field1 VARCHAR(10),
  field2 INT
);

INSERT INTO @Test1 ( field1, field2 )
    VALUES ( '.05', 12 );

SELECT field1 / CONVERT(DECIMAL(18, 2), field2)
    FROM @Test1;

Since this was marked as the answer: I converted the integer value to a decimal because of data type precedence. The string '.05' can't be converted to an integer, but it makes a perfectly fine decimal.