views:

31

answers:

2

I've picked up some SQL similar to the following:

IF EXISTS(SELECT name FROM tempdb..sysobjects WHERE name Like N'#tmp%'
 and id=object_id('tempdb..#tmp'))
DROP TABLE #tmp

into #tmp
select * from permTable

I need to add more data to #tmp before continuing processing:

insert into #tmp
select * from permTable2

But this gives errors because SQL has assumed sizes and types for #tmp columns (e.g. if permTable has a column full of ints but permTable2 has column with same name but with a NULL in one record you get "Cannot insert the value NULL into column 'IsPremium', table 'tempdb.dbo.#tmp").

How do I get #tmp to have the types I want? Is this really bad practise?

+2  A: 

Have you considered creating a table var instead? You can declare the columns like such

declare @sometable table(
     SomeField [nvarchar](15),
     SomeOtherField [decimal](15,2));
Christopherous 5000
Cool, looks good. Is sometable created in the same place, have the same life cycle etc as #tmp?
Patrick
Table vars go out of scope with the proc or function, where temp tables go out of scope at the end of the session. See http://databases.aspfaq.com/database/should-i-use-a-temp-table-or-a-table-variable.html for some more details
Christopherous 5000
Great link, thank you
Patrick
+1  A: 

This is why select into is a poor idea for your problem. Create the table structure specifically with a create table command and then write two insert statements.

HLGEM