MySQL while语法
### MySQL while语法
DELIMITER //
DROP PROCEDURE IF EXISTS Pgm_while_001;
CREATE PROCEDURE Pgm_while_001() BEGIN
DECLARE flag INT DEFAULT 0;
DECLARE tmphost VARCHAR(40);
DECLARE num int default 0;
DECLARE hostlist CURSOR FOR SELECT HostName FROM `sql_table1` WHERE IPv4Address != '';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET flag=1;
OPEN hostlist;
FETCH hostlist INTO tmphost;
WHILE flag <> 1 DO
SET @newipv4=(SELECT IPv4Address FROM `sql_table1` WHERE IPv4Address != '' AND HostName = tmphost LIMIT 0,1);
SET @newmac=(SELECT MacAddress FROM `sql_table1` WHERE MacAddress != '' AND HostName = tmphost LIMIT 0,1);
UPDATE `sql_table1` SET IPv4Address=@newipv4,MacAddress=@newmac WHERE HostName = tmphost AND IPv4Address = '';
FETCH hostlist INTO tmphost;
END WHILE;
CLOSE hostlist;
END
//
DELIMITER ;
CALL Pgm_while_001();
MSSQL while语法-案例1
### MSSQL While语法
# 案例1
USE sql_database
DECLARE
@Id uniqueidentifier,
@ProductId nvarchar(50),
@DelBarcodeList varchar(max),
@BoxBarcode nvarchar(50),
@BoxType int ,
@OrderId nvarchar(50),
@BoxQty int ,
@IsPrint int ,
@EAN nvarchar(50) ,
@FUW_MOMA nvarchar(50) ,
@UserCode nvarchar(50) ,
@UserAlias nvarchar(50) ,
@HostName nvarchar(50) ,
@IPv4Address nvarchar(50) ,
@MacAddress nvarchar(50) ,
@LoginName nvarchar(50) ,
@ScreenSnap_b64File varchar(200) ,
@DeleteTime datetime
DECLARE id_cursor CURSOR
FOR (SELECT TOP 1000 Id,UserCode,UserAlias,HostName,IPv4Address,MacAddress,LoginName,DeleteTime FROM sql_table1)
OPEN id_cursor
FETCH NEXT FROM id_cursor INTO @Id,@UserCode,@UserAlias,@HostName,@IPv4Address,@MacAddress,@LoginName,@DeleteTime
WHILE @@FETCH_STATUS=0
BEGIN
SET @var001=CONVERT(nvarchar(36),@Id)+'.txt'
INSERT INTO sql_table2
VALUES (@Id,@UserCode,@UserAlias,@HostName,@IPv4Address,@MacAddress,@LoginName,@var001,@DeleteTime)
FETCH NEXT FROM id_cursor INTO @Id,@UserCode,@UserAlias,@HostName,@IPv4Address,@MacAddress,@LoginName,@DeleteTime
END
CLOSE id_cursor
DEALLOCATE id_cursor
MSSQL while语法-案例2
### MSSQL While语法
# 案例2
USE sql_database
DECLARE
@HostName nvarchar(50)
DECLARE a_cursor CURSOR
FOR (SELECT HostName FROM sql_table1 WHERE IPv4Address='')
OPEN a_cursor
FETCH NEXT FROM a_cursor INTO @HostName
WHILE @@FETCH_STATUS=0
BEGIN
UPDATE sql_table1 SET IPv4Address=(SELECT TOP 1 IPv4Address FROM sql_table1 WHERE HostName=@HostName and IPv4Address <> ''),
MacAddress=(SELECT TOP 1 MacAddress FROM sql_table1 WHERE HostName=@HostName AND MacAddress <> '') WHERE HostName=@HostName AND IPv4Address = ''
FETCH NEXT FROM a_cursor INTO @HostName
END
CLOSE a_cursor
DEALLOCATE a_cursor
无