Caffeinated
Caffeinated

Reputation: 12484

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!

Upvotes: 27

Views: 96777

Answers (5)

Don L
Don L

Reputation: 61

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

Upvotes: 6

Limey
Limey

Reputation: 2772

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]  

Upvotes: 1

Jamie F
Jamie F

Reputation: 23809

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

Upvotes: 5

Jimbo
Jimbo

Reputation: 2537

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

Upvotes: 46

Markus Mikkolainen
Markus Mikkolainen

Reputation: 3497

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

Upvotes: 1

Related Questions