首页 > 代码库 > Sqlserver 循环表

Sqlserver 循环表

CREATE TABLE dbo.[User] (
  UID BIGINT IDENTITY
 ,Name VARCHAR(50) NOT NULL
 ,Pwd VARCHAR(50) NOT NULL
 ,CONSTRAINT PK_User PRIMARY KEY CLUSTERED (UID)
) ON [PRIMARY]
-- 方法2:使用表变量
-- 声明表变量
DECLARE @temp TABLE
(
    UID BIGINT,
    Name VARCHAR(50),
    Pwd VARCHAR(50)
);

-- 将源表中的数据插入到表变量中
INSERT INTO @temp(UID, Name, Pwd )
SELECT UID,Name,Pwd FROM [User]
ORDER BY UID;

-- 声明变量
DECLARE
    @UID AS BIGINT,
    @Name AS VARCHAR(50),
    @Pwd AS VARCHAR(50);
    
WHILE EXISTS(SELECT UID FROM @temp)
BEGIN
    -- 无序堆top1 有索引 top1  SET ROWCOUNT 1 无差别
    SELECT top 1 @UID= UID, @Name= Name,@Pwd= Pwd FROM @temp;  
   -- SELECT @UID,@Name,@Pwd
    PRINT 主键+ cast(@UID as varchar(50))+用户名+@Name+密码+@Pwd
   -- SET ROWCOUNT 0    
    DELETE FROM @temp WHERE UID=@UID;
END

 

Sqlserver 循环表