The REPLICATE()
function in SQL Server is used to repeat a given string expression a specified number of times. It takes two arguments:
- Expression: The string you want to repeat.
- Number: The number of times the string should be repeated.
Syntax:
REPLICATE(string_expression, number)
string_expression
: The string value you want to repeat.number
: The number of times you want to repeat the string. If the number is less than or equal to 0, the result will be an empty string.
Example 1: Simple String Repetition
SELECT REPLICATE('A', 5) AS Result;
This will return:
Result
------
AAAAA
Example 2: Repeating a Word Multiple Times
SELECT REPLICATE('Hello ', 3) AS Result;
This will return:
Result
------------
Hello Hello Hello
Example 3: Handling Edge Cases
SELECT REPLICATE('X', 0) AS Result; -- Returns an empty string
SELECT REPLICATE('Y', -1) AS Result; -- Also returns an empty string
Use Case:
The REPLICATE()
function is often used for padding strings or generating patterns. For example, if you wanted to create a separator string of dashes for formatting:
SELECT REPLICATE('-', 20) AS DashLine;
This would return:
DashLine
--------------------
No comments:
Post a Comment