简体   繁体   中英

How do you deal with blank spaces in column names in SQL Server?

Suppose I want to use code like this:

select 'Response Status Code', 'Client Response Status Code' 
from TC_Sessions (NOLOCK)
WHERE StartDate BETWEEN '05-15-2012' AND '06-01-2012'
AND SupplyID = 3367

How do you do this in SQL Server?

thank you!

select [Response Status Code], [Client Response Status Code]
from TC_Sessions (NOLOCK) 
WHERE StartDate BETWEEN '05-15-2012' AND '06-01-2012' 
AND SupplyID = 3367 

Wrap the names in square brackets.

It is , however, best to avoid spaces in names if possible. It just creates more work for you down the road...

select
   [Response Status Code],
   [Client Response Status Code] 
from TC_Sessions (NOLOCK)
WHERE StartDate BETWEEN '05-15-2012' AND '06-01-2012'
AND SupplyID = 3367

This will work for table names as well, and is also a good practice if your field name is a reserved word or similar, such as [Order] or [Month]

A better practice is to avoid those entirely...

I understand the need for creating columns with spaces in them, especially for reports that users will interact with, it's not very user-friendly to have a column heading labeled as 'Client_Response_Status_Code'.

Certainly the previous answers were all technically correct, however I would suggest rather than create columns with spaces in their names, create views and change the column names there instead...

For Example:

create view TC_Sessions_Report as
select response_status_code AS [Response State Code], 
       client_response_status_code as [Client Response Status Code]

...

This way you don't have to deal with those "friendly" column names everywhere in your code, but where you do need to use the friendly column names you can use the view instead...

Generally in sql you dont do it. you do response_status_code , if you have to use spaces i would try escaping them with \\ or using [Response Status Code] or something

You can have columns with spaces, but it is usually avoided. You need to wrap your column in brackets to select it:

select [Response Status Code], [Client Response Status Code]  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM