如何在存储过程中存储查询的结果

时间:2010-07-07 01:55:27

标签: sql sql-server-2005

假设我的存储过程中有这个很棒的查询。

Select * from Temp

我如何将结果存储在同一个存储过程中,因为在下一行中我想在循环中完成它(我不知道如何执行此操作)并对其执行操作。< / p>

我找到了类似的东西

 DECLARE total_count INT DEFAULT 0
 SET total_count = 10; 

但似乎不起作用。

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.

修改

好的,这就是我到目前为止所做的。我不知道我在做什么,所以我不知道这是否正确。

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

所以我认为这样做是因为它使得一些表变量然后将我的所有结果从临时表插入到这个temp2表变量中。然后我循环它们或类似的东西?

如果我拥有的东西到目前为止,我不会这样做。然后我找到了这个并且不确定这是否是下一步

declare @counter int

set @counter = 1

while @counter < (select max(idx) from @temp)
begin
    -- do what you want with the rows here
    set @counter = @counter + 1
end

临时表脚本

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

2 个答案:

答案 0 :(得分:2)

--Variable table @table
declare @table as Table (int i, ...)

insert into @table
Select * from Temp

--Temporary table #temp
create table #temp (int i, ...)

insert into #table
Select * from Temp

--Use it

--Finally
drop table #temp 

你找到的应该是:

DECLARE @total_count INT DEFAULT 0
SET @total_count = 10; 

变量以@

开头

有关差异的信息,我发现了articlestackoverflow question

答案 1 :(得分:0)

这是一个方便的模板,用于创建临时表,填充数据,然后由于某种原因光标浏览数据

-- create temp table
CREATE TABLE #tmp (field1 int, field2 varchar(10)) ON [PRIMARY]

-- populate temp table
insert into #tmp (field1, field2)

select  something1, something2
from    someTable

-- variables for cursor through temp table
declare @field1 int
declare @field2 varchar(10)

-- open cursor
declare myCursor Cursor for select field1, field2 from #tmp
open myCursor

-- get 1st row of data
fetch next from myCursor into @field1, @field2

-- loop through the data
while @@fetch_status = 0 begin
      -- do sumthin.. data is in @field1 and @field2
      -- get next row
      fetch next from myCursor into @field1, @field2
end

-- get rid of cursor
close myCursor
deallocate myCursor

-- drop temp table
drop table #tmp