1

我需要关于 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
4

2 回答 2

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

演示

或者像msmucker0527 那样使用Moduls

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 

演示

于 2013-02-08T16:55:11.063 回答
1

将您的选择替换为

SELECT (CASE WHEN @PitchType_Skey % 4 = 0 THEN 4 ELSE @PitchType_Skey % 4 END)

% 是 Modulus 或 Remainder,所以它得到 @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
于 2013-02-08T16:03:19.840 回答