Inserting data into a temporary table - sql

After having created a temporary table and declaring the data types like so;
CREATE TABLE #TempTable(
ID int,
Date datetime,
Name char(20))
How do I then insert the relevant data which is already held on a physical table within the database?

INSERT INTO #TempTable (ID, Date, Name)
SELECT id, date, name
FROM physical_table

To insert all data from all columns, just use this:
SELECT * INTO #TempTable
FROM OriginalTable
Don't forget to DROP the temporary table after you have finished with it and before you try creating it again:
DROP TABLE #TempTable

SELECT ID , Date , Name into #temp from [TableName]

My way of Insert in SQL Server. Also I usually check if a temporary table exists.
IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP Table #MyTable
SELECT b.Val as 'bVals'
INTO #MyTable
FROM OtherTable as b

SELECT *
INTO #TempTable
FROM table

I have provided two approaches to solve the same issue,
Solution 1: This approach includes 2 steps, first create a temporary table with
specified data type, next insert the value from the existing data
table.
CREATE TABLE #TempStudent(tempID int, tempName varchar(MAX) )
INSERT INTO #TempStudent(tempID, tempName) SELECT id, studName FROM students where id =1
SELECT * FROM #TempStudent
Solution 2: This approach is simple, where you can directly insert the values to
temporary table, where automatically the system take care of creating
the temp table with the same data type of original table.
SELECT id, studName INTO #TempStudent FROM students where id =1
SELECT * FROM #TempStudent

After you create the temp table you would just do a normal INSERT INTO () SELECT FROM
INSERT INTO #TempTable (id, Date, Name)
SELECT t.id, t.Date, t.Name
FROM yourTable t

The right query:
drop table #tmp_table
select new_acc_no, count(new_acc_no) as count1
into #tmp_table
from table
where unit_id = '0007'
group by unit_id, new_acc_no
having count(new_acc_no) > 1

insert into #temptable (col1, col2, col3)
select col1, col2, col3 from othertable
Note that this is considered poor practice:
insert into #temptable
select col1, col2, col3 from othertable
If the definition of the temp table were to change, the code could fail at runtime.

Basic operation of Temporary table is given below, modify and use as per your requirements,
-- CREATE A TEMP TABLE
CREATE TABLE #MyTempEmployeeTable(tempUserID varchar(MAX), tempUserName varchar(MAX) )
-- INSERT VALUE INTO A TEMP TABLE
INSERT INTO #MyTempEmployeeTable(tempUserID,tempUserName) SELECT userid,username FROM users where userid =21
-- QUERY A TEMP TABLE [This will work only in same session/Instance, not in other user session instance]
SELECT * FROM #MyTempEmployeeTable
-- DELETE VALUE IN TEMP TABLE
DELETE FROM #MyTempEmployeeTable
-- DROP A TEMP TABLE
DROP TABLE #MyTempEmployeeTable

INSERT INTO #TempTable(ID, Date, Name)
SELECT OtherID, OtherDate, OtherName FROM PhysicalTable

insert #temptable
select idfield, datefield, namefield from yourrealtable

All the above mentioned answers will almost fullfill the purpose. However, You need to drop the temp table after all the operation on it. You can follow-
INSERT INTO #TempTable (ID, Date, Name)
SELECT id, date, name
FROM physical_table;
IF OBJECT_ID('tempdb.dbo.#TempTable') IS NOT NULL
DROP TABLE #TempTable;

Related

how to see difference between 2 tables

I have 2 tables: 1 temp and the other one is my main table.
Each day I would update my temp table and I want to update my main table based on the changes I made from the temp table.
Example: The first temp table contains an id and name. Then I insert the value from temp into the main table. But when I made changes from my temp like insert another id and name, I want my main table to compare and only insert the unique id from the temp table.
As you said, it seems like you have a table object named as temp table. If this is the case then you may use after insert trigger on temp table to insert new inserted value in your main table.
CREATE TRIGGER AfterINSERTTrigger on [Temptable]
FOR INSERT
AS DECLARE #id INT,
#col1 VARCHAR(50),
.
.
SELECT #id = ins.id FROM INSERTED ins;
SELECT #col1 = ins.col1 FROM INSERTED ins;
.
.
INSERT INTO [MainTable](
[id]
,[col1]
.
.)
VALUES (#id,
#col1,
.
.
.
);
PRINT 'We Successfully Fired the AFTER INSERT Triggers in SQL Server.'
GO
Similarly you can update your table on update of record in temptable using update trigger. You may find this link on more info on trigger. LINK
OR
If you are creating temp table object to get the new inserted record then use simple not in or not exists clause to get the newly inserted record.
Using NOT IN
insert into maintable ( id, col1, ...)
select Id , col1, .... from temptable
where id not in (select id from maintable)
Using NOT EXISTS
insert into maintable ( id, col1, ... )
select id, col1, ... from temptable as temp
where not exists (select id from maintable as main where main.id=temp.id)
You can use NOT EXISTS as follows
INSERT into main_table(
id, name,
...
)
SELECT
id,name,
...
FROM temp_table t
WHERE
NOT EXISTS(
SELECT 1
FROM main_table m
WHERE m.id = t.id
)
Cheers!!

