How to deal with SQL column names that look like S

2019-01-01 09:06发布

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 or is there a special syntax to avoid the SQL Server being confused?

14条回答
旧人旧事旧时光
2楼-- · 2019-01-01 09:12

These are the two ways to do it:

  1. Use back quote as here:

SELECT `from` FROM TableName

  1. You can mention with table name as:

SELECT TableName.from FROM TableName

查看更多
看淡一切
3楼-- · 2019-01-01 09:13

While you are doing it - alias it as something else (or better yet, use a view or an SP and deprecate the old direct access method).

SELECT [from] AS TransferFrom -- Or something else more suitable
FROM TableName
查看更多
人气声优
4楼-- · 2019-01-01 09:13

The following will work perfectly:

SELECT DISTINCT table.from AS a FROM table
查看更多
ら面具成の殇う
5楼-- · 2019-01-01 09:14

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

查看更多
步步皆殇っ
6楼-- · 2019-01-01 09:20

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).

查看更多
看淡一切
7楼-- · 2019-01-01 09:21

In Apache Drill, use backquotes:

select `from` from table;
查看更多
登录 后发表回答