简体   繁体   中英

How to convert varchar value to numeric

I have a column in database which is varchar. How can I convert to integer in order to get the sum in crystal report. Will it possible to conver the varchar to numeric when using the stored procedure....

To do it in C# without using Try/Catch:

int value = 0;
if (Int32.TryParse("string to parse", out value))
{
    // Value parsed correctly        
}
else
{
    // Could not be parsed.
}

You might be better off doing it in the database query though if possible. Also as others have suggested, why is a numeric being stored in a varchar field?

Edit

Both Transact SQL and PL/SQL dialects support the CAST function.

You could probably do the conversion in the query using - although be aware that there may be subtle differences in the actual database you are using.

SELECT ..., CAST(field_name AS int), ... FROM table_name ...

Thanks to Anjay for his most valuable contributions.

This should do it:

SELECT SUM(CONVERT(INT , varchar_column)) FROM [test]

You use the following functions in Stored procedure or Views and use them in Crystal report which will do the calculation part.

SELECT CAST(YourVarcharCol AS INT) FROM Table
or

SELECT CONVERT(INT, YourVarcharCol) FROM Table

http://msdn.microsoft.com/en-us/library/aa226054(v=sql.80).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM