SQL 2008循环所有表和所有列
Code
declare @tblname varchar(200)
declare @object_id int
declare tbl_cursor CURSOR for
select name,object_id from sys.all_objects where type='u'
open tbl_cursor
FETCH NEXT FROM tbl_cursor
INTO @tblname,@object_id
while @@FETCH_STATUS = 0
Begin
declare @str varchar(8000)
declare @selectstr varchar(2000)
set @selectstr=''
set @str='INSERT INTO '+ @tblname +'('
--print @tblname,@object_id
declare @colname varchar(200)
declare col_cursor CURSOR for
select name from sys.columns where object_id=@object_id order by column_id
open col_cursor
FETCH NEXT FROM col_cursor INTO @colname
WHILE @@FETCH_STATUS = 0
BEGIN
set @str=@str+@colname+','
--Print @str
set @selectstr=@selectstr+@colname+','
--Print @colname
FETCH NEXT FROM col_cursor INTO @colname
END
close col_cursor
deallocate col_cursor
set @str=substring(@str,0,len(@str))
set @selectstr=substring(@selectstr,0,len(@selectstr))
set @str=@str+') SELECT ' + @selectstr +' FROM '+ @tblname
Print @str
fetch next from tbl_cursor into @tblname,@object_id
End
close tbl_cursor
deallocate tbl_cursor
declare @tblname varchar(200)
declare @object_id int
declare tbl_cursor CURSOR for
select name,object_id from sys.all_objects where type='u'
open tbl_cursor
FETCH NEXT FROM tbl_cursor
INTO @tblname,@object_id
while @@FETCH_STATUS = 0
Begin
declare @str varchar(8000)
declare @selectstr varchar(2000)
set @selectstr=''
set @str='INSERT INTO '+ @tblname +'('
--print @tblname,@object_id
declare @colname varchar(200)
declare col_cursor CURSOR for
select name from sys.columns where object_id=@object_id order by column_id
open col_cursor
FETCH NEXT FROM col_cursor INTO @colname
WHILE @@FETCH_STATUS = 0
BEGIN
set @str=@str+@colname+','
--Print @str
set @selectstr=@selectstr+@colname+','
--Print @colname
FETCH NEXT FROM col_cursor INTO @colname
END
close col_cursor
deallocate col_cursor
set @str=substring(@str,0,len(@str))
set @selectstr=substring(@selectstr,0,len(@selectstr))
set @str=@str+') SELECT ' + @selectstr +' FROM '+ @tblname
Print @str
fetch next from tbl_cursor into @tblname,@object_id
End
close tbl_cursor
deallocate tbl_cursor