HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Calculation With VARCHAR

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
withcalculationvarchar

Problem

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;

Solution

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.

Code Snippets

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;

Context

StackExchange Database Administrators Q#164611, answer score: 6

Revisions (0)

No revisions yet.