Sqlserverfor Loop Problems

Source: Internet
Author: User
SQL Server does not have a For loop, but can be replaced by a while loop. The following is an example For your reference. Sample Code for copying: CREATEPROCEDUREAddStudentsASBeginDeclare @ nbigintDeclare @ Sqlnvarchar (225) set @ n0while @ n10000beginSet @ SqlInsertintoSt

SQL Server does not have a For loop, but can be replaced by a while loop. The following is an example For your reference. Code example: create procedure AddStudents AS Begin Declare @ n bigint Declare @ SQL nvarchar (225) set @ n = 0 while @ n10000 begin Set @ SQL = 'insert into St

SQL Server does not haveLoopBut you can useLoopHere is an example for your reference.

Sample Code:

Create procedure AddStudents
Begin
Declare @ n bigint
Declare @ SQL nvarchar (225)
Set @ n = 0
While @ n< 10000
Begin
Set @ SQL = 'insert into Students Values (''hamunet'', 10, ''sianchina', ''100 '')'
Exec (@ SQL)
Set @ n = @ n + 1
End

Another SQL serverLoopAlternative example.
ForLoopProcessing.

Sample Code:

Declare @ itemnumber int -- Definition requiredLoopNumber of times
Declare @ tagint int -- defines the flag field for endLoop
Set @ tagint = 1
Select @ itemnumber = count (distinct Creater) from Demo_TestTable where isnull (Creater, '') <>'' And
DATEDIFF (DAY, CreatDate, GETDATE () <1
If (@ itemnumber> 0)
Begin
While @ tagint <= @ itemnumber
Begin
Waitfor delay '00: 00: 01' -- replace available parameter variables every second
Update Demo_TestTable set CreatDate = GETDATE () where Creater = (
Select Creater from (
Select Creater, ROW_NUMBER () over (order by Creater) as RowID from Demo_TestTable where
Isnull (Creater, '') <>'' And DATEDIFF (DAY, CreatDate, GETDATE () <1 group by Creater
) TableA
Where TableA. RowID = @ tagint
)
Set @ tagint = @ tagint + 1
End
End

LoopThen, the format of yyyy-MM-dd hh: mm: ss: fff in CreatDate is changed to yyyy-MM-dd.
SQL server does not haveLoopIt is good to use while instead.

This article from: script School, reproduced please indicate the source: http://www.jbxue.com/db/6301.html

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.