Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does MS-SQL support in-memory tables?

Recently, I started changing some of our applications to support MS SQL Server as an alternative back end.

One of the compatibility issues I ran into is the use of MySQL's CREATE TEMPORARY TABLE to create in-memory tables that hold data for very fast access during a session with no need for permanent storage.

What is the equivalent in MS SQL?

A requirement is that I need to be able to use the temporary table just like any other, especially JOIN it with the permanent ones.

like image 667
Hanno Fietz Avatar asked Aug 26 '08 12:08

Hanno Fietz


2 Answers

You can create table variables (in memory), and two different types of temp table:

--visible only to me, in memory (SQL 2000 and above only)
declare @test table (
    Field1 int,
    Field2 nvarchar(50)
);

--visible only to me, stored in tempDB
create table #test (
    Field1 int,
    Field2 nvarchar(50)
)

--visible to everyone, stored in tempDB
create table ##test (
    Field1 int,
    Field2 nvarchar(50)
)

Edit:

Following feedback I think this needs a little clarification.

#table and ##table will always be in TempDB.

@Table variables will normally be in memory, but are not guaranteed to be. SQL decides based on the query plan, and uses TempDB if it needs to.

like image 58
Keith Avatar answered Oct 13 '22 17:10

Keith


@Keith

This is a common misconception: Table variables are NOT necessarily stored in memory. In fact SQL Server decides whether to keep the variable in memory or to spill it to TempDB. There is no reliable way (at least in SQL Server 2005) to ensure that table data is kept in memory. For more detailed info look here

like image 31
Manu Avatar answered Oct 13 '22 19:10

Manu