?
Solved

I need help with using a temp table in a Stored Procedure in SQL SERVER 2008 R2

Posted on 2013-06-06
9
Medium Priority
?
575 Views
Last Modified: 2013-06-18
Hi Experts,
I have created a Stored Procedure in SQL Server 2008 R2.  I created a few @-variables and named them @Principal, @Interest, @TotalPrincipal,@TotalInterest.  In my stored procedure I loop through a Temp Table I created.  As I loop through the table I add @Principal to @TotalPrincipal, and I add @Interest to @TotalInterest.  Once I am done with the loop I want my Stored Procedure to return the @TotalPrincipal and @TotalInterest values.  How can I do this? Do I need another temp table?  I have included a sample of my code.  Thanks in advance for your help.  -mrotor :-)

Here's a sample of my code:


Create table #DataTemp
(      
      PK int Identity(1,1)
      Principal varchar(50),
      Interest varchar(50),
)
INSERT INTO #DataTemp(Principal,Interest)
SELECT  Principal, Interest FROM RecordTrans


DECLARE @COUNTRAWDATA int;
SELECT @COUNTRAWDATA = COUNT(*) FROM #DataTemp

DECLARE @intCounter int;
SET @intCounter = 1

DECLARE @PRINCIPAL float;
DECLARE @TOTALPRINCIPAL float;
DECLARE @INTEREST float;
DECLARE @TOTALINTEREST float;


WHILE @intCounter <= @COUNTRAWDATA
BEGIN

    SELECT @PRINCIPAL = Principal,
    @INTEREST = Interest
    FROM #DataTemp WHERE PK = @intCounter
      
      @TOTALPRINCIPAL = @TOTALPRINCIPAL + @PRINCIPAL
        @TOTALINTEREST = @TOTALINTEREST + @INTEREST

      --INCREMENT MY COUNTER
      SELECT @intCounter = @intCounter + 1
END
0
Comment
Question by:mainrotor
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +3
9 Comments
 
LVL 20

Expert Comment

by:dsacker
ID: 39226084
At the end of your stored proc, simply:
SELECT  Principal,
        Interest
FROM    #DataTemp

Open in new window

0
 
LVL 66

Assisted Solution

by:Jim Horn
Jim Horn earned 668 total points
ID: 39226086
>Once I am done with the loop I want my Stored Procedure to return the @TotalPrincipal and @TotalInterest values.  How can I do this?

CREATE PROC yourproc(@whatever as whatever)

-- Your SP code goes here.

-- Return recordset
SELECT @TotalPrincipal as TotalPrincipal, @TotalInterest as TotalInterest
GO
0
 
LVL 20

Expert Comment

by:dsacker
ID: 39226089
My bad. Misread the request.
0
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

 
LVL 4

Expert Comment

by:BAKADY
ID: 39226315
Do you really need help!!!


What are the data types of Principal and Interest from RecordTrans???
Are they numeric/float or char/varchar???
Have you consider I/O and other Performances???

All that you need is :

SELECT @TOTALPRINCIPAL = SUM(Principal), @TOTALINTEREST =  SUM(Interest) FROM RecordTrans GROUP BY 0;
GO

SELECT @TOTALPRINCIPAL as TotalPrincipal, @TOTALINTEREST as TotalInterest;
GO


Regards

NOTE: are Principal and Interest Text? if yes you need to convert them to numeric.


WRONG:

Create table #DataTemp
(      
      PK int Identity(1,1)
      Principal varchar(50),  <<<< WRONG DATA TYPE FOR NUMERIC OPERATIONS
      Interest varchar(50),  <<<< WRONG DATA TYPE FOR NUMERIC OPERATIONS
)
INSERT INTO #DataTemp(Principal,Interest)
SELECT  Principal, Interest FROM RecordTrans   <<<< WRONG: USE SUM(..) FUNCTION


DECLARE @COUNTRAWDATA int;   <<< YOU DON'T REALLY NEED THIS, SAVE MEMORY FOR IMPORTANT THINGS
SELECT @COUNTRAWDATA = COUNT(*) FROM #DataTemp

DECLARE @intCounter int;
SET @intCounter = 1

