Find out anagram using SQL

Any word or phrase that exactly reproduces the letters in another order is an anagram. For example: “Hamlet” is an anagram of the word “Amleth”. We will show u a query today which can determine if two given words are anagram or not. We have used a Tally table for parsing the given strings. It has only one column called ‘N’ and the values of this column are like 1,2,3,4…….100

DROP TABLE #a
DROP TABLE #b

DECLARE @str1 VARCHAR(30)
DECLARE @str2 VARCHAR(30)

SET @str1 = ‘ramy’
SET @str2 = ‘mary’

SELECT N, SUBSTRING(@str1,N,1)letters
INTO #a
FROM dbo.Tally  WHERE N <= LEN(@str1)
ORDER BY N

SELECT N, SUBSTRING(@str2,N,1)letters
INTO #b
FROM dbo.Tally  WHERE N <= LEN(@str2)
ORDER BY N

IF EXISTS(
SELECT A.*,B.* FROM
(
SELECT letters,COUNT(*)C FROM #a GROUP BY letters
)A
FULL OUTER JOIN
(
SELECT letters,COUNT(*)C FROM #b GROUP BY letters
)B
ON A.letters = B.letters AND A.C = B.C
WHERE A.letters IS NULL OR B.letters IS NULL
)
PRINT ‘NOT ANAGRAM’
ELSE
PRINT ‘ANAGRAM’

Advertisements

About Zahid

Team Lead at IMS Health (www.imshealth.com). A part-time consultant and trainer. Fields of expertise are ETL, BI Reporting (Microstrategy, Excel, ASP.NET Dashboards etc.) Data Warehouse, OLAP Cube, MDX etc.
This entry was posted in SQL, Database and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s