Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql server temp table

Tags:

sql

sql-server

I need to create a temp table who contains the number of employes of each department. If the department have no employer, we need to print a message.

IF (count(*) = 0) 
    BEGIN
    PRINT 'Espace vide'
    END
    else 
    Select deptno,count(*)  
    from emp    
    group by deptno;

this is the query to see how many employes are in each dept, but I don't know how to create a temp table with it.

like image 712
MTHeadss Avatar asked Feb 09 '12 17:02

MTHeadss


People also ask

How do I create a temporary table in SQL Server?

Create a Global Temporary Table in SQL Server. You can also create a global temporary table by placing double hash (##) before the temporary table name. The global temporary table will be available across different connections. 3 records will be inserted into the table.

Where are temp tables in SQL Server?

Temporary tables are stored in tempdb. They work like a regular table in that you can perform the operations select, insert and delete as for a regular table. If created inside a stored procedure they are destroyed upon completion of the stored procedure.

Which is better CTE or temp table?

As far as when to use each, they have very different use cases. If you will have a very large result set, or need to refer to it more than once, put it in a #temp table. If it needs to be recursive, is disposable, or is just to simplify something logically, a CTE is preferred.

What is temp table in SQL Server?

What is a temp table? As its name indicates, temporary tables are used to store data temporarily and they can perform CRUD (Create, Read, Update, and Delete), join, and some other operations like the persistent database tables.


1 Answers

Choose suitable for you method:

Select deptno,count(*) cnt
INTO #TempTable  
from emp    
group by deptno;

select 
  *,
  CASE cnt WHEN 0 THEN 'Espace vide' ELSE NULL END AS column1
FROM #TempTable

if exists(SELECT * FROM #TempTable WHERE cnt = 0) PRINT 'Espace vide'
like image 127
Oleg Dok Avatar answered Sep 21 '22 03:09

Oleg Dok