我在C#中使用准备好的声明.
SqlCommand inscommand = new SqlCommand(supInsert, connection);
inscommand.Parameters.Add("@ordQty", SqlDbType.Decimal,18);
inscommand.Prepare();
u = inscommand.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)
以上代码抛出异常:
SqlCommand.Prepare方法要求"Decimal"类型的参数具有显式设置的Precision和Scale.
编辑:如何避免此异常
Mit*_*dir 32
以下将设置精度18和刻度8的十进制(十进制(18,8))
SqlCommand insertCommand= new SqlCommand(supInsert, connection);
insertCommand.Parameters.Add("@ordQty", SqlDbType.Decimal,18);
insertCommand.Parameters["@ordQty"].Precision = 18;
insertCommand.Parameters["@ordQty"].Scale = 8;
insertCommand.Prepare();
u = insertCommand.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)
正如异常所指出的那样,您必须显式设置SqlParameter.Precision和SqlParameter.Scale属性才能将decimal类型用作参数.
假设你的SQL字段是类型的decimal(18,8).内联方法是在将SqlParameter添加到SqlParameter时使用大括号初始化SqlParameterCollection,如下所示:
cmd.Parameters.Add(new SqlParameter("@ordGty", SqlDbType.Decimal) {
Precision = 18, Scale = 8 });
Run Code Online (Sandbox Code Playgroud)
你也可以
cmd.Parameters.Add(new SqlParameter("@ordGty", SqlDbType.Decimal) {
Precision = 18, Scale = 8}).Value = 0.4m; // or whatever
Run Code Online (Sandbox Code Playgroud)
如果需要,可以添加值.你甚至可以这样做
cmd.Parameters.Add(new SqlParameter("@ordGty", SqlDbType.Decimal) {
Precision = 18, Scale = 8, Value = 0.4m /* or whatever */});
Run Code Online (Sandbox Code Playgroud)
如果你更喜欢.Brace初始化非常强大.
旁注:我意识到这是一个老问题,但我认为这种形式比将对象添加到列表中然后设置比例和精度更具可读性.对于后人!(因为这是一个高级列表谷歌搜索结果)