Click here to Skip to main content
16,016,180 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have read an excel sheet and inserted it into an table in sql. now i want to perform multiplication of two columns and store the result in 3rd column. the problem i m facing is since the table is read from an excel sheet those columns are in nvarchar data type. now i m not able to convert those data type in int or float. while i run the query select (a) * (b) as Tot from table1. i m getting the error as Operand data type nvarchar is invalid for multiply operator.. how can i avoid this?. i m not able to change the date type in sql table. In excel sheet also i've formatted those columns as number. but still while reading into sql server the data type is still varchar.
Posted
Updated 11-Aug-13 23:15pm
v2

Have a look at examples.

Below query:
SQL
SELECT A*B AS C
FROM (
	SELECT '123' AS A, '2' AS B
	) AS T

raises error:
Msg 8117, Level 16, State 1, Line 2
Operand data type varchar is invalid for multiply operator.

Why? Because of varchar data type. In this case numbers are stored as a text!!!

This query:
SQL
SELECT CONVERT(INT,A)*CONVERT(INT,B) AS C
FROM (
	SELECT '123' AS A, '2' AS B
	) AS T

returns: 246

Conclusion: Use appropriate data types[^]!
 
Share this answer
 
v2
Comments
ARUN K P 12-Aug-13 5:21am    
Thanks maciej los.
Maciej Los 12-Aug-13 5:23am    
You're welcome ;)
Try:
SQL
SELECT CONVERT(INT, a) * CONVERT(INT, b) AS Tot FROM Table1


[edit]Forgot the "1" of "Table1" - OriginalGriff[/edit]
 
Share this answer
 
v2
Comments
ARUN K P 12-Aug-13 5:21am    
Thanks griff. tat above query works fine.
OriginalGriff 12-Aug-13 5:25am    
You're welcome!
Maciej Los 12-Aug-13 5:23am    
+5
You may use the SQL CAST operator, see the documentation[^] for examples.
 
Share this answer
 
Comments
Maciej Los 12-Aug-13 5:23am    
+5
CPallini 12-Aug-13 5:25am    
Thanks.
ARUN K P 12-Aug-13 5:49am    
+5
CPallini 12-Aug-13 6:29am    
Thank you.
SQL
select cast(a as float) * cast(b as float) as Tot from tablename
Happy Coding!
:)
 
Share this answer
 
Comments
ARUN K P 12-Aug-13 5:57am    
+5
Aarti Meswania 12-Aug-13 6:07am    
Thank you! :)
jaideepsinh 26-Aug-13 9:37am    
5+ve.
Aarti Meswania 26-Aug-13 12:24pm    
thank you! :)
jaideepsinh 27-Aug-13 0:37am    
YW..By the way where you from.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900