2011-11-02 10 views
10

voglio usare le variabili di tabella nelle stored procedure, ma qui è un problema. Le mie tabelle sono molto grandi e dichiarare che una variabile di tabella necessita di un codice lungo per scrivere e fare il debug.Creare @TableVariable in base a una tabella di database esistente?

Gentilmente mi consigli qualche modo per dichiarare le variabili di tabella in modo rapido, è possibile creare variabile di tabella in base a una tabella esistente?

O si prega di condividere qualsiasi suggerimento per creare il codice per la creazione di variabile di tabella.

Grazie

risposta

5

Come discusso in questa SO Question non è possibile selezionare in una variabile di tabella.

Quando si dice "grandi", se si intende un sacco di colonne, l'approccio migliore per voi sarebbe probabilmente a script che tabella come creare e salvare la definizione e l'uso che nel vostro Declare.

Se si intende grande per quanto riguarda il numero di righe che si avranno nella variabile di tabella, si consiglia di prendere in considerazione l'utilizzo di una tabella temporanea che è quindi possibile eseguire un'istruzione SELECT INTO per crearla in base all'originale.

SELECT * INTO #tmpTable FROM srcTable 
+1

Ma cosa succede se c'è una modifica nella struttura della tabella? – Shamim

4

Fare clic destro della tabella, scegliere Script As Create.

Sostituire create table xxx con declare @xxx table.

+0

grazie, possiamo creare variabile di tabella basata sulla tabella esistente? – haansi

+1

@haansi Che Andomar descritto (e quello che ho descritto) è come farlo. Come ho detto nella mia risposta, non è possibile effettuare una selezione per crearla da una tabella esistente come si potrebbe fare per una tabella temporanea. Scripting e usarlo per la tua dichiarazione è l'unico modo reale. –

0

La semplice risposta è "No, non è possibile creare una tabella delle variabili sulla base di altra tabella"

Ma, si può generalizzare un po 'utilizzando una tabella di tipo. Per esempio (nota: è possibile aggiungere documentazione al tavolo tipo e colonne, che può essere utile per riferimento futuro):

PRINT 'type: [dbo].[foo_type]' 
PRINT ' - Check if [dbo].[foo_type] TYPE exists (and drop it if it does).' 
GO 
IF EXISTS (SELECT 1 FROM sys.types WHERE name = 'foo_type' AND is_table_type = 1 AND SCHEMA_ID('dbo') = schema_id) 
BEGIN 
    -- Create the proc 
    PRINT ' - Drop TYPE [dbo].[foo_type]'; 
    DROP TYPE [dbo].[foo_type]; 
END; 
GO 
PRINT ' - create [dbo].[foo_type] TYPE.' 
GO 
CREATE type [dbo].[foo_type] as Table 
(
     [id]     int identity(1,1) PRIMARY KEY 
     , [name]    varchar(255) NOT NULL 
     , [description]   varchar(255) 
     , numeric_data   numeric(26, 6) 
     , datetimestamp   datetime default getdate() 
     , Unique_Indicator  float unique not null default cast(getdate() as float) 
     , CHECK (Unique_Indicator > 0) 

); 
GO 
PRINT ' - done.' 
GO 


-- Adding the descriptions 
PRINT ' - Adding Type level Description' 
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'describe the usage of this type.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TYPE',@level1name=N'foo_type' 
GO 
PRINT ' - Adding Column level Descriptions' 
PRINT ' - column: id' 
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'ID of the record...' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TYPE',@level1name=N'foo_type', @level2type=N'COLUMN',@level2name=N'ID'; 
GO 

------------------------------------------------------------------------------------------------ 
-- use the type defined above to manipulate the variable table: 

declare @foo_table foo_type; 

--insert using the default value for the for the unique indicator. 
insert into @foo_table (name, [description], numeric_data, datetimestamp) 
    values('babar', 'this is the king of the elephants', 12.5, '1931-01-01') 
     ; 

-- insert the records one by one to use the scope_identity() for the unique indicator. 
insert into @foo_table (name, [description], numeric_data, datetimestamp, Unique_Indicator) 
    values('zephyr', 'Babar''s monkey friend', 5.5, '1932-01-01', scope_identity()) 
     ; 
insert into @foo_table (name, [description], numeric_data, datetimestamp, Unique_Indicator) 
    values ('Celeste', 'Babar''s sister', 19.5, '1932-01-01', scope_identity()) 
     ; 

-- insert using a list of values 
insert into @foo_table (name, [description], numeric_data, datetimestamp, Unique_Indicator) 
    values('Babur', 'Not Babar!!!', 1483, '1983-02-14', 10) 
     , ('Mephistopheles', 'Not Babar either...', 666, '1866-01-01',11) 
     ; 

-- insert using a select 
insert into @foo_table (name, [description], numeric_data, datetimestamp, Unique_Indicator) 
    (select 'Conan', 'The Cimmerian barbarian', 850, '1932-12-01',99 union 
     select 'Robert E. Howard', 'Conan''s creator', 30, '1906-01-22', 100 
    ); 

-- check the data we inserted in the variable table. 
select * from @foo_table; 


-- Clean up the example type 
DROP TYPE [dbo].[foo_type]; 
Problemi correlati