SQL Server, Insert into table from select query? - sql-server

I would fill a table from a query in a stored procedure,
This works:
SELECT *
INTO #tmpTable
FROM MyTable
This works:
SELECT TOP (1) *
FROM MyTable
WHERE Land = #Land
but how do I fill #tmpTable with
SELECT TOP (1) *
FROM MyTable
WHERE Land = #Land

Because the #temp Table's scope is limited to its session (SPID), i.e. the Stored Procedure itself. After the SP execution completes the #temp table is Dropped.
Also while the SP is being executed you cannot see the #temp Table from other sessions (SPID)

USE Global temp table like ##temp even it can be accessible after execution of sp also

Related

SQL Server - View or Stored Proc to Union All On a Growing Table List

The SQL server has tables that all have the same structure. tableX_2016, tableX_2017, tableX_2018, tableX_2019, tableX_2020, tableX_2021.
I want a view that is simply:
select * from tableX_2016
union all select * from tableX_2017
union all select * from tableX_2018
union all select * from tableX_2019
union all select * from tableX_2020
union all select * from tableX_2021
However, I would like that view to automatically pick up tableX_2022, tableX_2023, etc., once they exist. The best would be to put all this data in one table (!), but unfortunately, I do not have the latitude to do that.
Is there a way to do this in a view? Or, a way to do it in a stored procedure and then somehow consume that stored procedure as if it were a view (use its output in CTEs, join to its output, etc)?
Thanks!
Database design seems poor. If you are keeping data in same database, it would be wise to handle by creating year or date column.
However, you can achieve your result by the given query
DROP TABLE IF EXISTS ##temp
SELECT * INTO ##temp FROM dbo.tableX_2016
TRUNCATE TABLE ##temp
EXEC sp_MSforeachtable
#command1 = 'INSERT INTO ##temp SELECT * FROM ?',
#whereand = 'AND OBJECT_NAME(OBJECT_ID) LIKE ''tableX_%'''
SELECT * FROM ##temp
Note that, sp_MSforeachtable is an undocumented stored procedure in SQL Server
PS: You can create view, stored procedure, etc. as per the need using above query

MSSQL server select into

I have a table with 20 millions rows and I need to create another table
off of it. but select into new table only inserts 100K records.
I have tried select into it and select table as
select * INTO #test
from dbo.log
New table should have 20 millions rows
Tables in temp db are very similar to the one available on regular databases. The table may be restricted with disk space available.
SELECT *
INTO #temp
FROM dbo.log
-- checking actual number of rows affected by query above
SELECT ##ROWCOUNT;
In addition to #gordy's ROWCOUNT suggestion, you could be looking at the wrong #temp table.
Consider:
select top 10 * into #foo from sys.objects
exec ('select * into #foo from sys.objects')
select count(*) from #foo
The nested batch creates a transient temp table called #foo that is destroyed at the end of the batch. This would happen calling a stored procedure too.

Checking whether value exists in results of a stored procedure

I have a stored procedure which returns a list of IDs for a particular set of generators I want to be able to then use the results of this stored procedure as part of another query.
Can I write a query like:
select * from table where id in (exec dbo.storedprocedurename)
Using table variable and JOIN you can achieve this. Store the procedure result into the table.
DECLARE #ProcOutput TABLE (Id INT);
INSERT INTO #ProcOutput (Id)
EXEC [dbo].[storedprocedurename]
SELECT T.*
FROM Table T
JOIN #ProcOutput O ON O.Id = T.Id
If the procedure returns multiple entries, according to the output you can re-design the table's schema.
If your output of procedure is 2 columns then you may try this:
INSERT INTO MyTable
(
Col1,
Col2
)
EXEC [dbo].[storedprocedurename]
GO
SELECT * FROM TABLE WHERE ID IN (SELECT Col1 from Mytable)

Temp table in Azure SQL Server returns error on second insert in Stored Procedure

I have a temp table declared in a stored procedure within an Azure SQL Server instance.
After declaring it with
WITH temp
(cols) AS
(SELECT * FROM goaltable
WHERE someCondition = true)
and utilizing it in a couple of INSERT statements, SQL Server returns an error on the second INSERT that invalid object name 'temp'.
Will I have to declare the table again before my second INSERT statement, or is there a better way to do it?
WITH key word is used to initialise a CTE (Comman Table Expression), it is not a Temporary Table.
Temp Tables are prefixed with a pound sign # or ##(Global Temp tables, google for the differences).
A CTE's scope is limited to the very first statement after the CTE has been initialised.
WITH CTE AS
( /* Your query here */)
SELECT FROM CTE --<-- Scope of above CTE
-- it maybe select , delete, update statement here
SELECT FROM CTE --<-- this statement is out of scope
-- this will return an error
Temp Tables
In your case if you want to create a temp table and use it on multiple places you would need to do something like this...
SELECT * INTO #Temp
FROM goaltable
WHERE someCondition = true
Now this #Temp table's scope is the connection in which it is created. You can select from it multiple times anywhere in this session.
for example the following queries will be executed without any errors as long as they are executed in the same connection.
SELECT TOP 10 * FROM #Temp
SELECT * FROM #Temp
Note
Even though the scope of the temp table is your session, yet it is a good practice to drop temp tables once you are done working with them.
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp

Temporary table in SQL Server - error occurs if the query takes long time to complete

Have a look a the following query.
select *
into TempTable
from MainTable
select * from TempTable
WAITFOR DELAY '00:00:10'
drop table TempTable
After executing this query, I open other window and execute the query:
select *
into TempTable
from MainTable
select * from TempTable
drop table TempTable
I get the following error:
There is already an object named 'TempBucket' in the database.
Suppose that it a part of the stored procedure, and it takes a long time to finish. If there's a second call to this stored procedure, this error will occur. How do I fix this error?
I assume you are using MSSQL DBMS by the tags against your post.
Use a genuine temp table: prefix the name of the table with '#'.
Using this method the temp table will exist only in the scope of the procedure within which it was created.
select *
into #TempTable
from MainTable
select * from #TempTable
No drop actually neccessary but is probably better practice.
Try this one -
IF OBJECT_ID (N'tempdb.dbo.#TempTable', 'U') IS NOT NULL
DROP TABLE #TempTable
SELECT *
INTO #TempTable
FROM dbo.MainTable
SELECT *
FROM #TempTable

Resources