Link to home
Start Free TrialLog in
Avatar of jxbma
jxbmaFlag for United States of America

asked on

What is the difference between a #Temp table and an @Table variable in MS SQL?

What is the difference between a #Temp table and an @Table variable in MS SQL?

I understand that both are crated in the TempDB. I also understand the creation and scope difference between @Table, #Table and ##Table.

But in simple/straightforward terms, what is the real difference?

When would I use one over the other?

Thanks,
JohnB
ASKER CERTIFIED SOLUTION
Avatar of p_nuts
p_nuts
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Simply said: If you don't have to worry about maintaing tables in database use #temp table.
It is created as a normal table but is managed by the database, will be cleared when you exit SQL.


@t is a temporary table variable returned from a table valued function. @t =@retuen_table in the following example
if object_id(N'ufn_multistatement_table_valued',N'TF') is not null
	drop function dbo.ufn_multistatement_table_valued  ;
go
create function dbo.ufn_multistatement_table_valued 
(@parameter_name  nvarchar(25))
RETURNS @retuen_table TABLE (a nvarchar(25) Primary Key,r nvarchar(25))
WITH EXECUTE AS CALLER
AS
BEGIN
	declare @a nvarchar(25)
	set @a='3'
	INSERT @retuen_table SELECT a, r FROM A WHERE a>@parameter_name
	RETURN
END;
GO
SELECT * from dbo.ufn_multistatement_table_valued('1');

Open in new window

@v is a temporary variable, you can use to manage your table records.

declare @v Int;
select @v=a from A where a=1;
select @v; -- you can manipulate @v and modify the records.

Open in new window