drop temp table but already founded 'There is already an object named '#temp' in the database' - sql-server-2012

in part of code need to make swap between two temp table when i make drop one table and reuse it i can't
create table #temp (id int)
create table #swap (id int)
drop table #temp
select * into #temp from #swap
drop table #swap
drop table #temp
i receive this error
Msg 2714, Level 16, State 1, Line 6
There is already an object named '#temp' in the database.

Just change out your logic flow a little. If all that matters is that #temp is empty when the INSERT happens, this should do what you need.
create table #temp (id int)
create table #swap (id int)
<Add loop logic here>
truncate table #temp
insert #temp(id)
select id from #swap
<Close out loop logic>
drop table #swap
drop table #temp
I also made the column names explicit. SELECT * is an accident waiting to happen in production code.

Related

How can I create table not declare column but copy from another?

I want to create a stored procedure to return all column data from a table except one column that key of where condition. The original table will be change a lot during my project, so I don't want to create table with declaring columns. How can I create the table that columns are copy of another table? I'm using SQL Server.
ALTER PROCEDURE [dbo].[SelectCharacterDataById]
#Id INT
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE #TempTable
AS
SELECT *
FROM dbo.CharacterData
WHERE CharacterID = #Id
ALTER TABLE #TempTable
DROP COLUMN CharacterID
SELECT *
FROM #TempTable
END

Multiple table Set-based insert with identity column in table1 and foreign key in table2 [duplicate]

