How to Loop in SQL server?
The below example shows how to loop in microsoft SQL server and insert records in chunks: This makes inserts faster.
SET IDENTITY_INSERT dbo.table1 ON /* This is required if you are adding data to Identity columns */
DECLARE @cnt INT = 2006;
WHILE @cnt < 2016
select * from table1 where [Reporting_Period_SID]= @cnt
SET @cnt = @cnt + 1
SET IDENTITY_INSERT dbo.table1 OFF
Selecting top 3 (n) or Max 3 (n) records for each group by condition
Use the example to select top 3 records for each group. The row number is broken by the Sales_Reporting_Period and then is used to filter the top 3 records.
SELECT Company_code, Run_sid, Curr_ind, Sales_Reporting_Period from
,BB.Sales_Reporting_Period , ROW_NUMBER()
PARTITION BY Sales_Reporting_Period
order by Sales_Reporting_Period, BB.Run_Sid Desc
) AS RowNo
AF.Run_SID = BB.Run_SIDgroup by
,BB.Run_SID)Q1 where RowNo <=3