SQL Server Learning Series-Gets the number of occurrences of a character in a string and the subscript at which a character appears

Source: Internet
Author: User

DECLARE @Str NVARCHAR( -)= '1_bb_cc_dd_aa_ee_yy_ww_hh_gg'--//1. Gets the number of times an underscore appears in a stringSELECT LEN(@Str)- LEN(REPLACE(@Str,'_',"'))--//2. Get the subscript where the underline appearsIF  EXISTS(SELECT *  fromSys.objectsWHERE object_id = object_id(N'[dbo]. [Indexnumofstr]') andTypeinch(N'FN'N'IF'N'TF'N'FS'N'FT'))    DROP FUNCTION [dbo]. IndexnumofstrGOCREATE FUNCTIONdbo. Indexnumofstr (@Str     NVARCHAR( -),--string    @charStr NVARCHAR( -),--the character to query    @num     INT                    --The first few occurrences)RETURNS INT  asBEGIN    DECLARE @posIndex INT = 0        --the location that appears    DECLARE @i INT = 0                --Number of lookups     while @i < @num    BEGIN        SET @i = @i + 1        SET @posIndex = CHARINDEX(@charStr,@Str,@posIndex + 1)        IF @posIndex = 0        BEGIN            RETURN 0        END    END    RETURN @posIndexENDGO--//test ResultsSELECTDbo. INDEXNUMOFSTR (@Str,'_',Ten)

SQL Server Learning Series-Gets the number of occurrences of a character in a string and the subscript at which a character appears

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.