简体   繁体   English

DECIMAL 值自行转换为 INT + 1

[英]DECIMAL values being converted to INT + 1 on its own

I have a C# app where the user fills a form to store a product in a SQL Server database.我有一个 C# 应用程序,用户可以在其中填写表单以将产品存储在 SQL Server 数据库中。

The problem is that every time a product is stored (through the user filling a form), the price (a decimal) is automatically converted to int and has 1 added to it.问题是每次存储产品时(通过用户填写表单),价格(小数)会自动转换为int并添加 1。

I initially thought it was an issue with the app, however, the registration process is pretty simple and I didn't find any error there, so I inserted a row directly from SQL Server and the issue presented itself, so this tells me the issue is in SQL Server, not in the app .我最初认为这是应用程序的问题,但是,注册过程非常简单,我没有在那里发现任何错误,所以我直接从 SQL Server 插入了一行并且问题出现了,所以这告诉我问题是在 SQL Server 中,而不是在应用程序中

Executing执行

insert into product (code, description, unit_price, stock, category_code)
values (7, 'Window Cleaner', 20.50, 20, 3)

Results into price being 21.结果价格为 21。

This is the table definition这是表定义

CODE INT NOT NULL,
DESCRIPTION VARCHAR(30) NOT NULL,
UNIT_PRICE DECIMAL NOT NULL,
STOCK INT NOT NULL,
CATEGORY_CODE INT NOT NULL
CONSTRAINT PK_PRODUCT PRIMARY KEY(CODE),
CONSTRAINT FK_CATEGORY_CODE FOREIGN KEY (CATEGORY_CODE) REFERENCES Category(CODE),
CONSTRAINT PRODUCT_POSITIVE_VALUES CHECK(UNIT_PRICE > 0 AND CODE >= 0 AND STOCK >= 0)

You have used the following to define your column:您已使用以下内容来定义您的列:

UNIT_PRICE DECIMAL NOT NULL

This has no precision nor scale and will therefore use the default precision (18) and scale (0).这没有精度和小数位数,因此将使用默认精度 (18) 和小数位数 (0)。 The default scale of 0 is effectively an int . 0 的默认比例实际上是一个int So when you insert/update a value the value will get rounded to an int .因此,当您插入/更新值时,该值将四舍五入为int To solve your problem define your column with the correct precision and scale eg为了解决您的问题,请以正确的精度和比例定义您的列,例如

UNIT_PRICE DECIMAL(9,2) NOT NULL

Reference 参考

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

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