简体   繁体   English

如何将varchar值转换为数字

[英]How to convert varchar value to numeric

I have a column in database which is varchar.我在数据库中有一个列是 varchar。 How can I convert to integer in order to get the sum in crystal report.如何转换为 integer 以获得水晶报表中的总和。 Will it possible to conver the varchar to numeric when using the stored procedure....使用存储过程时是否可以将 varchar 转换为数字....

To do it in C# without using Try/Catch:在不使用 Try/Catch 的情况下在 C# 中执行此操作:

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?也正如其他人所建议的那样,为什么将数字存储在 varchar 字段中?

Edit编辑

Both Transact SQL and PL/SQL dialects support the CAST function. Transact SQLPL/SQL方言都支持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.感谢 Anjay最宝贵的贡献。

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.您在存储过程或视图中使用以下函数,并在将执行计算部分的 Crystal 报表中使用它们。

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 http://msdn.microsoft.com/en-us/library/aa226054(v=sql.80).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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