Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How can I trim certain characters in SQL?

Posted on 2011-09-26
4
Medium Priority
?
275 Views
Last Modified: 2012-06-27
How can I trim certain characters in a query?

I have a column that had some records containing the value: 12345-123
I only want to select the characters before the dash.

So I want to trim the dash and all characters at the right of the dash.
(So it returns the value: 12345)

Best regards,
Clyde.
0
Comment
Question by:Clyde_Radcliffe
  • 2
4 Comments
 
LVL 6

Expert Comment

by:kswathi
ID: 36597606
0
 
LVL 6

Expert Comment

by:kswathi
ID: 36597616
0
 
LVL 3

Expert Comment

by:John_Arifin
ID: 36597972
Select Left(YourField, charindex('-', YourField) - 1) from YourTable
0
 
LVL 93

Accepted Solution

by:
Patrick Matthews earned 2000 total points
ID: 36599320
If the data will ALWAYS have a dash, then John_Arifin's suggestion will work splendidly.

If there is any possibility that there is no dash, would you want the whole string returned, or nothing?  If the former:

SELECT LEFT(SomeColumn, CHARINDEX('-', SomeColumn + '-') - 1) AS Answer
FROM SomeTable

Open in new window


If the latter, this excludes records where there is no dash:

SELECT LEFT(SomeColumn, CHARINDEX('-', SomeColumn) - 1) AS Answer
FROM SomeTable
WHERE SomeColumn LIKE '%-%'

Open in new window


and this returns a null:

SELECT CASE 
    WHEN SomeColumn LIKE '%-%' THEN LEFT(SomeColumn, CHARINDEX('-', SomeColumn) - 1)
    ELSE NULL END AS Answer
FROM SomeTable

Open in new window


and this returns a zero length string:

SELECT CASE 
    WHEN SomeColumn LIKE '%-%' THEN LEFT(SomeColumn, CHARINDEX('-', SomeColumn) - 1)
    ELSE '' END AS Answer
FROM SomeTable

Open in new window

0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

972 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question