什么SQLite列名可以/不可以?

pro*_*eek 35 sql sqlite keyword

SQLite的列名是否有任何规则?

  • 它可以有像'/'这样的字符吗?
  • 可以是UTF-8吗?

Spo*_*oks 24

http://www.sqlite.org/lang_keywords.html有一个完整的列表!请享用!

  • 这只是一个关键字列表,它不提供列名的允许字符. (18认同)

J. *_*fer 11

它可以有像'/'这样的字符吗?

所有示例都来自在Linux上运行的SQlite 3.5.9.

如果用双引号括住列名称,则可以:

> CREATE TABLE test_forward ( /test_column INTEGER );
SQL error: near "/": syntax error
> CREATE TABLE test_forward ("/test_column" INTEGER );
> INSERT INTO test_forward("/test_column") VALUES (1);
> SELECT test_forward."/test_column" from test_forward;
1
Run Code Online (Sandbox Code Playgroud)

也就是说,你可能不应该这样做.

  • 单引号用于字符串文字.双引号用于标识符.单引号在这里起作用,因为SQLite在它所接受的内容方面是自由的,但它是非标准的. (4认同)
  • 您可以,但它将是数据库剩余生命周期的 PITA。我强烈建议不要这样做。 (2认同)

use*_*443 9

以下答案基于 SQLite 源代码,主要依赖于文件parse.y(柠檬解析器的输入)。

特尔;博士:

CREATE TABLE语句中列名和表名允许的一系列字符是

  • '- 任何类型的转义字符串(甚至关键字)
  • 标识符,这意味着
    • ``` 和"-escaped 任何类型的字符串(甚至是关键字)
    • 下表中不构成关键字的一系列MSB=18 位 ASCII 字符或 7 位 ASCII 字符: 1有效的标识符字符
  • 关键字,INDEXED因为它是非标准的
  • JOIN我不知道的原因关键字。

SELECT语句中结果列允许的一系列字符是

  • 如上所述的字符串或标识符
  • 以上所有如果用作列别名写在 AS

现在到探索过程本身

  1. 让我们看看CREATE TABLE列的语法

    // The name of a column or table can be any of the following:
    //
    %type nm {Token}
    nm(A) ::= id(X).         {A = X;}
    nm(A) ::= STRING(X).     {A = X;}
    nm(A) ::= JOIN_KW(X).    {A = X;}
    
    Run Code Online (Sandbox Code Playgroud)
  2. 深入挖掘,我们发现

    // An IDENTIFIER can be a generic identifier, or one of several
    // keywords.  Any non-standard keyword can also be an identifier.
    //
    %type id {Token}
    id(A) ::= ID(X).         {A = X;}
    id(A) ::= INDEXED(X).    {A = X;}
    
    Run Code Online (Sandbox Code Playgroud)

    “通用标识符”听起来很陌生。tokenize.c然而,快速浏览一下定义

    /*
    ** The sqlite3KeywordCode function looks up an identifier to determine if
    ** it is a keyword.  If it is a keyword, the token code of that keyword is 
    ** returned.  If the input is not a keyword, TK_ID is returned.
    */
    
    /*
    ** If X is a character that can be used in an identifier then
    ** IdChar(X) will be true.  Otherwise it is false.
    **
    ** For ASCII, any character with the high-order bit set is
    ** allowed in an identifier.  For 7-bit characters, 
    ** sqlite3IsIdChar[X] must be 1.
    **
    ** Ticket #1066.  the SQL standard does not allow '$' in the
    ** middle of identfiers.  But many SQL implementations do. 
    ** SQLite will allow '$' in identifiers for compatibility.
    ** But the feature is undocumented.
    */
    
    Run Code Online (Sandbox Code Playgroud)

    有关标识符字符的完整映射,请参阅tokenize.c.

  3. 目前还不清楚 a 的可用名称是什么result-column(即在SELECT语句中分配的列名或别名)。parse.y在这里再次有帮助。

    // An option "AS <id>" phrase that can follow one of the expressions that
    // define the result set, or one of the tables in the FROM clause.
    //
    %type as {Token}
    as(X) ::= AS nm(Y).    {X = Y;}
    as(X) ::= ids(Y).      {X = Y;}
    as(X) ::= .            {X.n = 0;}
    
    Run Code Online (Sandbox Code Playgroud)