SQL循环插入记录,需要用到WHILE来实现,比如要插入L1至L50到表中。
Code
DECLARE @i int
SET @i=1
WHILE @i < 44
BEGIN
INSERT INTO [ProductionLines] ([ProductionLinesName]) VALUES ('L' + CONVERT(nvarchar,@i))
SET @i= @i+1
END
DECLARE @i int
SET @i=1
WHILE @i < 44
BEGIN
INSERT INTO [ProductionLines] ([ProductionLinesName]) VALUES ('L' + CONVERT(nvarchar,@i))
SET @i= @i+1
END
如果需要插入如下数据,MA001至MA999呢:
Code
DECLARE @j int
SET @j = 1
WHILE @j <1000
BEGIN
IF LEN(CONVERT(nvarchar,@j))=1
INSERT INTO [Machine] ([MachineName]) VALUES ('MA00' + CONVERT(nvarchar,@j))
IF LEN(CONVERT(nvarchar,@j))=2
INSERT INTO [Machine] ([MachineName]) VALUES ('MA0' + CONVERT(nvarchar,@j))
IF LEN(CONVERT(nvarchar,@j))=3
INSERT INTO [Machine] ([MachineName]) VALUES ('MA' + CONVERT(nvarchar,@j))
SET @j= @j+1
END
DECLARE @j int
SET @j = 1
WHILE @j <1000
BEGIN
IF LEN(CONVERT(nvarchar,@j))=1
INSERT INTO [Machine] ([MachineName]) VALUES ('MA00' + CONVERT(nvarchar,@j))
IF LEN(CONVERT(nvarchar,@j))=2
INSERT INTO [Machine] ([MachineName]) VALUES ('MA0' + CONVERT(nvarchar,@j))
IF LEN(CONVERT(nvarchar,@j))=3
INSERT INTO [Machine] ([MachineName]) VALUES ('MA' + CONVERT(nvarchar,@j))
SET @j= @j+1
END