SQL Server Multiplying/duplicating/triplicating rows in SQL efficiently

iklwldmw  于 2023-08-02  发布在  其他
关注(0)|答案(1)|浏览(148)

I would like to know how to efficiently (computation-wise) duplicate/triplicate/quadruple rows in a given SQL table. I know I could build a small table containing just a series of INT (say, from 1 to 4 to quadruple the existing rows) and use CROSS JOIN to do the job as below (example can also be found here) --

  1. CREATE TABLE ForgeRock
  2. ([productName] varchar(13), [description] varchar(57))
  3. ;
  4. INSERT INTO ForgeRock
  5. ([productName], [description])
  6. VALUES
  7. ('OpenIDM', 'Platform for building enterprise provisioning solutions'),
  8. ('OpenAM', 'Full-featured access management'),
  9. ('OpenDJ', 'Robust LDAP server for Java')
  10. ;
  11. CREATE TABLE Multiplier (
  12. [Times] int
  13. );
  14. INSERT INTO Multiplier (Times)
  15. VALUES
  16. (1),
  17. (2),
  18. (3),
  19. (4)
  20. ;
  21. SELECT
  22. productName,
  23. description
  24. FROM
  25. ForgeRock
  26. CROSS JOIN
  27. Multiplier

but this is a bit round-about way in my opinion (because we have to build another table with integers in it) and I'm wondering if anyone has a more elegant and efficient approach (preferably using just simple SQL such as ISO 9075 compliant one).

Thank you in advance for your suggestions!

iovurdzv

iovurdzv1#

Your approach is the standard way to go. If you want to avoid creating a table of numbers, you can declare it within the query using a row-constructore syntax.

In SQL Server, you would use VALUES() :

  1. SELECT f.productName, f.description
  2. FROM ForgeRock f
  3. CROSS JOIN ( VALUES (1), (2), (3), (4) ) v(times)

An alternative is to use a recursive query to duplicate the rows - but this is likely to be less efficient, especially if a large number of rows need to be duplicated:

  1. with cte as (
  2. SELECT productName, description, 0 lvl, 4 max_lvl FROM ForgeRock
  3. UNION ALL
  4. SELECT productName, description, lvl + 1, max_lvl FROM cte WHERE lvl < max_lvl
  5. )
  6. SELECT productName, description FROM cte
展开查看全部

相关问题