Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double loop with drop table in MSSQL

I've while loop inside while loop and both loops do some modifications of one table. I receive an error that table already exists. Below simple example of this problem. Could someone clarify why this doesn't work? I know how to bypass this problem in this particular case, nevertheless I'd like to understand where did it come from.

CREATE TABLE #a(
  ID int)

DECLARE @i INT
DECLARE @j INT  

SET @i = 1
SET @j = 1

WHILE @i < 10
BEGIN

    SELECT  *
    INTO #b
    FROM  #a

    DROP TABLE #b

    WHILE @j < 10 BEGIN
        SELECT  *
        INTO #b
        FROM  #a

        DROP TABLE #b

        SET @j = @j + 1
    END

  SET @i = @i + 1
END
like image 343
Tomek Tarczynski Avatar asked Mar 22 '26 16:03

Tomek Tarczynski


1 Answers

As Sean Lange pointed out, you can probably do whatever your doing without loops.

You cannot have two statements in the same procedure that create a temp table with the same name. This is a leftover from SQL 6.5 which did not have deferred name resolution.

Instead of using select into, use create table + insert.

Instead of dropping and recreating the same table with the same schema, use truncate table.

Answer by Erland Sommarskog on MSDN Social

create table #a(ID int);
create table #b(ID int);
declare @i int;
declare @j int;
set @i = 1;
set @j = 1;
while @i < 10
  begin;
    insert into #b (id)
      select id
      from #a;

    truncate table #b;

    while @j < 10
      begin;
        insert into #b (id)
          select id
          from #a

        truncate table #b;

        set @j = @j + 1;
      end;
    set @i = @i + 1;
  end;
like image 124
SqlZim Avatar answered Mar 24 '26 12:03

SqlZim



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!