SQL Server 2012 temp table OBJECT_ID issue - sql

We have an issue upgrading to SQL Server 2012. I am using the following script to create temporary tables that used to work fine on SQL Server 2008 R2 but now it is generating an error with 2012:
if (OBJECT_ID( 'tempdb..#idstable') > 0)
truncate table #idstable
else
create table #idstable (id int not null)
the error thrown is
There is already an object named '#idstable' in the database.
This is obviously not thrown the first time I use the script (in the same transaction).
Any idea? Thank you!

In SQL Server 2012, #temp tables are created with a negative object_id, so your script won't work as is. The safest way is:
IF OBJECT_ID( 'tempdb..#idstable') IS NOT NULL
(I blogged about this here, and knew it would catch someone.)
Though your script is bound for failure anyway, if it is part of a single batch. The parser will not let you try and create the same #temp table twice.

Try this:
IF OBJECT_ID (N'tempdb..#idstable', N'U') IS NOT NULL
truncate table #idstable
else
create table #idstable (id int not null)

My dears,
This issue is due to the truncate statement. Truncate is used to delete all records preserving the table. Use drop table instead of truncate table and this will works fine ;-)

Related

What is the process during re-naming and re-creating a MS-SQL table using stored procedure?

I have a table called myTable where continuous insertion is happening. I will rename that table by myTable_Date and create a new table, myTable through a Store Procedure.
I want to know what will happen during re-naming and re-creating the table, will it drop any packet?
SQL Server has sp_rename built in if you just want to change the name of a table.
sp_rename myTable, myTable_Date
Would change the name from myTable to myTable_Date
But it only changes the name reference in sys.Objects so make sure any references are altered and read the documentation about it :)
The Microsoft doc for it is HERE
When you rename the myTable to myTableDate, myTable won't exist anymore so if someone tries to insert something inside myTable it will fail.
When you create new myTable with the same name and columns everything will be fine and the insertion process will continue.
I suggest you to make a little script renaming the table and creating new one. Something like this:
sp_rename myTable, myTable_Date
GO
CREATE TABLE myTable(
-- Table definition
)
When you rename the table you will get warning like this: "Caution: Changing any part of an object name could break scripts and stored procedures." so you better create the new table fast.
Other option is you create a table exact like myTable and insert all data from myTable there and then can delete them from myTable. No renaming, no dropping and insertion process will not be interrupted.
I want to know what will happen during re-naming and re-creating the
table, will it drop any packet?
Inserts attempted after the table is renamed will err until the table is recreated. You can avoid that by executing the tasks in a transaction. Short term blocking will happen if an insert is attempted before the transaction is committed but no rows will be lost. For example:
CREATE PROC dbo.ReanmeMytableWithDate
AS
DECLARE #NewName sysname = 'mytable_' + CONVERT(nchar(8), SYSDATETIME(), 112);
SET XACT_ABORT ON;
BEGIN TRY;
BEGIN TRAN;
EXEC sp_rename N'dbo.mytable', #NewName;
CREATE TABLE dbo.mytable(
col1 int
);
COMMIT;
END TRY
BEGIN CATCH
THROW;
END CATCH;
GO
I don't know your use case for renaming tables like this but it seems table partitioning might be a better approach as #Damien_The_Unbeliever suggested. Although table partitioning previously required Enterprise Edition, the feature is available in Standard Edition beginning with SQL Server 2016 SP1 as well as Azure SQL Database.

How to drop a table in SQL Server 2008 only if exists

