FETCH NEXT的使用

來源:互聯網
上載者:User

原表結構:
HR_NewsPaper
------------------
id
CompanyName
CompanyInfo
PositionName
PositionNumber
Requirement
Note

為了排除冗餘資料,將此表分為兩表,表Company用於儲存公司相關資訊,表HRNewsPaper用於儲存招聘資訊. 
HRNewsPaper表:
------------------
id
CompanyId
PositionName
PositionNumber
Requirement
InfoFrom
UpdateTime

Company表:
------------------
id
CompanyName
CompanyInfo
Note
InfoFrom
UpdateTime

排除原表中關於Company的冗餘資料的方法有三(僅列出關鍵語句):
1. select distinct companyName into tmp from HR_Newspaper

2. select id, CompanyName, CompanyInfo, Note, getDate() as UpdateTime into CompanyNew from HR_Newspaper t1
where checksum(*) = (select top 1 checksum(*) from HR_Newspaper where CompanyName = t1.CompanyName)

3. select  min(id) as id, CompanyName, min(CompanyInfo) as CompanyInfo, min(Note) as Note, getdate() as UpdateTime into NewCompany
 from HR_Newspaper  group   by   CompanyName

使用FETCH NEXT迴圈取出相關資料並插入新表:
DECLARE @CompanyName varchar(256)
declare @CompanyInfo varchar(4000)
declare @PositionName varchar(60)
declare @PositionNumber int
declare @Requirement varchar(4000)
declare @Note varchar(4000)
DECLARE @id int
DECLARE @tmpHrId int
declare @counter int
DECLARE @i int
set @id = 1
set @i = 1
select @counter = count(CompanyName) from HR_NewsPaper

DECLARE hr_cursor CURSOR FOR
SELECT id, CompanyName,CompanyInfo,PositionName,PositionNumber,Requirement,Note FROM HR_NewsPaper

OPEN hr_cursor

FETCH NEXT FROM hr_cursor
INTO @id, @CompanyName,@CompanyInfo,@PositionName,@PositionNumber,@Requirement,@Note

WHILE @@FETCH_STATUS = 0
BEGIN

   PRINT Convert(varchar(4), @id) + ','+  @CompanyName +','+ @PositionName
   select @i = id from COMPANY where CompanyName = @companyName
--插入資料
   INSERT INTO HRNewsPaper (CompanyId, PositionName, PositionNumber, Requirement)
   VALUES (@i, @PositionName, @PositionNumber, @Requirement)
   -- This is executed as long as the previous fetch succeeds.
   FETCH NEXT FROM hr_cursor
   INTO @id, @CompanyName,@CompanyInfo,@PositionName,@PositionNumber,@Requirement,@Note
END

CLOSE hr_cursor
DEALLOCATE hr_cursor

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.