存储过程--表变量和while简单运用

1、sql创建表
/*订单*/
CREATE TABLE Orders
(
PRIMARY KEY(Id),
Id int,
Name varchar(20)
)
2、存储过程ProTestDT
    1)创建表变量@NewDT
    2)给表变量@NewDT赋值(INSERT)
    3)循环表变量@NewDT,更新实际表dbo.Orders

 1 CREATE PROCEDURE ProTestDT

 2 AS

 3 BEGIN

 4 DECLARE @NewDT TABLE

 5 (

 6 dtID int,

 7 dtName varchar(20)

 8 )

 9 

10 INSERT INTO @NewDT(dtID,dtName) SELECT id,Name FROM dbo.Orders 

11 

12 DECLARE @c INT SET @c=0

13 DECLARE @i INT SET @i=0

14 DECLARE @id INT

15 DECLARE @name varchar(20)

16 

17 SELECT @c=COUNT(*) FROM @NewDT

18 PRINT @c

19 

20 WHILE(@i<@c)

21 BEGIN

22 SELECT TOP 1 @id=dtID,@name=dtName FROM @NewDT /*表变量查询一条数据*/

23 SET @name=CONVERT(VARCHAR,@id)+@name+CONVERT(VARCHAR,@id)

24 UPDATE dbo.Orders SET Name=@name WHERE id=@id /*更新表*/

25 DELETE FROM @NewDT WHERE dtID=@id /*表变量删除查询出来的数据*/

26 

27 SET @i=@i+1

28 PRINT @i

29 END

30 END

31 

32  
View Code

 

你可能感兴趣的:(while)