Multiple Drop table statement in a query fails

I have a temp table which needs to be recreated with different where conditions. Even though I have a drop statement for the temp table the query fails when executed, is there any way to overcome this issue. Please find the below example for better clarity. any help is much appreciated.
drop table if exists table1;
create table table1(id int)
insert into table1 values (2),(3)
drop table if exists #temp;
select * into #temp from(select * from table1 where id=2)a;
drop table if exists #temp;
select * into #temp from(select * from table1 where id=3)a;
Try using this. It is good practice to use GO to make batches of your query.
drop table if exists table1;
go
create table table1(id int)
insert into table1 values (2),(3)
go
drop table if exists #temp;
go
select * into #temp from table1 where id=2;
go
drop table if exists #temp;
go
select * into #temp from table1 where id=3;

Multi column exist statement

I am trying to insert data to a table from another where data is not already exists
The table I am inserting the data into
CREATE TABLE #T(Name VARCHAR(10),Unit INT, Id INT)
INSERT INTO #T
VALUES('AAA',10,100),('AAB',11,102),('AAC',12,130)
The table I am selecting the data from
CREATE TABLE #T1(Name VARCHAR(10),TypeId INT,Unit INT, Id INT)
INSERT INTO #T1
VALUES('AAA',3,10,100),('AAA',3,10,106)
In this case I want to select ('AAA',3,10,106) from #T1 because AAA,106 combination not exists in #T
Basically what I want is to populate unique Name and Id combination
I tried below which doesn't seems to work
SELECT *
FROM #T1
WHERE NOT EXISTS(SELECT * FROM #T)
You have to somehow correlate the two tables:
SELECT *
FROM #T1
WHERE NOT EXISTS(SELECT *
FROM #T
WHERE #T1.Name = #T.Name AND #T1.ID = #T.ID)
The above query essentially says: get me those records of table #T1 which do not have a related record in #T having the same Name and ID values.
Your best bet is probably to use a insert statement with a subquery. Something like this:
SQL Insert Into w/Subquery - Checking If Not Exists
Edit: If you're still stuck, try this--
INSERT INTO #T (Name, Unit, Id)
SELECT Name, Unit, Id
FROM #T1
WHERE
NOT EXISTS (SELECT Name, Unit, Id FROM #T
WHERE #T.Name = #T1.Name AND #T.Unit = #T1.Unit AND #T.Id = #T1.Id)

SQL Insert into Temp Table With Serial Number

I have a simple SQL Query like:
Select Distinct GroupCode
Into #TempTable
From MyTable
SELECT * FROM #TempTable
drop Table #TempTable
And its OutPut is as
Now, I also want a Serial Number Column like 1,2,3.... there in the Out put.
How can I achieve that?
Thanks
Just add row_number():
select row_number() over (order by (select NULL)) as id, GroupCode
into #TempTable
from (select distinct GroupCode from MyTable) t;
select *
from #TempTable;
drop Table #TempTable;
You can explicitly create the temp table and add an IDENTITY column for your serial numbers, like so:
create table #tmp(id int identity(1,1), groupcode uniqueidentifier)
insert into #tmp (groupcode)
Select Distinct GroupCode
from mytable
select * from #tmp
order by id
drop table #tmp

How can I create two temporary tables with the same structure without write twice?

How can I create two temporary tables with the same structure without write twice?
Something like that:
DECLARE #TEST_TABLE1, #TEST_TABLE2 TABLE
(
FIELD1 INT,
FIELD2 INT
)
and NO:
DECLARE #TEST_TABLE1 TABLE
(
FIELD1 INT,
FIELD2 INT
)
DECLARE #TEST_TABLE2 TABLE
(
FIELD1 INT,
FIELD2 INT
)
These are not "temp tables", a temp table is CREATE TABLE #TempTable(x int)
to make this work for true table tables, try:
CREATE TABLE #TempTable(x int)
insert into #TempTable values(5) --test data to show no data copied to new table
select * into #tempTable2 from #TempTable where 1=2
select * from #TempTable
select * from #TempTable2
These are table vaiables (#tableVariable) and you have to declare each variable, there is no way around it.
The only very non-standard way I can think this may work is to just write to the sys.tables directly, but you would still have to do two inserts, but you are doing the tables at the same time.
That may not be what you want, but short of using a stored procedure, and making one call from your app, and two on the database I can't think of any other solution.
Create the first temp table, then select into a second temp table:
-- Create first temp table
CREATE TABLE #TEST_TABLE1
(
FIELD1 int
,FIELD2 int
)
-- Select into second temp table
SELECT *
INTO #TEST_TABLE2
FROM #TEST_TABLE1
-- Vet existence of both temp tables
SELECT * FROM #TEST_TABLE1
SELECT * FROM #TEST_TABLE2