Split the sentence into words in sql server


This stored procedure gets the input as sentence through the parameter and print the results as words one by one. Here the space is the delimeter to split the sentence into words.

You need to compile this stored procedure in your sql server any database.

CREATE PROCEDURE Proc_SplitWords
@Sentence VARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON
    SET XACT_ABORT ON

DECLARE @Words VARCHAR(MAX)
DECLARE @tmpWord VARCHAR(MAX)
DECLARE @t VARCHAR(MAX)
    DECLARE @I INT

    SET @Words = @Sentence    
    SELECT @I = 0

    WHILE(@I < LEN(@Words)+1)
    BEGIN
      SELECT @t = SUBSTRING(@words,@I,1)

      IF(@t != ' ')
      BEGIN
SET @tmpWord = @tmpWord + @t
      END
      ELSE
      BEGIN
PRINT @tmpWord
        SET @tmpWord=''
      END
SET @I = @I + 1
        SET @t = ''
    END
   PRINT @tmpWord
END


Execute this stored procedure in the query window as mentioned below.

EXEC Proc_SplitWords 'This is sample stored procedure for split the words in sql server'

Once you have executed the above stored procedure then you will get the output like the following.

SqlServerSplitwords.jpg