How to strip specific characters from text using SQL queries

I’m working on a SQL problem where I need to clean up some text data. I have strings that contain letters, hyphens, and uppercase characters, but I only want to keep the lowercase letters that come before the hyphen.

Examples of what I’m trying to achieve:

  • Input: abc-X → Expected: abc
  • Input: hello-Z → Expected: hello

I’ve been experimenting with a loop-based approach using variables, but I’m wondering if there’s a simpler way to do this with just a single query.

DECLARE @text NVARCHAR(100);
DECLARE @index INT;

SET @text = 'abc-X';
SET @index = 1;

WHILE @index <= 26
BEGIN
    SET @text = REPLACE(@text, CHAR(64 + @index), '');
    SET @index = @index + 1;
END;

SELECT @text AS CleanedText;

Is there a more direct approach to handle this kind of text cleaning in SQL without using loops?

Using SUBSTRING and CHARINDEX offers a more efficient solution for your situation. You can grab the text before the hyphen with SUBSTRING(@text, 1, CHARINDEX('-', @text) - 1), which eliminates the need for loops. This approach has served me well especially with product codes and other similar data. Additionally, it performs better on larger datasets since string manipulation functions are generally faster than iterative processes. If there’s a chance that some records don’t contain hyphens, consider incorporating a CASE statement.

Interesting problem! What if you’ve got multiple hyphens though? Like test-abc-Z? Do you want just the part before the first hyphen, or does your data always have that single hyphen pattern?

if u wanna go simpler, use REGEXP_REPLACE if ur SQL version supports it. It can cleanly strip away what u don’t need, or simply grab the text before the hyphen directly. Good luck!