Skip to content

Instantly share code, notes, and snippets.

@FromMeloriWithLove
Created October 19, 2023 23:57
Show Gist options
  • Save FromMeloriWithLove/1abda726b3e307fea6446db9b61aa465 to your computer and use it in GitHub Desktop.
Save FromMeloriWithLove/1abda726b3e307fea6446db9b61aa465 to your computer and use it in GitHub Desktop.
DECLARE @string NVARCHAR(1000)
DECLARE @word NVARCHAR(50)
DECLARE @space INT
DECLARE @words TABLE (
word NVARCHAR(50),
amount INT
)
DECLARE cur CURSOR FOR SELECT mess FROM messages
OPEN cur
FETCH NEXT FROM cur INTO @string
WHILE @@FETCH_STATUS = 0
BEGIN
SET @string = LOWER(@string)
SET @string = @string + ' '
SET @string = TRANSLATE(@string, '!?.=)(*,-:1234567890', ' ') ;
WHILE CHARINDEX(' ', @string) > 0
BEGIN
SET @string = REPLACE(@string, ' ', ' ')
END
SET @space = CHARINDEX(' ', @string)
WHILE @space > 0
BEGIN
SET @word = SUBSTRING(@string, 1, @space - 1)
SET @string = SUBSTRING(@string, @space + 1, LEN(@string) - @space + 1)
IF EXISTS (SELECT * FROM @words WHERE word = @word)
BEGIN
UPDATE @words
SET amount = amount + 1
WHERE word = @word
END
ELSE
BEGIN
INSERT INTO @words VALUES (@word, 1)
END
SET @space = CHARINDEX(' ', @string)
END
FETCH NEXT FROM cur INTO @string
END
CLOSE cur
DEALLOCATE cur
SELECT TOP 50 word, amount
FROM @words
ORDER BY amount DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment