2013-02-08 98 views
1

我需要while語句的幫助,我從來沒有使用一個之前,想知道不得不repaeat序列,直到我打了一個目標:重複While語句

對於實例

1 
2 
3 
4 
1 
2 
3 
4 
Until 5000 

我曾嘗試我自己寫的,但已經成爲卡住:

USE Occupancy 
CREATE TABLE Bookings2 
(Booking_Skey INT IDENTITY (1,1) not null, 
PitchType_Skey INT not null) 

DECLARE @PitchType_Skey INT 
SET @PitchType_Skey = 1 
WHILE (@PitchType_Skey <= 4) 

BEGIN 
INSERT INTO Bookings2(PitchType_Skey) 
SELECT @PitchType_Skey 
SET @PitchType_Skey = @PitchType_Skey + 1 
END 
+0

你好,你的問題不給很多工作來幫助你,你能告訴我們你在雖然想要什麼。 – Rednaxel 2013-02-08 15:57:52

+0

我不完全確定你要在這裏完成什麼。例如,你是否試圖重複序列「1,2,3,4」5000次?對於這個問題,我不太清楚你的桌子是用來做什麼的。從本質上講,我可以告訴你如何使用WHILE循環,但是你使用WHILE循環和Bookings2表完全解決了什麼問題? – 2013-02-08 15:58:13

+0

您的代碼運行良好。問題是什麼? – 2013-02-08 15:58:54

回答

1

0123的同時,內更換您的選擇

%是模數或餘數,所以它可以讓你不得不用4

WHILE (@PitchType_Skey <= 5000) 
BEGIN 
    INSERT INTO Bookings2(PitchType_Skey) 
    SELECT (CASE WHEN @PitchType_Skey % 4 = 0 THEN 4 ELSE @PitchType_Skey % 4 END) 
    SET @PitchType_Skey = @PitchType_Skey + 1 
END 
+0

msmucker非常感謝你,這正是我所需要的。 – wafw1971 2013-02-08 16:11:43

1

實際上取代0悠唐的@PitchType_Skey/4(保證值小於4)

然後將殘餘「T需要一段時間,因爲你可以使用master..spt_values

WITH t1250 
    AS (SELECT TOP 1250 Row_number() 
          OVER( 
          ORDER BY t1.number) AS N 
     FROM master..spt_values t1 
       CROSS JOIN master..spt_values t2) 
INSERT INTO Bookings2 
     (PitchType_Skey) 

SELECT v.number 
FROM master..spt_values v 
     CROSS JOIN t1250 
WHERE v.type = 'P' 
     AND v.number > 0 
     AND v.number < 5 

Demo

或者用Moduls作爲msmucker0527 did

WITH t5000 
    AS (SELECT TOP 5000 Row_number() 
          OVER( 
          ORDER BY t1.number) AS N 
     FROM master..spt_values t1 
       CROSS JOIN master..spt_values t2) 
INSERT INTO Bookings2 
    (PitchType_Skey) 
SELECT 
     CASE WHEN n % 4 = 0 THEN 4 ELSE n % 4 END 
FROM t5000 

Demo