SQL 2008 : How can i see Temptable in DB? - sql

I have made one temp table in my database.
My question is "How can i see my temp table in database ?"
Is it physically allocated ?

When you create a table prefaced with a pound sign, it gets created in your tempdb database. Once the procedure calling it is over, it is automatically dropped.
create table #notforlong (id int,catname varchar(20))
It now exists in tempdb
You could find it in sysobjects where name like '#notforlong%'. However, since it goes away outside your proc anyway, I'm not sure it's helpful to refer to it this way.

Your question is completely unclear.
What do you mean by "seeing the table graphically"?
Here's an answer for one interpretation of it as you also mention physical allocation (Assumes: SQL Server 2008)
CREATE TABLE #foo
(
bar int,
baz nchar(100)
)
insert into #foo values (1, REPLICATE('A',100))
select sys.fn_PhysLocFormatter(%%physloc%%) AS RID, bar, baz
FROM #foo /*Returned 1:121:0 for me*/
Then look at that page in SQL Internals Viewer

Related

There is already an object named '#tmptable' in the database

I´m trying to execute stored procedure but I get an issue of an existing temporal table, but I just create one time and use into another part of code
SELECT ...
INTO #tmpUnidadesPresupuestadas
FROM proce.table1
--Insertar in table src..
INSERT INTO table (
....)
SELECT
....
FROM
#tmpUnidadesPresupuestadas
I get this message:
There is already an object named
'#tmpUnidadesPresupuestadas' in the database.
How can I solve it? Regards
A temp table lives for the entirety of the current session. If you run this statement more than once, then the table will already be there. Either detect that and truncate it, or before selecting into it drop it if it exists:
DROP TABLE IF EXISTS #tmpUnidadesPresupuestadas
If prior to SQL Server 2016, then you drop as such:
IF OBJECT_ID('tempdb.dbo.#tmpUnidadesPresupuestadas', 'U') IS NOT NULL
DROP TABLE #tmpUnidadesPresupuestadas;
Without seeing more of the code, it's not possible to know if the following situation is your problem, but it could be.
When you have mutually exclusive branches of code that both do a SELECT...INTO to the same temp table, a flaw causes this error. SELECT...INTO to a temp table creates the table with the structure of the query used to fill it. The parser assumes if that occurs twice, it is a mistake, since you can't recreate the structure of the table once it already has data.
if #Debug=1
select * into #MyTemp from MyTable;
else
select * into #MyTemp from MyTable;
While obviously not terribly meaningful, this alone will show the problem. The two paths are mutually exclusive, but the parser thinks they may both get executed, and issues the fatal error. You extend that, wrapping each branch in a BEGIN...END, and add the drop table (conditional or not) and the parser will still give the error.
To be fair, in fact both paths COULD be executed, if there were a loop or GOTO so that one time around #Debug = 1, and the other time it does not, so it may be asking too much of a parser. Unfortunately, I don't know of a workaround, and using INSERT INTO instead of SELECT INTO is the only way I know to avoid the problem, even though that can be terribly onerous to name all the columns in a particularly column-heavy query.
I am a bit unclear as to what you are attempting. I assume you don't want to drop the table at this point. I believe the syntax you may be looking for is
Insert Into
Insert into #tmpUnidadesPresupuestadas (Col1, col2, ... colN)
Select firstcol, secondcol... nthCol
From Data
If you do indeed wish to drop the table, the previous answers have that covered.
This might be useful for someone else, keep in mind that If more than one temporary table is created inside a single stored procedure or batch, they must have different names. If you use the same name you won't be able to ALTER the PROCEDURE.
https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2012/ms174979(v=sql.110)#temporary-tables
Make sure the stored procedure and the table doesn't have same name.
Add logic to delete if exists. Most likely you ran it previously. The table remains from the previous running of the stored procedure. If you log out and log in then run it, that would likely clear it. But the cleanest way is to check if it exists and delete it if it does. I assume this is MsSql.
At first you should check if temp table is already exist if yes then delete it then create a empty table then use insert statement. refer below example.
IF OBJECT_ID('tempdb..#TmpTBL') IS NOT NULL
DROP TABLE #TmpTBL;
SELECT TOP(0) Name , Address,PhoneNumber
INTO #TmpTBL
FROM EmpDetail
if #Condition=1
INSERT INTO #TmpTBL (Name , Address,PhoneNumber)
SELECT Name , Address,PhoneNumber FROM EmpDetail;
else
INSERT INTO #TmpTBL (Name , Address,PhoneNumber)
SELECT Name , Address,PhoneNumber FROM EmpDetail;

Is it necessary to use # for creating temp tables in SQL server?

