How to implement log traversal of tables in SQL Server

Source: Internet
Author: User
Tags rowcount

SQL Servercursors are generally used to traverse tables, andSQL Server can easily loop through cursors to implement SQL Server traversal records in tables. However, cursors are not recommended for actual development. We know that you can also implement SQL Server traversal tables with temporary tables or table variables, etc.The following example uses table variables to implement a simple loop:(run directly into Query Analyzer)
1.   Declare @temp table
 2.              (     
 3.                [id] int identity (, )    
 4.                [name] varchar      
 5.             )      
6.   declare @tempId int, @tempName varchar (TEN)
7.  
 8.             insert into  @temp  values (' a ')      
 9.             insert into  @temp  values (' B ')      
 10.         insert into  @temp  values (' C ')      
 11.         insert into  @temp  values (' d ')      
.   INSERT into @temp values (' E ')
.  
.   --select * from @temp
A .  
 16.         while exists (select [id] from  @temp)      
 17.         begin     
.   SET ROWCOUNT 1
.  SELECT @Tempid= [id],@Tempname=[name] from @temp
 20.         set rowcount 0     
.   Delete from @temp where [id] = @tempId
.  
 23.         print  ' Name:----' [email protected]     
 24.         end    
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.