Selecting a column with period in the column name SQL Server

偶尔善良 提交于 2019-12-23 11:59:09

问题


I am linked to a Proficy Historian that allows periods in the column names. Because the data is stored in a non DBMS format I can not use openquery to get the data because there is no set schema to the tables. So I must use four part name syntax to get the data. This example works:

SELECT * FROM iHist...[SELECT * FROM ihTrend]

but this fails with Incorrect syntax near '.'.

SELECT * FROM iHist...[SELECT [SERVER.pid_astatus[07][0].F_CV.Value] FROM ihTrend]

where SERVER.pid_astatus[07][0].F_CV.Value is the name of the column

This fails as well with Incorrect syntax near the keyword 'from'.

SELECT * FROM 
    iHist...[SELECT [SERVER.pid_astatus[[07]][[0]].F_CV.Value] from ihTrend]`

Any ideas on how I can make SQL Server see this as a column?

EDIT:

Martins suggestion of the right brackets to escape the brackets work only on the outside of the sql call

SELECT [SERVER.pid_astatus[07]][0]].F_CV.Value] FROM iHist...[SELECT * FROM ihTrend] 

However it does not work inside Incorrect syntax near the keyword 'from'.

SELECT * FROM iHist...[SELECT [SERVER.pid_astatus[07]][0]].F_CV.Value] FROM ihTrend]

EDIT

SELECT * FROM iHist...[SELECT [SERVER.pid_astatus[07]][0]].F_CV.Value]] FROM ihTrend] 

I had to escape the column escape :)


回答1:


You only need to escape these ]

[pid_astatus[07]][0]].F_CV.Value]

This works for me

CREATE TABLE #t(
    [pid_astatus[07]][0]].F_CV.Value] int
) 

SELECT [pid_astatus[07]][0]].F_CV.Value]
FROM #t



回答2:


(Edited to reflect new knowledge, if you like this vote for Martin Smith's answer instead!)

Escape the ] by doubling them:

SELECT * FROM 
    iHist...[SELECT [SERVER.pid_astatus[07]][0]].F_CV.Value] from ihTrend]

Based on your comment, try:

SELECT [SERVER.pid_astatus[07]][0]].F_CV.Value] FROM iHist...ihTrend


来源:https://stackoverflow.com/questions/3284929/selecting-a-column-with-period-in-the-column-name-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!