This question already has an answer here:
T-SQL - Insert Data into Parent and Child Tables
(1 answer)
Closed 3 years ago.
I am writing an Application that imports configuration data from multiple external systems. To decouple the user-data from imported data y am using an intermediate table. The following tables are simplified for the sake of the argument.
table [connection] (generic connection information referenced by other tables not included)
table [importConfig] (Connection configuration from one of the external systems)
table [connectionImportConfig] (intermediate table, linking [connection] and [importConfig]
For each connection in [importConfig] I want to create a row in [connection] with an identity column. Then I want to insert the new IDs from [connection] together with the identifier from [importConfig] in [connectionImportConfig].
Constraint: I don't want to use a cursor. Must be a set-based solution.
The examples I have found on stackoverflow are either not set-based or I found them not applicable for other reasons.
T-SQL Insert into multiple linked tables using a condition and without using a cursor (not valid for multiple rows, using ##IDENTITY)
How to perform INSERT/UPDATE to Linking (Join) table which has FKs to IDENTITY PKs (not valid for multiple rows. Not telling how to join the identity values with the original data I want to insert)
I have tried a lot and am stuck at the point where I have to insert the new IDs into connectionImportConfig
-- Test tables&data (stripped down version)
CREATE TABLE connection (ConnectionID int identity(1,1) NOT NULL, comment nvarchar(max) null)
CREATE TABLE connectionImportConfig(connectionID int NOT NULL, ConfigCode nvarchar(50) NOT NULL)
CREATE TABLE importConfig (ConfigCode nvarchar(50) NOT NULL)
DECLARE #MyConnection table (ConnectionID int not null);
insert into importConfig values ('a')
insert into importConfig values ('b')
insert into importConfig values ('c')
-- Insert into PK-table creating the IDs
INSERT INTO connection (comment)
OUTPUT INSERTED.ConnectionID INTO #MyConnection
SELECT * from importConfig
-- How do I insert the new IDs together with the ConfigCode? 1 has to be replaced with the ID.
-- JOIN doesn't seem to work because there is no join condition to use
INSERT INTO connectionImportConfig (connectionID, ConfigCode)
SELECT 1, ConfigCode FROM ImportConfig
select * from #MyConnection
select * from connectionImportConfig
-- Cleanup
DROP TABLE importConfig;
DROP TABLE connection;
DROP table connectionImportConfig;
Have a look at this. I am sure you could loosely modify this to your needs. I don't typically like inserting right off the output but it really depends on your data. Hope this example helps.
IF OBJECT_ID('tempdb..#ImportConfig') IS NOT NULL DROP TABLE #ImportConfig
IF OBJECT_ID('tempdb..#Config') IS NOT NULL DROP TABLE #Config
IF OBJECT_ID('tempdb..#Connection') IS NOT NULL DROP TABLE #Connection
GO
CREATE TABLE #ImportConfig (ImportConfigID INT PRIMARY KEY IDENTITY(1000,1), ImportConfigMeta VARCHAR(25))
CREATE TABLE #Config (ConfigID INT PRIMARY KEY IDENTITY(2000,1), ImportConfigID INT, ConfigMeta VARCHAR(25))
CREATE TABLE #Connection (ConnectionID INT PRIMARY KEY IDENTITY(3000,1), ConfigID INT, ConnectionString VARCHAR(50))
INSERT INTO #ImportConfig (ImportConfigMeta) VALUES
('IMPORT_ConfigMeta1'),('IMPORT_ConfigMeta2')
;MERGE
INTO #Config AS T
USING #ImportConfig AS S
ON T.ConfigID = S.ImportConfigID
WHEN NOT MATCHED THEN
INSERT (ImportConfigID, ConfigMeta) VALUES (
S.ImportConfigID,
REPLACE(S.ImportConfigMeta,'IMPORT_','')
)
OUTPUT INSERTED.ConfigID, 'CONNECTION_STRING: ' + INSERTED.ConfigMeta INTO #Connection;
SELECT 'IMPORT CONFIG' AS TableName, * FROM #ImportConfig
SELECT 'CONFIG' AS TableName, * FROM #Config
SELECT 'CONNECTION' AS TableName, * FROM #Connection

Convert an existing Column to Identity

I have a table in SQL Server with bundle of records. I want to convert the ID column which is Primary Key to an identity Column without loss of data. I thought of the following two approaches:
Create a new table with identity & drop the existing table.
Create a new column with identity & drop the existing column.
but it's clear that they can not be implemented because keeping records is my first priority.
Is there another way to do this?
This solution violates your point 2, but there is no other way and I think your aim is to keep the old values, because nothing else makes sense...
You could do the following:
make it possible to insert into identity columns in your table:
set identity_insert YourTable ON
add a new ID column to your table with identity and insert the values from your old columns
turn identity insert off
set identity_insert YourTable OFF
delete old ID column
rename new column to old name
make it to the primary key
The only problem could be that you have your ID column already connected as foreign key to other tables. Then you have a problem with deleting the old column...
In this case you have to drop the foreign key constraints on your ID column after step 3, then do step 4 to 6 and then recreate your foreign key constraints.
As you are using SQL Server 2012, another possible alternative could be to create a sequence object that has a starting value of the highest ID +1 already in your table, then create a default constraint for your column using GET NEXT VALUE FOR and reference your sequence object you just created.
If you have direct access to the Server Database, just go into the design of the table, select the PK column, and change the identity to "Yes". Make sure you set your seed to the max value of that column. The increment is 1 by default. Save the table design and you should be good to go.
Considering the source table isn't too big:
Create new table (with IDENTITY)
Populate new table from existing table (with IDENTITY_INSERT ON)
Drop old table (drop any existing FKs first)
Rename new table to old name (re-establish FKs if needed)
-- Create Sample Existing Table
DROP TABLE IF EXISTS #tblTest
CREATE TABLE #tblTest
(
ID INT NOT NULL
, Val VARCHAR(10) NOT NULL
)
INSERT INTO #tblTest
(
ID
, Val
)
VALUES
(1, 'a')
, (2, 'b')
, (4, 'c')
GO
-- Create and Populate New Table (with IDENTITY_INSERT ON)
DROP TABLE IF EXISTS #tblTestNew
CREATE TABLE #tblTestNew
(
ID INT IDENTITY(1, 1) NOT NULL
, Val VARCHAR(10) NOT NULL
)
SET IDENTITY_INSERT #tblTestNew ON
INSERT INTO #tblTestNew
(
ID
, Val
)
(
SELECT
#tblTest.ID
, #tblTest.Val
FROM
#tblTest
)
SET IDENTITY_INSERT #tblTestNew OFF
GO
-- Rename Existing Table to Old (can use sp_rename instead, but I can't for temp tables)
SELECT * INTO #tblTestOld FROM #tblTest
DROP TABLE #tblTest
GO
-- Rename New Table to Existing (can use sp_rename instead, but I can't for temp tables)
SELECT * INTO #tblTest FROM #tblTestNew
DROP TABLE #tblTestNew
GO
-- Test Inserting new record
INSERT INTO #tblTest (Val)
VALUES ('d')
-- Verify Results
SELECT * FROM #tblTest
EXEC tempdb.sys.sp_help #objname = N'#tblTest'
-- Drop 'Old' Table (when ready)
DROP TABLE IF EXISTS #tblTestOld
-- Cleanup
DROP TABLE IF EXISTS #tblTest
DROP TABLE IF EXISTS #tblTestNew
DROP TABLE IF EXISTS #tblTestOld
If the table is very large, consider the log growth, Recovery Model, possible single-user mode, etc.
create table t1 (col1 int, col2 varchar(10))
insert into t1 values (10, 'olddata')
--add identity col
alter table t1 add col3 int identity(1,1)
GO
--rename or remove old column
alter table t1 drop column col1
--rename new col to old col name
exec sp_rename 't1.col3', 'col1', 'column'
GO
--add new test , review table
insert into t1 values ( 'newdata')
select * from t1

Drop a temporary table if it exists

I have two lines of code in SQL that create two tables on the fly, i need to do something like
IF TABLE EXISTS
DROP IT AND CREATE IT AGAIN
ELSE
CREATE IT
my lines are the following ones
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
how can I apply that concept for these two tables in my procedure?
From SQL Server 2016 you can just use
DROP TABLE IF EXISTS ##CLIENTS_KEYWORD
On previous versions you can use
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
You could also consider truncating the table instead rather than dropping and recreating.
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
Check for the existence by retrieving its object_id:
if object_id('tempdb..##clients_keyword') is not null
drop table ##clients_keyword
What you asked for is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)

Can I insert into a temp table the result of a stored procedure plus another value?

I have a temp table that needs the values of a Stored procedure. So the SP inserts 3 columns into the temp table, then I want to add a datetime to every row without modifying the SP.
Since I call the SP 3 times, each time with a different datetime, I can't just update the whole temp table.
Any Suggestions?
DECLARE #temp TABLE
(
id INT IDENTITY(1,1),
Name VARCHAR(150),
Address VARCHAR(25),
Date DATETIME
)
WHILE (#count>=#daysBack)
BEGIN
SET #date=DATEADD(dd, #count, GETDATE())
INSERT INTO #temp (Name,Address)
EXEC[dbo].StoredProc#date
--I Want to check for Null and insert the date there
Update #temp SET Date=#date WHERE Date=''
SET #count=#count-1
Yes. Create the temp table and in the added date column that does not have representation from your sproc put a default value constraint of getdate() or whatever date formula you need. In the insert statement specify the columns explicitly and omit the date column and it should work. As the rows are added the default value constraint will kick in and fill that column for you.
example:
create table #tmp (c1 int, c2 int, dt datetime default(getdate()) )
insert into #tmp
(c1, c2)
exec mysproc