繁体   English   中英

每行循环

[英]Loop for each row

我有两个带有FOREIGN KEY([Table_ID])

Columns

ID       Table_ID       ActiveFlag
1        1              0
2        2              1
3        1              1
4        3              0

Sys_Tables

Table_ID       Name
1              Request
2              Plan
3              Contecst

我正在编写一个存储过程,该过程将为每个表返回任何列。

上面的值的示例输出

--first output table
ID       Table_ID       ActiveFlag
1        1              0
3        1              1
--second output table
ID       Table_ID       ActiveFlag
2        2              1
--third output table
ID       Table_ID       ActiveFlag
4        3              0

我的主意是这样

Select c.*             
from Ccolumns c
     inner join Sys_tables t
    on t.Table_ID = c.Table_ID and t.Table_ID = @Parameter

我的问题是,我不知道如何为每一行循环。 我需要最好的方法。 示例我可以使用以下循环:

DECLARE @i int = 0
DECLARE @count int;
select @count = count(t.Table_ID)
from Sys_tables t
     WHILE @i < @count BEGIN
    SET @i = @i + 1
--DO ABOVE SELECT   
END

但这并不完全正确。 例如我的Sys_tables这样的数据可能是

Table_ID       Name
1              Request
102            Plan
1001           Contecst

你有什么主意吗?

有几种方法可以实现:循环和游标,但首先您需要知道这是一个坏主意:反正两者都很慢,这是某种循环示例:

declare @row_ids table (
    id INT IDENTITY (1, 1),
    rid INT
); 
insert into @row_ids (rid) select someIdField from SomeTable

declare @cnt INT = @@ROWCOUNT
declare @currentRow INT = 1

WHILE (@currentRow <= @cnt)
BEGIN
    SELECT rid FROM @row_ids WHERE id = @currentRow
    SET @currentRow = @currentRow + 1
END

我猜您正在使用SQL Server,对吗?

然后,您可以在此处使用CURSOR如何在SQL Server 2008中的存储过程中写入游标

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM