我需要一个关于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 :(得分:1)
用
替换你的选择SELECT (CASE WHEN @PitchType_Skey % 4 = 0 THEN 4 ELSE @PitchType_Skey % 4 END)
%是模数或余数,因此它获得@PitchType_Skey / 4的剩余部分(保证小于4的值)
然后你必须用4替换0
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
答案 1 :(得分:1)
你实际上不需要一段时间,因为你可以使用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
或使用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