Click here to Skip to main content
15,907,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Folks!!

I have a column 'EmployeeAddress'.I want to get the only employee 'House Number' from below address column.

employeeAddress
---------------------
245 1st main,Silkboard,Bangalore-560068------Here '245' is House Number
243 BTM,Bangalore-560068
653 Koramangala,Bangalore-560079
8 12th main,1st cross,Adugodi,Bangalore
1 electronic city,Bangalore------------------Here '1' is House number
5 electronic city,Bangalore------------------Here '5' is House number
8 electronic city,Bangalore------------------Here '8' is House number


Can anyone help me on this? Thanks in Advance..

What I have tried:

I tried like below .

SELECT LEFT(employeeAddress,charindex(' ',employeeAddress)-1) FROM Table

But i am getting below error

Msg 537, Level 16, State 2, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.
Posted
Updated 4-May-16 21:53pm
v2

First of all this is not the way to store data. If you need 'House Number' from your table you have to store it as 'House Number'. Still, if you are unable to do that you will have to rely on finding the substring from your address field. Now, the problem is we will get the first index of ' ' and find the substring. But what if the address has preceding spaces? You will have to trim the blank spaces from the left of your string. I would recommend you to google 'SUBSTRING' and 'LTRIM' functions for SQL Server before moving ahead. Then only try this query for your understanding:
SQL
DECLARE @address VARCHAR(50) = '   2508 Sample Address'
SELECT SUBSTRING(LTRIM(@address),1, CHARINDEX(' ', LTRIM(@address)))

Now, for your requirement, you should write:
SQL
SELECT SUBSTRING(LTRIM(employeeAddress),1, CHARINDEX(' ', LTRIM(employeeAddress))) AS [House Number] FROM [YourTableName]
 
Share this answer
 
v2
Comments
Member 11931581 5-May-16 7:17am    
Thank you Zafar..
Zafar Sultan 5-May-16 7:46am    
You're welcome.
Write simple query:

SELECT SUBSTRING(employeeAddress, 1, CHARINDEX(' ', employeeAddress, 1) - 1) FROM Table
 
Share this answer
 
v2
Comments
Zafar Sultan 5-May-16 3:57am    
This won't work if the address field has preceding blank spaces. For example '    2508 Sample Address'. See my solution below.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900