SQL Server REPLICATE() Function

The REPLICATE() function is used to repeat a string a certain number of times to generate a new string.

Syntax

REPLICATE(string_expression, integer_expression)

Use Cases

In some scenarios, we need to replicate a string multiple times, for example:

  • Generate a specific length of whitespace string.
  • Generate multiple identical strings for joining query results.
  • Repeat a word or phrase multiple times for testing or placeholders.

Examples

Here are two examples that demonstrate how to use the REPLICATE() function:

Example 1

Repeat a word multiple times to generate a new string. In this example, the REPLICATE() function is used to repeat the word hello three times:

SELECT REPLICATE('hello', 3) AS repeated_word;

Executing the above statement will generate the following result:

repeated_word
hellohellohello

Example 2

Generate a string consisting of whitespace with a length of 10. In this example, the REPLICATE() function is used to repeat the character A ten times:

SELECT REPLICATE('A', 10) AS blank_string;

Executing the above statement will generate the following result:

blank_string
AAAAAAAAAA

Conclusion

The REPLICATE() function is used to repeat a string multiple times to generate a new string. Its syntax is simple, and the parameters include the string to be repeated and the number of repetitions. In some cases, using the REPLICATE() function can help us process and analyze data more conveniently.