Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL run from Excel cannot use a temporary table

I have been able to create a data connection from Excel to SQL Server and execute many SQL queries successfully. But I cannot get any TSQL to work if it includes a temporary table. For example:

select * into #t from compass3.dbo.freq
select * from #t where freq_id>2

(Clearly there is no need to use #t in this case: I'm just giving the most simple example.) This work fine in SSMS but when executed via Excel I get the error message "We couldn't refresh the connection 'audbbicube'. The table 'ion Query1' may not exist."

In some other SO posts people suggested adding set nocount on, but that made no difference in this case.

like image 210
MattClarke Avatar asked Jan 28 '14 22:01

MattClarke


People also ask

What can I use instead of temp table in SQL?

A valuable alternatives for the SQL temp table and table variable are SCHEMA_ONLY Memory-Optimized tables and the Memory-optimized Table Variable, where the data will be completely stored in the memory without the need to touch the TempDB database, providing the best data access performance.

Is using CTE better than temp table?

Looking at SQL Profiler results from these queries (each were run 10 times and averages are below) we can see that the CTE just slightly outperforms both the temporary table and table variable queries when it comes to overall duration.


2 Answers

I wanted to add to the above answer - just using SET NOCOUNT ON at the top of the query, with a regular temp table SELECT name INTO #Names FROM Employee should work.

A table variable is not needed here.

You could also add SET ANSI_WARNINGS OFF to avoid messages like "NULL Value is eliminated by an aggregate".

like image 148
arjunrc Avatar answered Oct 31 '22 01:10

arjunrc


The following appears to work ...

set nocount on
declare @t table(fid int)  -- I'm sure I could add the rest of the columns if I wanted to
insert @t select freq_id from compass3.dbo.freq
select * from @t where fid>2

So as long as I turn nocount on and use a table variable rather than a temporary table, I can achieve what I need.

like image 14
MattClarke Avatar answered Oct 31 '22 01:10

MattClarke