Hi
I have below query & i want to insert data into temp table
SQL
ALTER PROC [dbo].[USP_Test]
as
begin
SELECT SP.[ID]
,SP.[BookID]
,B.[BookTitle]
FROM [SessionBookPlanningHistoricalData] SP
JOIN [BookDetails] B
ON SP.BookID=B.[ID]
JOIN [StudentDetails] ST
ON SP.[StudentID]=ST.[LoginCode]
WHERE SP.[Deleted]=0
UNION ALL
SELECT T0.[ID]
,T0.[BookID]
,T0.[BookTitle]
FROM [SessionBookPlanningDetailed] T0
WHERE T0.[HistoricalDataCount]=0
EndThanks

Amit MohantyRank #112 · 20K reputationPosted Apr 27, 2023, 6:17 AM EDT
Check this
ALTER PROC [dbo].[USP_Test] AS BEGIN -- create a temporary table with the same columns as the query IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL DROP TABLE #TempTable CREATE TABLE #TempTable ( ID int, BookID int, BookTitle nvarchar(100) ) -- insert the data into the temporary table INSERT INTO #TempTable (ID, BookID, BookTitle) SELECT SP.[ID], SP.[BookID], B.[BookTitle] FROM [SessionBookPlanningHistoricalData] SP JOIN [BookDetails] B ON SP.BookID=B.[ID] JOIN [StudentDetails] ST ON SP.[StudentID]=ST.[LoginCode] WHERE SP.[Deleted]=0 UNION ALL SELECT T0.[ID], T0.[BookID], T0.[BookTitle] FROM [SessionBookPlanningDetailed] T0 WHERE T0.[HistoricalDataCount]=0 -- select the data from the temporary table SELECT * FROM #TempTable -- drop the temporary table DROP TABLE #TempTable END