Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT TABLE REPEAT TABLE LOOP MSSQL

First off I am loving Stack Overflow, you are all so helpful..

I have a situation, I have a Table with data like this;

1 - Apple
2 - Bananna
3 - Pear
4 - Orange
5 - Plum

I could do something like this;

DECLARE @C INT = 0
WHILE (@C < 3) 
    BEGIN
        INSERT INTO tbl1 (ID,Name)
        SELECT * FROM tbl2 -- THIS WILL CONTAIN 5 Rows
        SET @C+=1
    END

So it would end up like this;

1 - Apple
2 - Bananna
3 - Pear
4 - Orange
5 - Plum
1 - Apple
2 - Bananna
3 - Pear
4 - Orange
5 - Plum
1 - Apple
2 - Bananna
3 - Pear
4 - Orange
5 - Plum

Now I could go ahead and put a while loop 3 times and be done, however this select script is to be repeated 400,000 times so using insert->select->insert->select, etc would cause massive overload. What I want to do is something like this;

INSERT INTO tbl1
SELECT 
   ID,
   Name,
   @C = COUNT(ID) 
FROM tbl2 
WHERE @C < 3

I don't know if this is even possible, however the other method is using COMMIT but I don't know how to use that effectively.

like image 204
Kiel Avatar asked Feb 03 '26 06:02

Kiel


1 Answers

Have you tried using GO to execute the INSERT statement as a batch

IF OBJECT_ID(N'dbo.T1', N'U') IS NULL
CREATE TABLE dbo.T1
    ([Id] int, [name] varchar(7)) ;

IF OBJECT_ID(N'dbo.T2', N'U') IS NULL
CREATE TABLE dbo.T2
    ([Id] int, [name] varchar(7)) ;

INSERT INTO T1
    ([Id], [Name])
VALUES
    (1, 'Apple'),
    (2, 'Bananna'),
    (3, 'Pear'),
    (4, 'Orange'),
    (5, 'Plum')
;

INSERT INTO dbo.T2
(Id,[name])
SELECT T.Id
        ,T.[name] 
FROM dbo.T1 T 
GO 100

DROP TABLE dbo.T1
DROP TABLE dbo.T2
like image 124
Mazhar Avatar answered Feb 06 '26 19:02

Mazhar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!