extracting column values when a part of the column value is known

  • hi

    How can we extract a column values from database if we know a part of that column value.

    For ex: if I have values for a column called statements like this:

    (I am good Gal)

    (you are a good boy) and so on..

    and I want to extract all the statements that have a part called 'good'

    what is the best way to query this?

  • Quick thought, use the LIKE operator

    😎

    USE tempdb;

    GO

    DECLARE @test-2 TABLE

    (

    TEST_ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED

    ,TEST_STRING VARCHAR(50) NOT NULL

    );

    INSERT INTO @test-2(TEST_STRING)

    VALUES

    ('I am a bad Gal')

    ,('I am a good Gal')

    ,('This is an old horse')

    ,('This is a good horse')

    ,('I am a good boy')

    ,('I am a naugthy boy');

    SELECT

    *

    FROM @test-2 T

    WHERE T.TEST_STRING LIKE '%good%';

    Results

    TEST_ID TEST_STRING

    ----------- ---------------------

    2 I am a good Gal

    4 This is a good horse

    5 I am a good boy

  • What to do if we want to replace the word 'good' with 'bad' in all those sentences?

    I wrote it like this:

    REPLACE(columnname,'good','bad')

    Is there any other way to do this?

  • Using the REPLACE function is the simplest way to do it. Assuming there aren't any unusual requirements, that's exactly the way I'd do it.

  • Thank you all for the help 🙂

  • Note that you might replace strings you don't want them to be replaced.

    INSERT INTO @test-2(TEST_STRING)

    VALUES

    ('I am a bad Gal')

    ,('I am a good Gal')

    ,('Oh my goodness! There''s no more goodwill')

    ,('He''s a patient with Osgood–Schlatter disease');

    SELECT

    *, REPLACE(TEST_STRING, 'good', 'bad')

    FROM @test-2 T

    WHERE T.TEST_STRING LIKE '%good%';

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • Luis Cazares (8/22/2014)


    Note that you might replace strings you don't want them to be replaced.

    INSERT INTO @test-2(TEST_STRING)

    VALUES

    ('I am a bad Gal')

    ,('I am a good Gal')

    ,('Oh my goodness! There''s no more goodwill')

    ,('He''s a patient with Osgood–Schlatter disease');

    SELECT

    *, REPLACE(TEST_STRING, 'good', 'bad')

    FROM @test-2 T

    WHERE T.TEST_STRING LIKE '%good%';

    DECLARE @STR VARCHAR(50) = 'That an absolute @£$%'

    SELECT REPLACE(REPLACE(REPLACE(REPLACE(@STR,'e @','ly'),'£',' a '),'$','brilliant'),'%',' point!')

    😎

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply