Solved

How can I trim certain characters in SQL?

Posted on 2011-09-26
4
269 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 92

Accepted Solution

by:
Patrick Matthews earned 500 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

[Webinar] Disaster Recovery and Cloud Management

Learn from Unigma and CloudBerry industry veterans which providers are best for certain use cases and how to lower cloud costs, how to grow your Managed Services practice in IaaS clouds, and how to utilize public cloud for Disaster Recovery

Question has a verified solution.

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

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

920 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now