Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL Define Temp Table (or table variable) Without Defining Schema?

Is there a way to define a temp table without defining it's schema up front?

like image 818
Jeff Avatar asked Mar 27 '09 01:03

Jeff


People also ask

How do you DECLARE a table variable in SQL?

To declare a table variable, start the DECLARE statement. The name of table variable must start with at(@) sign. The TABLE keyword defines that used variable is a table variable. After the TABLE keyword, define column names and datatypes of the table variable in SQL Server.

What is difference between table variable and temp table in SQL Server?

Table variable involves the effort when you usually create the normal tables. Temp table result can be used by multiple users. Table variable can be used by the current user only. Temp table will be stored in the tempdb.


1 Answers

Actually using a table VARIABLE, an in-memory table, is the optimal way to go. The #table creates a table in temp db, and ##table is global - both with disk hits. Consider the slow-down/hit experienced with the number of transactions.

CREATE PROCEDURE [dbo].[GetAccounts]      @AccountID BIGINT,     @Result INT OUT,     @ErrorMessage VARCHAR(255) OUT AS BEGIN     SET NOCOUNT ON;     SET @Result = 0     SET @ErrorMessage = ''      DECLARE @tmp_Accounts TABLE (                                                 AccountId BIGINT, AccountName VARCHAR(50), ... )  INSERT INTO @tmp_Accounts ([AccountId], [AccountName]... ) SELECT AccountID, AccountName FROM Accounts WHERE  ...       IF @@Rowcount = 0         BEGIN             SET @ErrorMessage = 'No accounts found.'             SET @Result = 0              RETURN @Result         END     ELSE         BEGIN             SET @Result = 1              SELECT *             FROM @tmp_Accounts         END  

Note the way you insert into this temp table.

The down-side of this is that it may take a bit longer to write, as you have to define your table variable.

I'd also recommend SQL Prompt for Query Analyzer by RedGate.

like image 162
ElHaix Avatar answered Sep 21 '22 10:09

ElHaix