views:

2186

answers:

6

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

+3  A: 

Yes, you can create it with

SELECT INTO ...

Let's say

SELECT * INTO #t
FROM OPENQUERY( 'server',
'exec database.dbo.proc_name value1, value2, ... ' )
boj
oh that's what he meant!!
Mitch Wheat
Does that work with a table variable?
recursive
I don't know, sorry.
boj
+1  A: 

you don't need OPENQUERY. Just put "INTO #AnyTableName" between the select list and the FROM of any query...

SELECT *
    INTO #Temp1
    FROM table1
    WHERE x=y
KM
or Select * into #Temp1 from table1 where 0 = 1
Gern Blandston
A: 

Had some other difficulties that made the #table solution unworkable so went with a ##table solution. Thanks all for the help really helped me think through this.

Jeff
A: 

can't create table on schema,help me

+1  A: 

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.

ElHaix
However, the table variable must be defined at compile rather than run time right? For this I needed a dynamically generated table.
Jeff
The table variable is defined in the sproc, which I'll post below...
ElHaix
A: 

Defining a table variable rather than a temp table is the optimal solution for this, as there are no disk-hits, among other things...

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.

ElHaix