[英]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.