Posts
400
Comments
213
Trackbacks
0
Eine Tabelle in eine temporäre Tabelle kopieren

Es gibt mindestens 2 Wege eine Tabelle in eine temporäre Tabelle zu kopieren:

einfacher Weg: 

DECLARE @tabelle nvarchar(100)
DECLARE @sql nvarchar(1000)

set @tabelle = "TabellenName"

set @sql = 'select * into ##temp from ' + @tabelle 
exec(@sql) 

   

umständlicher Weg: 

-- eine leere temporäre Tabelle anlegen
if object_id(N'tempdb..#temp') is not null
begin
   drop table #temp
end

create table #temp(id int)  

DECLARE TabellenFelder CURSOR FOR 
select  column_name, data_type, character_maximum_length,is_nullable 
from    information_schema.columns
where   table_name = @Tabelle
order   by ordinal_position

OPEN TabellenFelder 

FETCH NEXT FROM TabellenFelder INTO @column_name, @data_type, @character_maximum_length, @is_nullable 

WHILE @@FETCH_STATUS =
      BEGIN 
            --neue Spalte hinzufügen 
            set @sql = 'alter table #temp add ' + @column_name + ' ' 
            set @sql = @sql + @data_type 
            if @data_type ='nvarchar'  
            set @sql = @sql + '(' + @character_maximum_length +')' 
            exec(@sql)

            FETCH NEXT FROM TabellenFelder INTO @column_name, @data_type, @character_maximum_length, @is_nullable  
      END

CLOSE TabellenFelder
DEALLOCATE TabellenFelder

--die erste Spalte wieder löschen
set @sql = 'alter table #temp drop column id'
exec(@sql)

-- jetzt die Tabelle in die temporäre Tabelle kopieren
set @sql = 'insert into #temp select * from ' + @Tabelle
exec(@sql) 

posted on Wednesday, May 11, 2011 11:57 AM Print
Comments
Gravatar
# dallas garage doors
jony english
4/28/2012 2:39 PM
Excellent information, frisco garage door repair this is exactly what I needed. Dallas SEO Company Thanks. Keep up the good work!
Gravatar
# scottsdale moversv
scottsdale movers
4/29/2012 7:42 AM
Cool....i just love learning new things, thanks for the good instruction that i have found here.
Gravatar
# water damage san diego
water damage san diego
4/29/2012 7:46 AM
Great post, I never knew that, this is by far one of the most comprehensive posts i've seen here and look forward to more of the you have always nice things to post.
Gravatar
# Redding Wedding Photographer
Redding Wedding Photographer
4/29/2012 6:53 PM
Your all the post is so interesting so when is the next post coming? -
Gravatar
# re: Eine Tabelle in eine temporäre Tabelle kopieren
shahzad
5/14/2012 9:01 AM
my website are is as drivers as the business and cilents they promoter
Gravatar
# re: Eine Tabelle in eine temporäre Tabelle kopieren
Theater Seating
5/16/2012 3:13 PM
The post is written in very a good manner and it entails many useful information for me. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept. Thank you for the post.

Post Comment

Title *
Name *
Email
Url
Comment *  
Please add 2 and 1 and type the answer here: