Johanna
Johanna

Reputation: 27640

How in T-SQL to multiplying two different datatypes?

How can I multiply two types in SQL Server?

I have one column with cost, whose datatype is money, and another integer column that has the number of those products.

How can I multiply these two values to result in a value representing the cost?

Example: $2000 * 2

Upvotes: 0

Views: 4983

Answers (3)

Bogdan Bogdanov
Bogdan Bogdanov

Reputation: 1723

Dependantly of the types implicit or explicit convertion will take place (as @KM commented).

Implicit convertion is done automatically by SQL Server (which is your case). If it is not possible Error occurs.

Explicit convertion is done by developer (in SQL server using CAST or CONVERT). If convertion is not possible Error occurs.

For more information see SQL Server CAST and CONVERT help.

Upvotes: 0

OMG Ponies
OMG Ponies

Reputation: 332571

Use:

SELECT t.number_of_items * t.cost_of_item AS total_cost
  FROM PRODUCTS t

Upvotes: 4

JNK
JNK

Reputation: 65157

DECLARE @UNITS int
DECLARE @UnitCost money

SET @UNITS = 100
SET @UnitCost = 2.20

SELECT (@UNITS * CONVERT(decimal(18,2), @unitcost)) as Total

Replace the @variables with your column names.

Upvotes: 1

Related Questions