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

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

Related

How to capture Output of SQL queries and

I have a Database and i want to execute few queries on it, and the results of the queries i.e. message, has to be comapared in my code if it is expected or not.
Please let me know how to capture the output of the SQL queries in any variable that can be used later in code for comparision.
Try the following Method :
Create a Table with the Same structure as of your Procedure output
Insert the Result of the SP Execution to the Table
Compare your Query result with the Table
Like this
CREATE PROCEDURE dbo.uSp_Temp
AS
SELECT
GETDATE() "MyDate"
DECLARE #T TABLE
(
MyDate DATE
)
INSERT INTO #T
EXEC uSp_Temp
SELECT
*
FROM #T
You can use Temp tables or temp variable to save the result set of a query.
Below is the sample for temp table
create table #temp (id int)
insert into #temp
select 1 as id
select * from #temp
Below is sample for Temp variable
declare #temp table (id int)
insert into #temp
select 1 as id
select * from #temp

How best to call a dynamic table

I have a script which is quite a beefy select statement and the format of it is as below.
It works perfectly well as a standalone script, but the local variable and temporary table restrictions in functions and views are preventing me from adding it to a database. What is the best way of creating this dynamic data which I can call in the FROM clause of a stored procedure without using functionality that was not available prior to SQL2005?
CREATE TABLE t1
(CARE_ID int NOT NULL,EVENT_DATE datetime NULL,EVENT_ID int NULL,EVENT_TYPE varchar(20))
CREATE TABLE t2
(CARE_ID int NOT NULL,EVENT_DATE datetime NULL,EVENT_ID int NULL,EVENT_TYPE varchar(20))
INSERT INTO t1
SELECT STATEMENT GOES HERE
INSERT INTO t2
SELECT STATEMENT GOES HERE
SELECT * FROM anotherTable
UNION
SELECT * FROM t1
UNION
SELECT * FROM t2
DROP TABLE t1
DROP TABLE t2
Microsoft introduced table variables with SQL Server 2000 as an alternative to using temporary tables.
DECLARE #T1 TABLE
(
CARE_ID int NOT NULL,
EVENT_DATE datetime NULL,
EVENT_ID int NULL,
EVENT_TYPE varchar(20)
)
INSERT INTO #T1
SELECT STATEMENT GOES HERE
These are perfectly suitable for use within a stored procedure.

Is it possible to create indexes on a temp table when using SELECT INTO?

I am loading data from a CSV file into a temp staging table and this temp table is being queried a lot. I looked at my execution plan and saw that a lot of the time is spent scanning the temp table.
Is there any way to create index on this table when I SELECT INTO it?
SELECT *
FROM TradeTable.staging.Security s
WHERE (
s.Identifier IS NOT NULL
OR s.ConstituentTicker IS NOT NULL
OR s.CompositeTicker IS NOT NULL
OR s.CUSIP IS NOT NULL
OR s.ISIN IS NOT NULL
OR s.SEDOL IS NOT NULL
OR s.eSignalTicker IS NOT NULL)
The table created by SELECT INTO is always a heap. If you want a PK/Identity column you can either do as you suggest in the comments
CREATE TABLE #T
(
Id INT IDENTITY(1,1) PRIMARY KEY,
/*Other Columns*/
)
INSERT INTO #T
SELECT *
FROM TradeTable.staging.Security
Or avoid the explicit CREATE and need to list all columns out with
SELECT TOP (0) IDENTITY(int,1,1) As Id, *
INTO #T
FROM TradeTable.staging.Security
ALTER TABLE #T ADD PRIMARY KEY(Id)
INSERT INTO #T
SELECT *
FROM TradeTable.staging.Security

Couldn't create temp table from select query if result empty

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

Inserting data into a temporary table

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;