3

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

That works for me, See updated answer for complete sample solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.