游标的使用


 --//利用游标更改表字段属性
 -- Declare the variables to store the values returned by FETCH.
 Declare @Table varchar(50)
 Declare @Field varchar(50)
 Declare @Length int
 Declare @Type varchar(10)
 
 DECLARE MyCursor CURSOR    
    FOR 
     SELECT o.[name] as tname, c.[name] as fname, c.length, t.[name] as type
     FROM dbo.sysobjects o inner join dbo.syscolumns c
        on o.id=c.id and c.[name] in ('Org_ID','Client_ID','Sender_ID','Receiver_ID','Vendor_Id')
        left join  dbo.systypes t on c.xtype=t.xusertype
        Where o.xtype='U' and o.status>0
        And (t.[name] != 'varchar' Or c.length != 15)
     Order By o.[name]    --定义游标            

OPEN MyCursor    --打开游标

-- Perform the first fetch and store the values in variables.
-- Note: The variables are in the same order as the columns
-- in the SELECT statement. 

FETCH NEXT FROM MyCursor    --提取上次提取行之后的行
INTO @Table@Field@Length@Type

-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
BEGIN
   -- Concatenate and display the current values in the variables.
   PRINT 'Table: ' + @Table + '  Field:' +  @Field
    EXEC('
    Alter Table [' + @Table + ']
    Alter Column [' + @Field + '] varchar(15)
    ')    --修改表

   -- This is executed as long as the previous fetch succeeds.
    FETCH NEXT FROM MyCursor    --提取上次提取行之后的行
    INTO @Table@Field@Length@Type
END

CLOSE MyCursor    --关闭游标
DEALLOCATE MyCursor    --清除游标

GO 
posted @ 2006-01-08 18:21  blueKnight  Views(218)  Comments(0Edit  收藏  举报