简体   繁体   English

在SQL中是否可以将字符串自动转换为整数?

[英]Is string to integer conversion automatic in SQL?

I have a SQL statement to insert a record into a table. 我有一条SQL语句可将记录插入表中。 The table is defined as; 该表定义为:

+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| title       | varchar(255) | NO   |     | NULL    |                |
| description | text         | NO   |     | NULL    |                |
| filename    | varchar(255) | NO   |     | NULL    |                |
| type        | varchar(255) | NO   |     | NULL    |                |
| size        | int(11)      | NO   |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

The SQL statement is; SQL语句是;

INSERT INTO photos 
  (title, description, filename, type, size) 
VALUES 
  ('Title D', 'Description D', 'Filename_D', 'BMP', '2000');

I was always taught that if you did not match column type to the type of data you were trying to insert or update, SQL would throw an error. 我总是被告知,如果您没有将列类型与尝试插入或更新的数据类型匹配,SQL将会抛出错误。

To my surprise the SQL statement worked in MySQL and MS Access even though the "size" column is defined as integer and the size data in the SQL statement is enclosed in quotes making it a string ('2000'). 令我惊讶的是,即使“ size”列定义为整数并且SQL语句中的size数据用引号括起来使其成为字符串('2000'),该SQL语句仍在MySQL和MS Access中工作。

Is this a MySQL and MS Access feature or is this how SQL works across all SQL compliant databases? 这是MySQL和MS Access功能还是SQL在所有符合SQL的数据库中如何工作?

String to number conversion is automatic in most databases. 在大多数数据库中,字符串到数字的转换是自动的。 So, you can express your query this way: 因此,您可以通过以下方式表达您的查询:

INSERT INTO photos (title, description, filename, type, size) 
    VALUES ('Title D', 'Description D', 'Filename_D', 'BMP', '2000');

This is a bad idea, because implicit conversion can generate conversion errors -- and you have no clue where they come from. 这是一个坏主意,因为隐式转换会产生转换错误-而且您不知道它们来自何处。 I strongly advocate using the right types or explicit conversion: 我强烈建议使用正确的类型或显式转换:

INSERT INTO photos (title, description, filename, type, size) 
    VALUES ('Title D', 'Description D', 'Filename_D', 'BMP', 2000);

Thank you Gordon Linoff for the answer. 谢谢Gordon Linoff的回答。

Eric Brandt, I will open a fresh question on this. 埃里克·勃兰特(Eric Brandt),我将对此提出一个新的问题。 I'm also interested in seeing the response. 我也很想看到回应。

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

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