IF EXISTS does not drop the temp table - sql-server

This is probably a multipart question:
When I issue the statment
IF OBJECT_ID('temp..#tablename) IS NOT NULL --drop the table here
it does not drop the temp table. When I go look at the temp db, the name is something totally different...
#tablename___________________________________________00000001069F
Obviously, the drop statement wont work with this. How can I make sure that the temp table gets dropped with the above statement.
Also, if I use the "USE dbName" before the create temp table statement, does the temp table still get created in tempdb or the the dbName database? Is the default always tempDb?
Thanks,
RV.

use should use
OBJECT_ID('tempDB..#tablename')
not
OBJECT_ID('temp..#tablename')
does the temp table still get created in tempdb or the the dbName database? Is the default always tempDb?
YES
Temp Tables always gets created in TEMPDB..
Reason why you are seeing name like _____00000001069F is due to the fact that Temp tables are session specific and SQL takes care of assigning names to them,so that names won't conflict,even when they are used in parallel sessions with same names
Look out this answer on DBA.SE for more info,specifically look out Temp Tables section :
What's the difference between a temp table and table variable in SQL Server?

Related

Dropping temporary table in SQL Server 2012

I am using SQL Server 2012. When I want to create a temporary table named #TBL1, or rerun my code, I get this error:
There is already an object named '#TBL1' in the database
So I added this code to my query:
IF OBJECT_ID('dbo.#TBL1', 'U') IS NOT NULL
DROP TABLE dbo.#TBL;
But it shows the same error message
Please give me a clue is to what is wrong
You need to make sure OBJECT_ID looks in the right place. Temporary tables live in tempdb:
IF OBJECT_ID('tempdb.dbo.#TBL1', 'U') IS NOT NULL
BEGIN
DROP TABLE dbo.#TBL;
END
Also seems there is a typo (#TBL1 vs. #TBL).
And while I am normally am a big fan of schema prefixes, for #temp tables it’s not necessary and actually hampers readability IMHO.

How to find/see tempdb in SQL Server

Should I expect to be able to see tempdb tables in SSMS?
e.g. If I run this code, should I expect to be able to see the table in SSMS?
-- Drop the table if it already exists
IF (SELECT OBJECT_ID('tempdb..#TempPasswords')) IS NOT NULL
DROP TABLE #TempPasswords
CREATE TABLE #TempPasswords (
MemberNo INT,
Password nvarchar(120),
NewPassword varbinary(MAX)
)
Only if you run your code snippet in SSMS. In that session you will be able to execute
T-SQL that include your temp table.
In order to see temp tables globally use two hashes ##.
It is possible to see the temp DB but the name only. To see temp DB follow the instruction as per the image. After running the query right click on the Temporary Tables and Refresh .

Temporary Tables in SQL Server created and used inside a stored procedure

I'm creating a temporary table in a stored procedure. I understand that they get created and destroyed for each session, however something is not clear. Let's say two users access the web page where I call the stored procedure that creates the temporary table, would there be a conflict when the two users create the same temp table?
Thanks
If you create a local temp table (like #temp) then there is no problem. A global temp table (##Temp) however can be accessed by other sessions and as such I never use them unless I have no choice. From Books Online:
Local temporary tables are visible only to their creators during the
same connection to an instance of SQL Server as when the tables were
first created or referenced. Local temporary tables are deleted after
the user disconnects from the instance of SQL Server. Global temporary
tables are visible to any user and any connection after they are
created, and are deleted when all users that are referencing the table
disconnect from the instance of SQL Server.
Temporary tables are created per SQL connection so two users calling the same stored procedure would create an individual instance of the table in question.
The simplest way to demonstrate this is to run the following query in 2 seperate query windows:
select 1 as someid
into #temp
Each window will have it's own connection, so will create a unique temp table.
If you look in System Databases > TempDB > Temporary Tables (you may have to refresh the table list), you will see 2 tables uniquely named, something like:
#temp________xxx1
#temp________xxx2
If you then close one of the query windows and refresh the temp table list, you will see one table has been dropped.

SQL Server equivalent of MySQL Dump to produce insert statements for all data in a table

I have an application that uses a SQL Server database with several instances of the database...test, prod, etc... I am making some application changes and one of the changes involves changing a column from a nvarchar(max) to a nvarchar(200) so that I can add a unique constraint on it. SQL Server tells me that this requires dropping the table and recreating it.
I want to put together a script that will do the table drop, recreate it with the new schema, and then reinsert the data that was there previously all in one go, if possible, just to keep things simple for use when I migrate this change to production.
There is probably a good SQL Server way to do this but I'm just not aware of it. If I was using Mysql I would mysqldump the table and its contents, and use that as my script for applying that change to production. I can't find any export functionality in SQL server that will give me a text file consisting of inserts for all data in a table.
Use SQL Server's Generate Scripts command
right click on the database; Tasks -> Generate Scripts
select your tables, click Next
click the Advanced button
find Types of data to script - choose Schema and Data.
you can then choose to save to file, or put in new query window.
results in INSERT statements for all table data selected in bullet 2.
No need to script
here are two ways
1 use alter table ....alter column.....
example..you have to do 1 column at a time
create table Test(SomeColumn nvarchar(max))
go
alter table Test alter column SomeColumn nvarchar(200)
go
2 dump into a new table while converting the column
select <columns except for the columns you want to change>,
convert(nvarchar(200),YourColumn) as YourColumn
into SomeNewTable
from OldTable
drop old table
rename this table to the same table as the old table
EXEC sp_rename 'SomeNewTable', 'OldTable';
Now add your index

In SQL Server 2008 ,is it possible to disable auto drop of global temp table

Question 1: I am using a global temp tables in SQL Server 2008. But once my connection is closed this temp is dropped. Is there any way to disable auto drop
Question 2: If two connections are accessing same global temp table and another connection is
trying to delete that global temp table, does SQL Server handles this synchronization properly?
You can create your global temp tables in a stored procedure and mark it with the startup option.
SQL Server maintains a reference count greater than zero for all global temporary tables created within startup procedures.
some example code
CREATE PROC dbo.CreateGlobalTempTables
AS
CREATE TABLE ##my_temp_table
(
fld1 INT NOT NULL PRIMARY KEY,
fld2 INT NULL
);
GO
EXEC dbo.sp_procoption 'dbo.CreateGlobalTempTables', 'startup', 'true';
The global temporary table will be created automatically at startup and persist until someone explicitly drops it.
If you need a table to persist beyond the death of the connection that created it, you should just create a regular table instead of a temporary one. It can still be created in tempdb directly (geting you the benfits of simple logging and auto destruction on server restart) but it's name wouldn't be prefixed by ##.
DROP TABLE is a transactional statement that will block if there are any active connections using that table (with locks).
When the connection that created the ##GlobalTempTable ends, the table will be dropped, unless there is a lock against it.
You could run something like this from the other process to keep the table from being dropped:
BEGIN TRANSACTION
SELECT TOP 1 FROM ##GlobalTempTable WITH (UPDLOCK, HOLDLOCK)
...COMMIT/ROLLBACK
However, when the transaction ends, the table will be dropped. If you can't use a transaction like this, then you should use a permanent table using the Process-Keyed Table method.

Resources