SQL 'while' to read a table data to a variable

霸气de小男生 提交于 2019-12-11 20:32:43

问题


How could I write a while loop to populate data from a table to a variable to be used in a seperate query ? EX: select ITEM from Table1

ITEM
A0001
B0001
C0003
D0005
E0032

If I can get all that results here under column ITEM to @var1 and then use it in a seperate query like:

select * 
from Table2 
where @var1 = Item_table2  <-- a random column in table2

This query should match @var1 from A0001 to E0032 to the Item_table2 column in Table2.


回答1:


You don't need a loop.

select * from Table2 where Item_table2 in (select ITEM from Table1)



回答2:


If you really want cycle/loop, then use this one:

DECLARE @var1 varchar(100)

DECLARE ITEM_CURSOR CURSOR FOR
SELECT ITEM FROM Table1

OPEN ITEM_CURSOR
FETCH NEXT FROM ITEM_CURSOR INTO @var1

WHILE @@FETCH_STATUS = 0
BEGIN

/*Your separate query*/
SELECT * FROM Table2 where @var1 = Item_table2

FETCH NEXT FROM CURSOR_SMS INTO @var1

END
CLOSE ITEM_CURSOR;
DEALLOCATE ITEM_CURSOR;



回答3:


So here is your first table:

mysql> select * from item_table1;
+-------+
| item  |
+-------+
| A0001 |
| B0001 |
| C0003 |
| D0005 |
| E0032 |
+-------+
5 rows in set (0.01 sec)

Now, we need to create a view based on this table. The view is the equivalent concept you call in your question by @var1:

mysql> create view item_table2 as (select * from item_table1);
Query OK, 0 rows affected (0.30 sec)

Let's check our view item_table2 (@var1 in your own words):

mysql> select * from item_table2;
+-------+
| item  |
+-------+
| A0001 |
| B0001 |
| C0003 |
| D0005 |
| E0032 |
+-------+
5 rows in set (0.00 sec)

Now, you can select any item from item_table2 that exists in your item_table1 like this:

 select it2.item from item_table2 it2 where it2.item='A0001'


来源:https://stackoverflow.com/questions/27058848/sql-while-to-read-a-table-data-to-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!