SQL REPEAT function
Concatenates a string with itself a given number of times.
- 類別
- Strings
- Returns
string- In this category
- 117 of 172
語法
REPEAT(str, count)
SQL Server: REPLICATE(str, count)
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | Different name or syntax | Spelled REPLICATE(str, count). |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | 是 | Supported under this name. |
| SQLite | Not built in | No REPEAT; replace(hex(zeroblob(n)), '00', str) repeats str n times. |
| Oracle | Not built in | No REPEAT; RPAD(str, LENGTH(str) * n, str). |
範例
PostgreSQL
SELECT REPEAT('ab', 3) AS result; -- ababab
SQL Server
SELECT REPLICATE('-', 40) AS divider;
SQLite
SELECT replace(hex(zeroblob(3)), '00', 'ab') AS result; -- ababab
小知識
- A count of 0 returns ''. Negative counts differ: PostgreSQL and MySQL return '', SQL Server's REPLICATE returns NULL.
- REPLICATE truncates at 8,000 bytes unless the input is varchar(max) or nvarchar(max): LEN(REPLICATE('a', 10000)) is 8000, while REPLICATE(CAST('a' AS varchar(max)), 10000) has all 10,000.
- MySQL returns NULL, with a warning, when the result would exceed max_allowed_packet.
Questions about REPEAT
Is REPEAT the same as REPLICATE?
Yes, apart from negative counts: MySQL and PostgreSQL say REPEAT, SQL Server says REPLICATE. SQLite and Oracle have neither.
How do I repeat a string in Oracle?
RPAD(str, LENGTH(str) * n, str) repeats the pattern n times; RPAD('=', n, '=') gives exactly n characters.
Why did my REPLICATE result stop at 8,000 characters?
The input was a non-max varchar, so the result was capped at 8,000 bytes (4,000 nvarchar characters). Cast the input to varchar(max) or nvarchar(max).
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Walk a bill of materials Snippet
- Mask payment card numbers in SQL (show last 4) Snippet
- Mask names in query results Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.