How to deal with SQL column names that look like SQL keywords?

后端 未结 14 1096
温柔的废话
温柔的废话 2020-11-22 13:24

One of my columns is called from. I can\'t change the name because I didn\'t make it. Am I allowed to do something like SELECT from FROM TableName

相关标签:
14条回答
  • 2020-11-22 13:33

    In Apache Drill, use backquotes:

    select `from` from table;
    
    0 讨论(0)
  • 2020-11-22 13:38

    Wrap the column name in brackets like so, from becomes [from].

    select [from] from table;
    

    It is also possible to use the following (useful when querying multiple tables):

    select table.[from] from table;
    
    0 讨论(0)
  • 2020-11-22 13:40

    I ran in the same issue when trying to update a column which name was a keyword. The solution above didn't help me. I solved it out by simply specifying the name of the table like this:

    UPDATE `survey`
    SET survey.values='yes,no'
    WHERE (question='Did you agree?')
    
    0 讨论(0)
  • 2020-11-22 13:42

    Your question seems to be well answered here, but I just want to add one more comment to this subject.

    Those designing the database should be well aware of the reserved keywords and avoid using them. If you discover someone using it, inform them about it (in a polite way). The keyword here is reserved word.

    More information:

    "Reserved keywords should not be used as object names. Databases upgraded from earlier versions of SQL Server may contain identifiers that include words not reserved in the earlier version, but that are reserved words for the current version of SQL Server. You can refer to the object by using delimited identifiers until the name can be changed." http://msdn.microsoft.com/en-us/library/ms176027.aspx

    and

    "If your database does contain names that match reserved keywords, you must use delimited identifiers when you refer to those objects. For more information, see Identifiers (DMX)." http://msdn.microsoft.com/en-us/library/ms132178.aspx

    0 讨论(0)
  • 2020-11-22 13:44

    You can put your column name in bracket like:

    Select  [from] from < ur_tablename>
    

    Or

    Put in a temprary table then use as you like.
    Example:

    Declare @temp_table table(temp_from varchar(max))
    
    Insert into @temp_table
    Select * from your_tablename
    

    Here I just assume that your_tablename contains only one column (i.e. from).

    0 讨论(0)
  • 2020-11-22 13:45

    I have also faced this issue. And the solution for this is to put [Column_Name] like this in the query.

    string query= "Select [Name],[Email] from Person";
    

    So it will work perfectly well.

    0 讨论(0)
提交回复
热议问题