难道这些语句不是应该其中一个有效而另一个失败吗?
直觉表明语句 2 应该失败,因为 int 后面有一个逗号,并且没有列出第二列。
然而,两者都有效,最后一列数据类型后面的尾随逗号“,”没有区别。
-- Statement 1
CREATE TABLE dbo.MyTable1( col1 int);
-- Statement 2
CREATE TABLE dbo.MyTable2( col1 int,);
但是(这是预期的):最后一个字段后面的两个逗号“,,”确实会导致失败:
-- Statement 3
CREATE TABLE dbo.MyTable3( col1 int,,);
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ','.
测试表明,它不仅仅是允许通过的最后一个字段之后的任何字符。例如,这会失败:
-- Statement 3
CREATE TABLE dbo.MyTable3( col1 int ~);
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '~'.
也许 SQL Server 正在“保留席位”?也许是主键?我真的不知道。
我使用的是 Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)。
最佳答案
Description
When executing the CREATE TABLE command, a trailing comma following the last column is allowed. Based on the grammar in BOL and comma usage in lists in other T-SQL statements, this behavior is inconsistent. This is a very minor issue and does not appear to cause any adverse side-effects. It just appears that the parser may be a bit off.
微软认为这是一个错误,但只是一个小错误。
This was resolved some time ago as "won't fix" but we didn't explain why. Simply, this seems pretty harmless, and not worth fixing in a service pack. We may consider fixing this in a future release.
关于tsql - 使用 T-SQL 创建表时,为什么最后一个字段后面的逗号不重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11241501/