Solved

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

Posted on 2013-06-06
9
560 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
  • 2
  • 2
  • 2
  • +3
9 Comments
 
LVL 20

Expert Comment

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

Open in new window

0
 
LVL 65

Assisted Solution

by:Jim Horn
Jim Horn earned 167 total points
Comment Utility
>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
Comment Utility
My bad. Misread the request.
0
 
LVL 4

Expert Comment

by:BAKADY
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 69

Expert Comment

by:ScottPletcher
Comment Utility
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 26

Expert Comment

by:Zberteoc
Comment Utility
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
Comment Utility
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 26

Assisted Solution

by:Zberteoc
Zberteoc earned 166 total points
Comment Utility
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:
ScottPletcher earned 167 total points
Comment Utility
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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

744 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now