Published on

May 5, 2013

Understanding the REPLICATE Function in SQL Server

Have you ever encountered a situation where you needed to repeat a character or a string multiple times in SQL Server? The REPLICATE function comes to the rescue in such scenarios. In this article, we will explore how the REPLICATE function works and discuss some interesting aspects related to its usage.

Let’s start with a simple puzzle. Consider the following script:

DECLARE @FirstString VARCHAR(MAX)
DECLARE @SecondString VARCHAR(MAX)
DECLARE @ThirdString VARCHAR(MAX)

SET @FirstString = REPLICATE('A', 4000)
SELECT LEN(@FirstString) AS LenFirstString;

SET @SecondString = REPLICATE('B', 8000)
SELECT LEN(@SecondString) AS LenSecondString;

SET @ThirdString = REPLICATE('C', 11000)
SELECT LEN(@ThirdString) AS LenThirdString;

Running this script will produce the following result:

LenFirstString: 4000
LenSecondString: 8000
LenThirdString: 8000

Quiz 1: Pay attention to the last resultant and you will notice that the length of the @ThirdString is only 8000. Why is that?

Answer 1: The reason for this behavior is that if the first parameter of the REPLICATE function is not of type VARCHAR(MAX) or NVARCHAR(MAX), REPLICATE truncates the return value at 8,000 bytes. To return values greater than 8,000 bytes, the first parameter must be explicitly cast to the appropriate VARCHAR(MAX) or NVARCHAR(MAX).

Quiz 2: What changes should be made to the REPLICATE function to return the appropriate result in the case of @ThirdString? In our case, it should return the value of 11000 and not 8000.

Answer 2: To return the result as 11000, one simply needs to CAST or CONVERT the first parameter to VARCHAR(MAX) or NVARCHAR(MAX). Here is an example:

DECLARE @ThirdString VARCHAR(MAX)
SET @ThirdString = REPLICATE(CONVERT(VARCHAR(MAX), 'C'), 11000)
SELECT LEN(@ThirdString) AS LenThirdString;

Running this modified script will now produce the desired result:

LenThirdString: 11000

It’s important to note that the REPLICATE function is not limited to repeating single characters. You can also use it to repeat entire strings. For example:

DECLARE @RepeatedString VARCHAR(MAX)
SET @RepeatedString = REPLICATE('Hello ', 5)
SELECT @RepeatedString AS RepeatedString;

This script will generate the following output:

RepeatedString: Hello Hello Hello Hello Hello

As you can see, the REPLICATE function can be a handy tool when you need to generate repeated characters or strings in SQL Server.

That’s all for this article. I hope you found it informative and helpful. If you have any questions or comments, please feel free to leave them below.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.