Our company is migrating one of its products from SQL Server 2005 to 2008, and in the logs I've noticed excess of errors about deleting tables if it does not exist. In SQL Server 2005 we had this to delete tables
IF OBJECT_ID('dbo.Units', 'U') IS NOT NULL
DROP TABLE dbo.Units
which doesn't seem to work anymore.
What would be the proper way of deleting a table only if it exists in SQL Server 2008?
This should do it!
IF EXISTS
(SELECT
TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TableToDrop')
DROP TABLE TableToDrop
This code works on my SQL Server 2012:
IF OBJECT_ID('t', 'U') IS NOT NULL DROP TABLE t
CREATE TABLE t(id int)
Maybe your name is wrong (e.g. case sensitive collation on new installation?). What kind of error you are getting?
Note that in SQL Server 2016 you can use DROP IF EXISTS:
DROP TABLE IF EXISTS t
CREATE TABLE t(id int)

Create Database and Table Conditionally

I'm trying to write a small script to create a database if it doesn't exist, and create a table for that database if the table doesn't exist. What I have is this:
IF (db_id('db') is null) BEGIN
print 'Must create the database!';
CREATE DATABASE db;
END
USE db;
IF (object_id('test_table', 'U') is null) BEGIN
print 'Must create the table!';
CREATE TABLE test_table (
id int
);
END
I'm getting a strange error with this:
Database 'db' does not exist. Make sure that the name is entered correctly.
I'm guessing that it's parsing the script before running it and finding that 'db' doesn't exist, so it can't use it.
There must be a solution to this. Any help is appreciated.
SOLVED!
I realised 5 minutes after posting that the GO keyword solves the problem. Here is the fixed code:
IF (db_id('db') is null) BEGIN
print 'Must create the database!'
CREATE DATABASE db;
END
GO
USE db
IF (object_id('test_table', 'U') is null) BEGIN
print 'Must create the table!';
CREATE TABLE test_table (
id int
);
END
Sorry for wasting everyone's time.
SQL statements are parsed as one batch unless you break them apart. In SQL Server, you can use GO to do this. In both MySQL and SQL Server, you can use BEGIN and END.
If you want to commit the separate blocks to the database in different instances you can use BEGIN TRANS / COMMIT TRANS and START TRANSACTION / COMMIT for SQL Server and MySQL, respectively.
Something along the lines of Check if table exists in SQL Server would probably work (With a slight change)
IF (NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END
I might suggest using the built-in SQL syntax -
CREATE DATABASE name IF NOT EXISTS;
And subsequently
CREATE TABLE name(definition) IF NOT EXISTS;

SQL Import/Export wizard not allowing Create Table #temp

Through the Import/Export wizard (2008 R2) I'm trying to get data from a View and do some joins with it and put the data in a temp table then do a final select statement at the bottom.
But I keep getting a message saying that my first temp table definition is invalid.
Here's the def:
Create Table #CT (Code int, Col1 varchar(75), Col2 varchar(75), Col3 int)
INSERT INTO #CT
SELECT *
FROM...
I know this is good because I can run it directly on the server without problems.
Is it that Imp/Exp wiz doesn't allow these kinds of queries, where there's complex statements?
At the top of your SQL code, try adding set fmtonly off.
In some circumstances, SQL Server tries to determine the metadata for a query without actually running the query... but, this doesn't play well with temp tables. Adding set fmtonly off instructs it to actually execute the query to get the metadata.

Why are temporary tables not removed from tempdb in SQL Server?

I have created one stored procedure with 7 temporary tables and each temp table is dropped at the end of their own work.
I am calling the SP from one web service and same web service we are used for different instance.
I have dropped every temp table forcefully but when SP executes it will not delete any of the temporary table which are located in "tempdb/Temporary Table". And, when I open new instance of my application and try to execute same SP it will modify same temp tables.
This creates problem for me. it will lock the tables when SP execute simultaneously it will lock the table and my sp is not able to produce result and throw exception.
So I want to drop my temporary tables at the end of my operation. please help.
I can't tell you why this is happening, but I have dealt with it before as well.
Try cleaning up your tables at the beginning or end of the SP or using table variables.
IF object_id('tempdb..#TableName') IS NOT NULL DROP TABLE #TableName
This can occur in case if you have used many Temp tables and you have some Error in between of Your sp and your drop statement could not executed.
So its always best practice to use
IF object_id('tempdb..#TableName') IS NOT NULL DROP TABLE #TableName
in start of SP.
To force dropping of temp tables use
BEGIN TRY DROP #MyTable END TRY BEGIN CATCH END CATCH
Ugly but effective. Use a separate TRY for each temporary table.
IF object_id('tempdb..#TableName') IS NOT NULL DROP TABLE #TableName
I think this will not work as we know sql server store temp table name with adding some extra character.
if exists(select 1 from tempdb.sys.tables where name like '#TableName%')
DROP TABLE #TableName