Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5929659
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T14:27:04+00:00 2026-05-22T14:27:04+00:00

I have the following stored procedure that calculates the maximum values for multiple columns.

  • 0

I have the following stored procedure that calculates the maximum values for multiple columns. I have achieved the same result using a lengthy union select, however, I am just interested in the performance difference. Using a C# direction SQL parameter of either output or a return value, I would like to only return the value of the select statement marked “– NEED TO GET THIS VALUE RETURNED”.

I tried creating an OUTPUT variable, then using the SET syntax to store the value, then the RETURN syntax. But to no avail. Kept of getting errors that I need to create variables that are already there. I am not understanding the scope of the variables it seems. (I have removed that from the code in the meantime)

Here is my SP:

CREATE PROCEDURE sp_GetMaximumMax
  @FromDate DateTime,
  @ToDate DateTime,
  @TableName VarChar(150)
AS

DECLARE @SQL NVARCHAR(512), @ColumnName VARCHAR(150)
DECLARE @Result TABLE (Result int)

DECLARE read_cursor CURSOR FOR
   SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS  
   WHERE TABLE_NAME = @TableName 
     AND (column_name != 'id' AND column_name !='time' AND column_name !='no')

OPEN read_cursor;

FETCH NEXT FROM read_cursor INTO @ColumnName;

SET @SQL = 'SELECT MAX(['+@ColumnName+']) FROM '+@TableName+' WHERE [time] BETWEEN '''+CONVERT(VARCHAR, @FromDate, 120)+''' AND '''+CONVERT(VARCHAR, @ToDate, 120)+'''';

WHILE @@FETCH_STATUS = 0
BEGIN
Print @SQL
INSERT  @Result 
EXEC(@SQL);
FETCH NEXT FROM read_cursor
END

-- NEED TO GET THIS VALUE RETURNED
SELECT MAX(Result) AS MaxVar from @Result

CLOSE read_cursor;
DEALLOCATE read_cursor;

Herewith my revised code:

CREATE PROCEDURE sp_GetMaximumAvg

@FromDate DateTime,
@ToDate DateTime,
@TableName VarChar(150)

AS
CREATE TABLE #Fields(FieldName VARCHAR(150)) -- store column names
CREATE TABLE #Data(FieldName DECIMAL) -- store max values
DECLARE @ColumnName VARCHAR(150)
DECLARE @SQL VARCHAR(512)

-- add fields into field table
INSERT INTO #Fields (FieldName) SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS      WHERE TABLE_NAME = @TableName AND (column_name != 'id' AND column_name !='time' AND column_name !='no')

DECLARE @Field VARCHAR(150)
DECLARE @MyOutput INT
DECLARE ReadDaRow CURSOR

FOR SELECT * FROM #Fields

OPEN ReadDaRow
FETCH ReadDaRow INTO @Field
WHILE(@@FETCH_STATUS=0) BEGIN
SET @SQL = 'SELECT AVG(['+@Field+']) FROM '+@TableName+' WHERE [time] BETWEEN '''+CONVERT(VARCHAR, @FromDate, 120)+''' AND '''+CONVERT(VARCHAR, @ToDate, 120)+'''';
PRINT @SQL
INSERT INTO #Data EXEC(@SQL)
FETCH ReadDaRow INTO @Field
END

SELECT @MyOutput = MAX(FieldName) FROM #Data

RETURN @MyOutput

CLOSE ReadDaRow
DEALLOCATE ReadDaRow

DROP TABLE #Fields
DROP TABLE #Data

c# example of executing the SP:

SqlCommand GetMaxCmd = new SqlCommand("sp_GetMaximumAvg", SQLConnection);
GetMaxCmd.CommandType = System.Data.CommandType.StoredProcedure;
GetMaxCmd.Parameters.Add("@FromDate", SqlDbType.DateTime).Value =     DateTime.Parse(from_date);
GetMaxCmd.Parameters.Add("@ToDate", SqlDbType.DateTime).Value = DateTime.Parse(to_date);
GetMaxCmd.Parameters.Add("@TableName", SqlDbType.VarChar).Value = table_name;

SqlParameter Output = GetMaxCmd.Parameters.Add("@MyOutput", SqlDbType.SmallInt);
Output.Direction = ParameterDirection.ReturnValue;

try
{
    GetMaxCmd.ExecuteNonQuery();
    Max = Convert.ToInt32(Output.Value);
}
catch (NullReferenceException) { }
catch (FormatException) { }
catch (SqlException) { }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T14:27:04+00:00Added an answer on May 22, 2026 at 2:27 pm

    You can call NextResult() on a DataReader to retrieve the resultset of consecutive selects.

    EDIT: You can return it instead of a rowset:

    CLOSE read_cursor;
    DEALLOCATE read_cursor;
    
    RETURN (SELECT MAX(Result) AS MaxVar from @Result)
    

    This will end up in a parameter with direction System.Data.ParameterDirection.ReturnValue.

    Or you could read it with SqlCommand.ExecuteScalar().

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We have the following simple Stored Procedure that runs as an overnight SQL server
I have the following iBatis mapping for an Oracle Stored Procedure that returns a
So I have a stored procedure that does the following (modified out the data
I have the following stored procedure that I working on. I have noticed that
i have the following stored procedure that returns the sent emails of the latest
I have a stored procedure that runs the following: 'ALTER LOGIN ' + @Login
I have the following stored procedure that I am trying to convert to a
I have the following SQL stored procedure that when I try to save it,
Good Morning, I've written the following stored procedure that searches for records that have
I have created the following stored procedure.. CREATE PROCEDURE [dbo].[UDSPRBHPRIMBUSTYPESTARTUP] ( @CODE CHAR(5) ,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.