DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE
SITE SEARCH SQLUSA.com HEADLINES NEWS
SQL E/BOOKS   SQL 2014 PROGRAMMING   DOWNLOADS
SCRIPTS SQL 2005 SQL 2008 ARTICLES
SQL JOBS TWITTER FORMAT VIDEOS
How to find the nth occurrence of a substring?

Execute the following SQL Server T-SQL example scripts in Management Studio Query Editor to create and test a user-defined function for searching.

-- SQL Server user-defined function - UDF

-- SQL search character repeat occurrence in a string

USE AdventureWorks;

GO

CREATE FUNCTION fnNthIndex

               (@Input     VARCHAR(8000),

                @Delimiter CHAR(1),

                @Ordinal   INT)

RETURNS INT

AS

  BEGIN

    DECLARE  @Pointer INT,

             @Last    INT,

             @Count   INT

    SET @Pointer = 1

    SET @Last = 0

    SET @Count = 1

    WHILE (2 > 1)

      BEGIN

        SET @Pointer = CHARINDEX(@Delimiter,@Input,@Pointer)

        IF @Pointer = 0

          BREAK

        IF @Count = @Ordinal

          BEGIN

            SET @Last = @Pointer

            BREAK

          END

        SET @Count = @Count + 1

        SET @Pointer = @Pointer + 1

      END

    RETURN @Last

  END

GO

 

-- Test user-defined scalar function

SELECT dbo.fnNthIndex('123-45-6789','-',2)

GO

-- 7

 

SELECT dbo.fnNthIndex('The Mississippi River','s',4)

GO

-- 11

Exam Prep 70-461
Exam 70-461
DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE