Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to store results from a query while in a stored procedure
    text
    copied!<p>Say I have this great query in my stored procedure.</p> <pre><code>Select * from Temp </code></pre> <p>How would I store the results of this in the same stored procedure since in the next line I want to go through it in a loop(I don't know how to do this yet either) and do stuff to it.</p> <p>I found something like this </p> <pre><code> DECLARE total_count INT DEFAULT 0 SET total_count = 10; </code></pre> <p>but it seems like that does not work.</p> <pre><code>Msg 156, Level 15, State 1, Procedure csp_test, Line 3 Incorrect syntax near the keyword 'DECLARE'. Msg 155, Level 15, State 2, Procedure csp_test, Line 3 'INT' is not a recognized CURSOR option. </code></pre> <p><strong>Edit</strong></p> <p>Ok this is what I go so far. I have no clue what I am doing so I don't know if this is remotely right.</p> <pre><code>set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go ALTER PROCEDURE [dbo].[csp_test] AS BEGIN declare @temp2 table ( idx int identity(1,1), field varchar(max)) insert into @temp2 (field) Select * from temp END </code></pre> <p>So What I think this is doing is it makes some table variable then inserts all my results from temp table into this temp2 table variable. Then I loop through them or something like that?</p> <p>I don't if what I have is so far right. I then found this and not sure if this would be the next step</p> <pre><code>declare @counter int set @counter = 1 while @counter &lt; (select max(idx) from @temp) begin -- do what you want with the rows here set @counter = @counter + 1 end </code></pre> <p>Temp Table script</p> <pre><code>USE [test] GO /****** Object: Table [dbo].[temp] Script Date: 07/06/2010 19:20:34 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[temp]( [id] [int] IDENTITY(1,1) NOT NULL, [temp] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, CONSTRAINT [PK_temp] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload