SQL Server循環插入

一個SQL循環插入的代碼,運行正常:函數

 BEGIN
  DECLARE @idx AS INT;
  DECLARE @NodeName nvarchar(255); DECLARE @OtherName nvarchar(255); DECLARE @ParentId INT; DECLARE @OrderId Int; DECLARE @Url nvarchar(255); DECLARE @NodeClass nvarchar(255); DECLARE @myTable TABLE (NodeName nvarchar(255),OtherName nvarchar(255), ParentId INT,OrderId Int,Url nvarchar(255),NodeClass nvarchar(255)); INSERT INTO @myTable select NodeName,OtherName,ParentId,OrderId,Url,NodeClass from SysMenu where OtherName = '超級管理員'; declare @count int select @count=count(*) from @myTable set @idx=1; WHILE @idx <= @count BEGIN select @NodeName=NodeName, @OtherName=OtherName, @ParentId=ParentId, @OrderId=OrderId, @Url=Url, @NodeClass=NodeClass from (select row_number() over( order by OrderId)num,* from @myTable) a where num=@idx; INSERT INTO SysMenu (NodeName,OtherName,ParentId,OrderId,Url,NodeClass) values(@NodeName,'銷售設計渠道',@ParentId,-1,@Url,@NodeClass); SET @idx = @idx + 1; END End

整體思路:spa

 一、創建一個臨時表MyTable,將須要循環插入的數據插入到裏面。設計

 二、聲明一個變量,記錄數據總量:declare @count int select @count=count(*) from @myTable 。code

 三、用Wihle循環插入。blog

問題:如何取臨時表MyTable中的每一條數據?排序

解:參照代碼,使用rownumber函數排序,就能夠依次取出。class

相關文章
相關標籤/搜索