use*_*552 1 c# sqldbtype sql-server-2008 sql-server-2008-r2 sqlparameter
我在 SQL Server 中有一个存储过程,它有一个输出参数 pf type numeric(18,0)。我在 C# 中创建了一个SqlParameter带有 a 的对象SqlDbType.Decimal,并将精度设置为 18,小数位数设置为 0。
这是我的代码:
queryParameters[2] = new SqlParameter("@Id", SqlDbType.Decimal);
queryParameters[2].Precision = 18; // # digits
queryParameters[2].Scale = 0; // # decimals
queryParameters[2].Direction = ParameterDirection.Output;
Run Code Online (Sandbox Code Playgroud)
存储过程正确执行,并正确返回输出参数,但是当我将其解析为 C# 中的 long 变量时,如下所示:
long id = (long)queryParameters[2].Value;
Run Code Online (Sandbox Code Playgroud)
它说无法转换它。
但如果我将SqlParameter类型修改为SqlDbType.Bigint,那么它就可以工作。
那么我通过将其传递为 所做的事情是正确的吗SqlDbType.BigInt?或者最好将其作为传递SqlDbType.Decimal,然后使用十进制 C# 变量而不是 long ?
将其传递SqlDbType.Decimal为然后执行以下操作也有效:
decimal id = (decimal)queryParameters[2].Value;
Run Code Online (Sandbox Code Playgroud)
那么,考虑到这个数字是没有小数的整数,最好采用什么方法呢?
numeric(...)如果它是在数据库中定义的,那么它必须是C# 中的a decimal- 无论它(当前)在逗号后面是否有数字。
不要将其错误地表示为bigint/ long- 它显然不是那种类型!long另外 - 为什么你首先要尝试解析它/将其转换为 a ?对我来说毫无意义......它看起来像一个decimal,走路像一个decimal,嘎嘎叫起来像一个decimal- 那么你就很确定它是一个decimal!
如果您的 SQL Server 类型突然更改为 ,会发生什么情况numeric(20,2)?通过decimal在 C# 中使用 a - 就可以了,无需任何更改。如果您使用的long是,现在您需要开始将代码更改为decimal.
始终使用最合适的类型 - 对于 T-SQL numeric(),即decimalC# / .NET 中的类型。
| 归档时间: |
|
| 查看次数: |
3190 次 |
| 最近记录: |