views:

40

answers:

4

how can I use loop 'for' through a table in SQL to check if a column is 0?

I need to do like this in a stored procedure:

for  each record in  tablex
     if table.column1=0 then
         insert into table1;
     Else
         insert into table2;
 End for;
A: 

What you need is called cursor.

Sample for mysql:

DECLARE tmp INT;
DECLARE cur1 CURSOR FOR SELECT column1 FROM `table`;
OPEN cur1;

read_loop: LOOP
    FETCH cur1 INTO tmp;

    -- perform your IF here
END LOOP;

CLOSE cur1;

More details: http://dev.mysql.com/doc/refman/5.1/en/cursors.html

The sample for SQL Server is quite the same.

SQL Server details: http://msdn.microsoft.com/en-us/library/ms180169.aspx

zerkms
does cursors affect performance?
user1111111
Affect performance in comparison to what? If you need cursors - you use them, if you don't need - you don't. It is just a tool. Your question sounds like "Do SELECTs affect performance?".
zerkms
user1111111
Cursors are generally considerably slower than set based operations (like the INSERT solution a number of people have suggested).
Larry Lustig
+2  A: 

It's not clear what language you'll be writing in (MySQL or SQLServer), but the normal way to do this is using DECLARE CURSOR, FETCH, and WHILE.

However, if the task is as simple as you state in your problem, a better, faster, and more SQL-ish solution is probably:

INSERT INTO Table1 (ColList) 
     SELECT ColList 
       FROM SourceTable 
      WHERE Column1 = 0;

INSERT INTO Table2 (ColList) 
     SELECT ColList 
       FROM SourceTable 
      WHERE (Column1 <> 0 OR Column1 IS NULL);
Larry Lustig
I knew about cursors, I am wondering about any other way, I am intersted in any (MYSQL/ SQL SErver)
user1111111
+1  A: 

You may be able to do the same thing without a cursor:

INSERT INTO table1 (colA, colB) 
     SELECT valX, valy, 'const' 
       FROM Table 
      WHERE column1 = 0;

then repeat for table 2.

Nathan Feger
+1  A: 

Is there a reason you need to use a loop? Could you not just do

insert into table1
select * from tablex 
where tablex.column1 = 0

insert into table2
select * from tablex 
where tablex.column1 != 0
david