MS-SQLSERVER 批量修改表中 某個字段可爲NULL

-- 危險操做,處理前記得先備份數據庫


1
declare @sql varchar(500),@tbname varchar(100) 2 begin 3 4   -- 建立遊標 5   declare cursor_item cursor fast_forward for select [name] from sysobjects where xtype='U' AND id in(select id from syscolumns where name='myColumnName' and colstat=0 ) 6   open cursor_item;--打開遊標 7   while 1=1 --開始循環 8   begin 9     fetch next from cursor_item into @tbname; --賦值到變量中 10     if(@@fetch_status!=0) break;--若是沒有結果退出循環
11 12     -- 拼接修改字段的SQL語句 13     set @sql = 'alter table '+@tbname+' alter column myColumnName int NULL' 14 15     -- 執行拼接的SQL 16     exec(@sql); 17 18   end 19   close cursor_item --關閉遊標 20   deallocate cursor_item 21 22 end;

 

注意:sql

syscolumns 保存列信息的系統表
sysobjects 保存表信息的系統表

 colstat=0  表示查詢非自增加標識列數據庫

相關文章
相關標籤/搜索