Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 INSERT Statement using a SELECT Statement in a Stored Procedure

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2001-01-18 : 00:54:47
Stewart writes "Windows NT 4.0 sp6
SQL Server 7.0

I am really having trouble with a stored procedure that I want to use to display the results of a dynamic query. While I am fairly new to programming, I have worked with a number of seasoned programming professionals on this and no one could resolve the issue. The results should be paged in sets of 10 or what ever gets passed through the @RecsPerPage variable. I can get it to work if I don't include the INSERT statement, which blows the paging effect. Also, it works great in MS Query Analyzer. Here is the stored procedure:

--******This is the beginning of the stored procedure******
--The following Stored Procedure is a modified version of one taken from
--http://www.4guysfromrolla.com/webtech/062899-1.shtml on 12-20-00
CREATE PROCEDURE sp_PagedEquipment_sent
(
@Page int,
@RecsPerPage int,
@SearchCriteria char(255),
@SearchOrder char(50)
)
AS

-- We don't want to return the # of rows inserted
-- into our temporary table, so turn NOCOUNT ON
SET NOCOUNT ON

-- Find out where we will start our records from
DECLARE @RecCount int
SELECT @RecCount = @RecsPerPage * @Page + 1


--Create a temporary table
CREATE TABLE #TempItems
(
ID int IDENTITY,
EquipmentID int,
Picture char(50),
Category char(75),
myYear int,
Make char(15),
Model char(15),
Company char(10),
Availability char(15)
)

-- Create the dynamic sql statement
DECLARE @mySQL varchar(2000)
SELECT @mySQL = "SELECT EquipmentID, Picture, Category, myYear, Make, Model,
Company, Availability FROM EQUIPMENTLIST "
+ @SearchCriteria + " " + @SearchOrder

-- Insert the rows from tblItems into the temp. table
INSERT INTO #TempItems (EquipmentID, Picture, Category, myYear, Make, Model, Company, Availability)
EXEC(@mySQL)

-- Find out the first and last record we want
DECLARE @FirstRec int, @LastRec int
SELECT @FirstRec = (@Page - 1) * @RecsPerPage
SELECT @LastRec = (@Page * @RecsPerPage + 1)

-- Now, return the set of paged records, plus, an indiciation of we
-- have more records or not!
SELECT *,
MoreRecords =
(
SELECT COUNT(*)
FROM #TempItems TI
WHERE TI.ID >= @LastRec
)
FROM #TempItems
WHERE ID > @FirstRec AND ID < @LastRec


-- Turn NOCOUNT back OFF
SET NOCOUNT OFF

--**********This is the end of the stored procedure********

This is what gets passed to the stored procedure by the asp page:

exec sp_PagedEquipment_sent 1,10," WHERE Company = 'RA' "," ORDER BY Category"

I have used MS Profiler to double check that the above does indees get sent to the database.

I would really appreciate any assistance that you could provide."
   

- Advertisement -