DECLARE @PRINCIPAL float;
DECLARE @TOTALPRINCIPAL float;
DECLARE @INTEREST float;
DECLARE @TOTALINTEREST float;

 
WHILE @intCounter <= @COUNTRAWDATA <<< YOU DON'T NEED THIS, SAVE PROCESSOR FOR IMPORTANT THINGS
FOR
BEGIN

    SELECT @PRINCIPAL = Principal,
    @INTEREST = Interest
    FROM #DataTemp WHERE PK = @intCounter <<< YOU DON'T NEED THIS EITHER , SAVE I/O HDD AND MEMORY FOR IMPORTANT THINGS
     
      @TOTALPRINCIPAL = @TOTALPRINCIPAL + @PRINCIPAL
        @TOTALINTEREST = @TOTALINTEREST + @INTEREST

      --INCREMENT MY COUNTER
      SELECT @intCounter = @intCounter + 1
END
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 39226826
Your original code is missing the "SET" keyword: SQL Server's T-SQL requires "SET" when setting a variable:
...
      SET @TOTALPRINCIPAL = @TOTALPRINCIPAL + @PRINCIPAL
      SET @TOTALINTEREST = @TOTALINTEREST + @INTEREST
...


But, even better, SQL allows you to do aggregating/summary functions -- such as SUM(), COUNT(), AVG() -- on an entire table or specified groupings of rows in the table.

For example, you can get the totals you want in this case using code like this:


DECLARE @COUNTRAWDATA int;
DECLARE @PRINCIPAL float;
DECLARE @TOTALPRINCIPAL float;
DECLARE @INTEREST float;
DECLARE @TOTALINTEREST float;

SELECT
    @COUNTRAWDATA = COUNT(*),
    @PRINCIPAL = SUM(Principal),
    @INTEREST = SUM(Interest)
FROM #DataTemp
0
 
LVL 27

Expert Comment

by:Zberteoc
ID: 39226965
This is a typical procedural programming approach in the database context. You have to understand that in SQL language you don't need to loop through every record in a table like in a recordset in an application. In SQL language you should avoid the loops except when there is no other way, which is really rare.

Your code is an example of resource wasting and poor performance. In order to sum columns all you need is to use aggregate functions and grouping feature, if you group by some subsets. All in all you don't even need a stored procedure because you can do the same with 1 simple select statement:

SELECT  SUM(Principal) as TotalPrincipal, SUM(Interest) as TotalInterest FROM RecordTrans

Open in new window

Maybe you also need some filter in a WHERE clause unless you really want to sum the entire table.
0
 

Author Comment

by:mainrotor
ID: 39227953
ScottPletcher,
I changed my code to   SET @TOTALPRINCIPAL = @TOTALPRINCIPAL + @PRINCIPAL

But when I do the SELECT at the end
SELECT @TOTALPRINCIPAL AS TotatPrincipal
GO

 I just get a NULL.

Why is that?
0
 
LVL 27

Assisted Solution

by:Zberteoc
Zberteoc earned 664 total points
ID: 39227971
Because the default value when you declare a variable is NULL and in SQL any operation with a null will have null as result. You have to initialize your variables with zero or even better do:

SET @TOTALPRINCIPAL = ISNULL(@TOTALPRINCIPAL,0) + ISNULL(@PRINCIPAL,0)

Open in new window


With the SUM function you don't have this problem because null values are ignored. However, I hope you understood the point of not using the loop and any variables and stored procedure for that matter. It completely unnecessary.
0
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 668 total points
ID: 39229423
You have to initialize the totals to 0 before you add to them.  Otherwise they start out as NULL, and anything added to NULL only returns NULL.


DECLARE @PRINCIPAL float;
DECLARE @TOTALPRINCIPAL float;
DECLARE @INTEREST float;
DECLARE @TOTALINTEREST float;

SET @TOTALPRINCIPAL = 0
SET @TOTALINTEREST = 0


WHILE @intCounter <= @COUNTRAWDATA
BEGIN

    SELECT @PRINCIPAL = ISNULL(Principal, 0),
        @INTEREST = ISNULL(Interest, 0)

    FROM #DataTemp WHERE PK = @intCounter
     
    SET @TOTALPRINCIPAL = @TOTALPRINCIPAL + @PRINCIPAL
    SET @TOTALINTEREST = @TOTALINTEREST + @INTEREST

      --INCREMENT MY COUNTER
      SELECT @intCounter = @intCounter + 1
END
0

Featured Post

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …
A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Suggested Courses

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question