Table of Contents

    How to Use the REPLICATE() Function in SQL Server: A Complete Guide

    How to Use the REPLICATE() Function in SQL Server: A Complete Guide

    Syntax:

    
    REPLICATE(String_To_Be_Replicated, Number_Of_Times_To_Replicate) 
    

    Repeats the given string, for the specified number of times.

    Code:

    
     SELECT REPLICATE('Rambo', 3)
    
    

    Output:

    The above code will produce the following result-

    
     Rambo Rambo Rambo
    

    A practical example of using REPLICATE() function: We will be using this table, for the rest of our examples in this article.

    Replicate function example

    Code:

    
    Select FirstName, LastName, SUBSTRING(Email, 1, 2) + REPLICATE('*',5) + 
    SUBSTRING(Email, CHARINDEX('@',Email), LEN(Email) - CHARINDEX('@',Email)+1) as Email
    from TableEmployee
    

    Prerequisite Code:

    
    CREATE TABLE TableEmployee(
    	FirstName varchar(50),
    	LastName varchar(50),
    	Email varchar(50)
    )
    
    INSERT INTO TableEmployee VALUES('Rambo', 'Azmi', 'Rambo@aaa.com')
    INSERT INTO TableEmployee VALUES('Azam', 'Ali', 'Azam@aaa.com')
    INSERT INTO TableEmployee VALUES('Inza', 'Hoque', 'Rambo@aaa.com')
    INSERT INTO TableEmployee VALUES('Jaman', 'Sk', 'Jaman@aaa.com')
    INSERT INTO TableEmployee VALUES('Samser', 'Alam', 'Samser@aaa.com')
    
    SELECT * FROM TableEmployee