|
|
|
A sample script to count the number of occurrences of a particular string pattern in a text column. This demonstrates how to use PATINDEX with simple SELECT statements. |
Click here to copy the following block | CREATE TABLE #StrTbl ( StrID int IDENTITY (1,1) NOT NULL, Col text NULL );
INSERT INTO #StrTbl (Col) VALUES ('Blah Blah Blah <P1><L1> blah blah blah <P2><L2> blah blah blah <P3><L1> blah blah blah');
INSERT INTO #StrTbl (Col) VALUES ('Blah Blah Blah <P2><L1> blah blah blah <P1><L1> blah blah blah <P4><L2> blah blah blah');
INSERT INTO #StrTbl (Col) VALUES ('Blah Blah Blah <P1><L1> blah blah blah <P1><L2> blah blah blah <P3><L2> blah blah blah');
SELECT * FROM #StrTbl;
GO
SELECT StrID , Seq AS P , SUM( L1 + L2 ) AS LCount FROM ( SELECT StrID , Seq, CASE WHEN PATINDEX( L1 , Col ) > 0 THEN 1 ELSE 0 END AS L1 , CASE WHEN PATINDEX( L2 , Col ) > 0 THEN 1 ELSE 0 END AS L2 FROM #StrTbl JOIN (
SELECT 1 AS Seq , '%<P1>%' AS PToken , '%<P1><L1>%' AS L1 , '%<P1><L2>%' AS L2 UNION ALL SELECT 2, '%<P2>%' , '%<P2><L1>%' , '%<P2><L2>%' UNION ALL SELECT 3, '%<P3>%' , '%<P3><L1>%' , '%<P3><L2>%' UNION ALL SELECT 4, '%<P4>%' , '%<P4><L1>%' , '%<P4><L2>%' ) AS t
ON PATINDEX( pToken , Col ) > 0 ) AS t2 GROUP BY StrID , Seq ORDER BY StrID , Seq;
|
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|