d-_-b
d-_-b

Reputation: 23151

If value contains these letters, then

In SQL Server, is there a way to search (and format) a result for a certain string (like preg_match in PHP):

SELECT (IF (col1 contains 'http'){'<a>' + col 1 + '</a>'}
else {'<b>' + col1 + '</b>'}),
col2
FROM Table

... etc.

Is this possible? I want to format the results based on their content.

Upvotes: 7

Views: 57416

Answers (3)

Prashant Marathay
Prashant Marathay

Reputation: 313

I use something like the following:

IF (my_column_name LIKE "%MATCHSTRING%", 1, 0) AS new_column_name,

Leave off the % if you are doing a exact match as opposed to a contains

Upvotes: 0

Tom Chantler
Tom Chantler

Reputation: 14931

Try this:

SELECT CASE WHEN col1 LIKE '%http%' THEN '<a>' + col1 + '</a>' ELSE '<b>' + col1 + '</b>' END AS 'Desired Column Name', col2
FROM table

See the MSDN Documentation here: http://msdn.microsoft.com/en-us/library/ms181765.aspx

Upvotes: 20

daz-fuller
daz-fuller

Reputation: 1231

You could try something like this (from the AdventureWorks database)

SELECT  Title,
        FirstName,
        LastName,
        CASE 
            WHEN LastName LIKE 'G%' THEN '<a href="mailto:' + EmailAddress + '">' + LastName + '</a>'
            ELSE '<b>' + LastName + '</b>'
        END
FROM    SalesLT.Customer

Upvotes: 2

Related Questions