Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: Where xxx IN temporary table

Tags:

I have a temp table and want to check in a where clause wether a certain id/string is contained in the temp table.

Select... WHERE MyId  IN MyTempTable 

I get a general error in MS SQL Management studio.

is the "In" operator not suited for temp tables?

like image 730
Elisabeth Avatar asked Dec 06 '10 15:12

Elisabeth


People also ask

How do I access a temporary table in SQL?

The global temporary tables are created using the CREATE TABLE statement and their names must be prefixed with the double hashtag (##) sign. These tables can be accessed by all other sessions, unlike local ones.

Can we use Nolock for temp table?

While NOLOCK can "help" queries against *permanent* tables, it does not quite have the same effect against *temporary* tables - SQL Server knows that it doesn't have to worry about blocking other readers or writers, because #temp tables are scoped to a single, specific session.

What is ## temp table?

Temporary Tables. A temporary table is a base table that is not stored in the database, but instead exists only while the database session in which it was created is active.


1 Answers

Your syntax is wrong:

SELECT ...   FROM MyTable  WHERE MyID IN (SELECT MyID                   FROM MyTempTable) 

I don't much like the IN operator, so I prefer this:

SELECT ...   FROM MyTable  WHERE EXISTS (SELECT *                  FROM MyTempTable                 WHERE MyTable.MyID = MyID) 

But it's largely a matter of taste.

like image 147
Marcelo Cantos Avatar answered Sep 28 '22 11:09

Marcelo Cantos