Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select data up to a space?

I have an MSSQL database field that looks like the examples below:

u129  james
u300  chris
u300a jim
u202  jane
u5    brian
u5z   brian2

Is there a way to select the first set of characters? Basically select all the characters up until the first line space?

I tried messing around with LEFT, RIGHT, LEN, but couldn't figure out a way to do it with variable string lengths like in my example.

Thanks!

like image 332
SkyeBoniwell Avatar asked Nov 20 '12 19:11

SkyeBoniwell


People also ask

How do I add a space to a selected query?

In SQL Server, you can use the T-SQL SPACE() function to generate a specific number of spaces. This can be handy for adding spaces within a string, for example, when concatenating two or more strings.

How do I extract text before a space in SQL?

You can use a combiation of LEFT and CHARINDEX to find the index of the first space, and then grab everything to the left of that.

How do I select columns with spaces in SQL?

To select a column name with spaces, use the back tick symbol with column name. The symbol is ( ` `). Back tick is displayed in the keyboard below the tilde operator ( ~).


3 Answers

You can use a combiation of LEFT and CHARINDEX to find the index of the first space, and then grab everything to the left of that.

 SELECT LEFT(YourColumn, charindex(' ', YourColumn) - 1) 

And in case any of your columns don't have a space in them:

SELECT LEFT(YourColumn, CASE WHEN charindex(' ', YourColumn) = 0 THEN 
    LEN(YourColumn) ELSE charindex(' ', YourColumn) - 1 END)
like image 178
LittleBobbyTables - Au Revoir Avatar answered Oct 11 '22 20:10

LittleBobbyTables - Au Revoir


select left(col, charindex(' ', col) - 1)
like image 29
Blorgbeard Avatar answered Oct 11 '22 19:10

Blorgbeard


If the first column is always the same size (including the spaces), then you can just take those characters (via LEFT) and clean up the spaces (with RTRIM):

SELECT RTRIM(LEFT(YourColumn, YourColumnSize))

Alternatively, you can extract the second (or third, etc.) column (using SUBSTRING):

SELECT RTRIM(SUBSTRING(YourColumn, PreviousColumnSizes, YourColumnSize))

One benefit of this approach (especially if YourColumn is the result of a computation) is that YourColumn is only specified once.

like image 2
camerondm9 Avatar answered Oct 11 '22 19:10

camerondm9