I have two tables with 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
I'm writing a stored procedure that returns any column for each table.
Example Output for values above
--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
My idea is this
Select c.*
from Ccolumns c
inner join Sys_tables t
on t.Table_ID = c.Table_ID and t.Table_ID = @Parameter
My problem, i do't know how to make a loop for each row. I need the best way. Example i can use following loop:
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
But this is not entirely correct. Example my Sys_tables such data may be
Table_ID Name
1 Request
102 Plan
1001 Contecst
Do You have any idea?
There are couple ways you can achieve that: loops and cursors, but first of all you need to know that it's a bad idea: either are very slow, anyway, here's some kind of loop sample:
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
I guess you're using SQL Server, right?
Then, you can use a CURSOR
as here: How to write a cursor inside a stored procedure in SQL Server 2008
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.