我想在父表中插入10K名稱,在後面添加數字時使用10個描述的名稱。但管理只寫了第一千。我需要你的眼睛看看我失敗的地方。我明白@i並不增加,但不知道爲什麼。SQL:在while循環中while循環
DECLARE @TempNameTable table (ID int , Name varchar (50))
DECLARE @i int = 1,
@tempNameValue varchar(50),
@randNumber int = 1
INSERT INTO @TempNameTable VALUES
(1,'Jonas'), (2,'Petras'),(3,'Antanas')
, (4,'Stasys'), (5,'Dainius'), (6,'Giedrius')
, (7,'Mindaugas'), (8,'Povilas'), (9,'Kestutis')
, (10,'Darius')
WHILE ((SELECT COUNT(Name) FROM Parent) < 10000)
BEGIN
WHILE @i < 11
BEGIN
SET @tempNameValue = CASE
WHEN @i = 1 THEN
(SELECT Name from @TempNameTable WHERE ID = @i)
WHEN @i = 2 THEN
(SELECT Name from @TempNameTable WHERE ID = @i)
WHEN @i = 3 THEN
(SELECT Name from @TempNameTable WHERE ID = @i)
WHEN @i = 4 THEN
(SELECT Name from @TempNameTable WHERE ID = @i)
WHEN @i = 5 THEN
(SELECT Name from @TempNameTable WHERE ID = @i)
WHEN @i = 6 THEN
(SELECT Name from @TempNameTable WHERE ID = @i)
WHEN @i = 7 THEN
(SELECT Name from @TempNameTable WHERE ID = @i)
END
WHILE @randNumber < 1000
BEGIN
INSERT INTO Parent VALUES
(@tempNameValue + CAST(@randNumber as varchar(1000)))
SET @randNumber = @randNumber + 1
END
SET @i = @i + 1
END
END
如果查詢是相同的,爲什麼要使用CASE?您的@i變量保證不同的條件 –
標記您正在使用的dbms(也許是SQL Server?)該代碼與ANSI SQL不兼容。 – jarlh
我正在使用SQL服務器。 – LTnewbie