当前位置: 代码迷 >> Sql Server >> 存储过程-表变量跟while简单运用
  详细解决方案

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

热度:83   发布时间:2016-04-24 09:29:59.0
存储过程--表变量和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=013 DECLARE @i INT SET @i=014 DECLARE @id INT15 DECLARE @name varchar(20)16 17 SELECT @c=COUNT(*) FROM @NewDT18 PRINT @c19 20 WHILE(@i<@c)21 BEGIN22 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+128 PRINT @i29 END30 END31 32  
View Code

 

  相关解决方案