admin posted on October 8, 2009 22:19

Someone searched the site for this…let’s take a look



A reader was looking the other day to find how they might find a percent character (percent sign, or %) within a string using the LIKE operator.  Check the code below.

 

USE tempdb
CREATE TABLE Terms 
        (TermID int IDENTITY NOT NULL PRIMARY KEY
        ,CreditTerm varchar (25)
        );
GO
INSERT INTO Terms (CreditTerm) VALUES ('2/10, n/30');
INSERT INTO Terms (CreditTerm) VALUES ('3/10, n/30');
INSERT INTO Terms (CreditTerm) VALUES ('2%');
INSERT INTO Terms (CreditTerm) VALUES ('20%');
INSERT INTO Terms (CreditTerm) VALUES ('200%');

GO

--1. Plain Jane LIKE statement, level –100

SELECT *
FROM Terms
WHERE CreditTerm LIKE '20%'

--2. Find a '%' using LIKE in the string.
SELECT *
FROM Terms
WHERE CreditTerm LIKE '2[%]'


--3. Find all 2% discounts
SELECT *
FROM Terms
WHERE CreditTerm LIKE '2[%-/]%'

--How do we know which is first (in order)?
--Use ASCII to see which is the lesser value
--We know to put % before /

SELECT ASCII('%'), ASCII('/')
            
----------- -----------
37          47

(1 row(s) affected)

The first is an elementary SQL statement using LIKE.  No problems with this one I hope.  Next, the one that the reader was looking for;  here we use square brackets to signal that the percent sign is a literal, so it pops out for us. Good stuff.  Number three is slightly more interesting because if someone wants to get all of the 2% discounts (and not 20% or 200%), which includes 2%, and the accounting credit term 2/10, n30 (or 2% discount in 10 days, payable by 30 days from invoice date), we use this one. Brackets with values separated by a dash tell the LIKE to search from the first to the second.  One issue on this one – you have to know which to put first.  It’s easy if it’s letters ([a-d]), but in order to find the values of ours, use ASCII keyword to return the character set value. Obviously 37 comes before 47, so we have the order correct. If we tried to put the forward slash (/) first, we’d get nothing in our result set.

Lee

 

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

 

Like ask me if I care ok?

witching

 


Posted in: TSQL  Tags:
blog comments powered by Disqus

by Lee Everest, M.S.

Poll

Do you use Azure or cloud in your organization?



Show Results

Ads

Search


Month List

Calendar

«  February 2012  »
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011
View posts in large calendar

Tags

Disclaimer
The opinions, code, examples, et.al. expressed herein are my own personal opinions and do not represent my employer's view in any way, shape form, or fashion.  All code for demonstration purposes - no guarantees, either written or implied, are made.

© Copyright 2012 Lee Everest's SQL Server, etc. weblog