线上发现数据库数据未按脚本进行更新,排查发现是数据update语句写得有问题。
update 语句如下:
UPDATE Product set Length = 2.23 and Height = 234.19 where ProductID = 1;
使用update语句更新多个字段值时,使用了and关键字,导致未按预想的方式进行更新。
完整的数据库建表语句如下:
-- INIT database
CREATE TABLE Product (
ProductID INT AUTO_INCREMENT KEY,
Name VARCHAR(100),
Length Decimal(6,2),
Height Decimal(6,2),
Description VARCHAR(255)
);
INSERT INTO Product(Name, Length, Height, Description) VALUES ('Entity Framework Extensions', 100.23, 234.19, 'Use <a href="https://entityframework-extensions.net/" target="_blank">Entity Framework Extensions</a> to extend your DbContext with high-performance bulk operations.');
INSERT INTO Product(Name, Length, Height, Description) VALUES ('Dapper Plus', 110.23, 345.23,'Use <a href="https://dapper-plus.net/" target="_blank">Dapper Plus</a> to extend your IDbConnection with high-performance bulk operations.');
INSERT INTO Product(Name, Length, Height, Description) VALUES ('C# Eval Expression', 200.00, 300.00 ,'Use <a href="https://eval-expression.net/" target="_blank">C# Eval Expression</a> to compile and execute C# code at runtime.');
数据库中数据如下:
当我使用上述语句去更新时,实际更新结果如下:
Length并没有被更新成2.23,而是被更新成1。原因如下:
UPDATE Product set Length = (2.23 and Height = 234.19) where ProductID = 1;
and 被解析成了逻辑与,(2.23 and Height = 234.19)的值被当作是Length要更新的值。Height = 234.19 为true,2.23的结果也为true, Length的结果就是1.00
正确的写法:
UPDATE Product set Length = 2.23, Height = 234.19 where ProductID = 1;
总结:对于数据库update语句,这是个非常基础的问题,关键在于测试环境中未实际执行过该语句,没有进行验证,导致了线上数据出问题。