Is it necessary to use # before creating a temporary table in SQL server?
Example:
SELECT column1, column2, someInt, someVarChar
INTO ItemBack1
FROM table2
WHERE table2.ID = 7
For ItemBack1 is it necessary to use the # symbol?
If not, then what is the use of # in creating temp tables?
Yes. You need to prefix the table name with "#" (hash) to create temporary tables.
If you do NOT need the table later, go ahead & create it.
Temporary Tables are very much like normal tables. However, it gets created in tempdb.
Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.
"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.
Refer the below link for the Basics of Temporary Tables:
http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005
If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.
They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.
DECLARE #ItemBack1 TABLE
(
column1 int,
column2 int,
someInt int,
someVarChar nvarchar(50)
);
INSERT INTO #ItemBack1
SELECT column1,
column2,
someInt,
someVarChar
FROM table2
WHERE table2.ID = 7;
More Info on Table Variables:
http://odetocode.com/articles/365.aspx
The difference between this two tables ItemBack1 and #ItemBack1 is that the first on is persistent (permanent) where as the other is temporary.
Now if take a look at your question again
Is it necessary to Use # for creating temp table in sql server?
The answer is Yes, because without this preceding # the table will not be a temporary table, it will be independent of all sessions and scopes.

Selecting data from more than 2000 databases?

How i can search / select a field in more than 2000 databases in sql server.
i have a main database consisting a table called 'Kewword" where i store key world under 'kewwordtitle' field in keyword table, when new user register a new database are created for the user and user use a keyword,
now the situtation is, how i can find that how much user use a key work, here keywordtitle is primary key,...
thanks/
Your question is a little bit fuzzy, but if this is a one shot and if all your databases are on the same instance, you could do something like:
declare #t table(col int)
insert #t
exec sp_MSforeachdb 'use ?; select 1 from keyword where keywordtitle = ''<yourkeyword>'''
select count(*) from #t

table variables created and held in memory or in tempdb?

Are table variables created in memory or in tempdb? Same for
short temp tables?
A temp table will be created in tempdb and you can easily check for it by querying the sysobjects table in tempdb
example
create table #test (Item char(1), TimeSold varchar(20))
select * from tempdb.sys.sysobjects
where name like '#test%'
you should see something with a name like #test_______000000000905 but then with more underscores
If you need to check if a temp table exists then see also How Do You Check If A Temporary Table Exists In SQL Server
The structure of Table variable is also created in tempdb To see the table variable you could do something like this but there is not guarantee that someone didn't sneak in before you when creating his/her table variable. The table variable name will be something like #7BB1235D
declare #v table(id int)
select top 1 * from tempdb.sys.sysobjects
where name like '#%'
and name not like '%[_]%'
order by crdate desc
select * from #v
For more info see here: http://support.microsoft.com/kb/305977
It's been my understanding that, at a minimum, the structure of a table variable is always created in TempDB. Then, as pointed out by SQLMenace, the data may or may not spill over.
Per this Microsoft Knowledge Base Article:
A table variable is not a memory-only
structure. Because a table variable
might hold more data than can fit in
memory, it has to have a place on disk
to store data. Table variables are
created in the tempdb database similar
to temporary tables. If memory is
available, both table variables and
temporary tables are created and
processed while in memory (data
cache).
In MS SQL 2014 was introduced special type of table variables "Memory-Optimized Table Variables". And they don't use tempdb.
See https://msdn.microsoft.com/en-us/library/dn535766.aspx

T-SQL Table Variable Creating PHYSICAL Table!

OMG! What am I doing wrong?
declare #WTF TABLE (
OrderItemId int
)
SELECT TOP 20 OrderItemId as OrderItemId INTO [#WTF] FROM ac_OrderItems
SELECT * FROM [#WTF]
Problem A: This creates a PHYSICAL table called #WTF. WHY?? I thought this was in memory only?!
Problem B: The last line of code, if I do select * from #WTF... WITHOUT the [ ], it returns NOTHING. What is the significance of the [ ]?
I need serious help. I'm losing my MIND!
Thanks in advance.
What you experience is by design:
SELECT…INTO creates a new table in the default filegroup and inserts the resulting rows from the query into it.
The alternatives are to either:
Not define the WTF table, and rely on the behavior to create it automatically
Use the existing code, but change the SELECT INTO into an INSERT:
INSERT INTO #WTF
(orderitemid)
SELECT TOP 20
oi.orderitemid
FROM ac_ORDERITEMS oi
Mind that when using TOP, you should be defining an ORDER BY clause to ensure data is returned consistently.
Because Select INTO always creates a physical table. What you want to do is an Insert Into.
The Select INTO is creating a physical table named '#WTF', just as it's supposed to do.
The secondary answer is that the reason it seemed to only work with brackets [] is because of the # sign.
select * from #WTF
is selecting off of your empty table variable, where as
select * from [#WTF]
is selecting off of the new physical table the select into created that was populated with data. The brackets are used to allow characters not normally allowed in a table or column name so their use here signifies you are looking for a table with the name #WTF instead of a variable named WTF.
All table variables are "physical" tables.
Your belief that they are "memory only" is a myth. They reside in tempdb and are shown in the metadata views with system generated names such as #4BAC3F29. The structure of a table variable is identical to a #temp table.
You cannot use SELECT ... INTO with table variables but can do with #temp tables. Your code just creates a new user table called #WTF in your user database as indicated in the other answers.