I need to use CTE query inside from clause of SQL Query
See this example:
Drop Table #Temp
Drop Table #Temp2
Create Table #Temp(name1 text, name2 text)
Insert INTO #Temp Values ('test','test')
Insert INTO #Temp Values ('test','test')
select * into #Temp2
from #Temp
Select * from #Temp2
Here, I am just inserting rows into temp table 'Temp2' from selecting records from Temp... this is working fine...
But my need is, have to use CTE inside from clause.. like
select * into #Temp2
from (;With CTE as ( Select * from #Temp) select * from CTE)
Please don't encourage me to separate CTE query..because, I can't control that part of query since it is being provided by other system.
select * into #Temp2
from ("Query Provided by Other System")
So the "Query Provided by Other System" may or may not be the CTE query.
Check with below syntax, its worked for me and i hope you are looking for same:
With CTE as ( Select * from #Temp)
select * into #Temp2 from CTE
use below query
Create Table #Temp(name1 text, name2 text)
Insert INTO #Temp Values ('test','test')
Insert INTO #Temp Values ('test','test')
GO
With CTE as ( Select * from #Temp)
select * into #Temp2 from CTE
select * from #Temp2
GO
Drop Table #Temp
Drop Table #Temp2
I had a query script in SQL server management studio which is as below:
if OBJECT_ID('tempdb..#temp') IS NOT NULL
drop table #temp
select somecolumn into #temp from sometable where somecondition
if OBJECT_ID('tempdb..#temp') IS NOT NULL
drop table #temp
select somecolumn2 into #temp from sometable2 where somecondition2
I add the drop table line to ensure the #temp table is cleaned from the cache. However, for repeated running the script, I still got error as "here is already an object named '#temp' in the database." in the second select line. It seems that the drop table didn't take effect as I wish.
if OBJECT_ID('tempdb..#temp') IS NOT NULL
drop table #temp
select somecolumn into #temp from sometable where somecondition
GO --<-- Separate these two block with a batch separator
if OBJECT_ID('tempdb..#temp') IS NOT NULL
drop table #temp
select somecolumn2 into #temp from sometable2 where somecondition2
I want to crate a temp table from select query (My table has many columns, therefore I don't want to create the temp table manually)
I use the following query:
SELECT * INTO #TempTable
FROM MyTable
WHERE ...
If this query return empty rows, it won't create #TempTable. Hence, I cannot use this #TempTable for the next queries.
Is there a way to resolve this?
If the query SELECT * FROM MyTable WHERE ... in your code you posted:
SELECT *
INTO TempTable
FROM MyTable WHERE ...
returned no rows, it will create an empty TempTable, but it won't fill any data in it if there is no rows matched the WHERE clause. But it should create the table TempTable at least with the same structure as the MyTable and it will be empty.
For example this:
SELECT * INTO TempTable FROM MyTable WHERE 1 <> 1;
Will always create an empty table TempTable with the same structure as MyTable since the predicate 1 <> 1 is always false.
However you can declare it like so:
DECLARE #Temp TABLE(Field1 int, ...);
This is because you are dynamically creating and populating temporary table and not creating it explicitly.In such scenario, you must check the existence of the temp table in the beginning before you create one.
Try this:
IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL
BEGIN
DROP TABLE #TempTable
END
SELECT * INTO #TempTable FROM MyTable
Select * From #TempTable
your query
SELECT * INTO #TempTable
FROM MyTable
WHERE ...
will create an empty table if the select returns no rows
I want to transfer all data from one table into another with the following code:
INSERT INTO tblpremier
SELECT * INTO #TempTable
FROM dbo.IntermediateTable
ALTER TABLE #TempTable
DROP COLUMN id
SELECT * FROM #TempTable
And I get an error
Incorrect syntax near the keyword 'INTO'
at the second line of this code. Any help?.
What you've written doesn't make any sense. The first "statement" is this:
INSERT INTO tblpremier
SELECT * INTO #TempTable
FROM dbo.IntermediateTable
Now are you inserting into #temptable, or tblpremier? I'm guessing you wanted to perform all these operations and then insert into tblpremier - in which case split it into separate statements. I'm guessing you wanted to do:
SELECT * INTO #TempTable
FROM dbo.IntermediateTable
ALTER TABLE #TempTable
DROP COLUMN id
INSERT INTO tblpremier
SELECT * FROM #TempTable
But rather than need #Temptable which is the same as IntermediateTable minus the ID column, why not just select the correct columns you need from IntermediateTable in the first place rather than using *?
Edit:
Here's what I meant. Write the insert statement so you've got all the column names specified, and don't include the ID column. You'll get all new ID numbers on the copy of the table.
INSERT INTO tblpremier (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM IntermediateTable
However, if you wanted to to keep the same ID numbers in the copy of the table, and the columns are in the same order on both intermediate table and tblpremier, then you could write:
SET IDENTITY_INSERT tblpremier ON
INSERT INTO tblpremier
SELECT *
FROM IntermediateTable
SET IDENTITY_INSERT tblpremier OFF
But you would still need to watch out for trying to insert duplicate IDs if tblpremier isn't empty at first.
You cannot use both INSERT INTO TABLE SELECT FROM and SELECT INTO at the same time. You should break that statement into
INSERT INTO tblpremier
SELECT * FROM dbo.IntermediateTable
SELECT * INTO #TempTable
FROM dbo.IntermediateTable
ALTER TABLE #TempTable
DROP COLUMN id
SELECT * FROM #TempTable
You have both a SELECT INTO and INSERT INTO in the same statement.
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;