Code Generator | SQL

calculate_sum_function

This SQL script creates a function called calculate_sum that takes a table name and column name as input parameters and returns the sum of the specified column. It includes a usage example and unit testing with a sample table.


Empty image or helper icon

This Query related with thread "Data Analysis & AI Tool Insights"

Prompt

calculates the sum

Answer

/*
Function: calculate_sum
Description: This function calculates the sum of a column in a table
Parameters:
    - @table_name: Name of the table
    - @column_name: Name of the column to calculate sum
Returns: Sum of the specified column
*/

CREATE FUNCTION calculate_sum (@table_name VARCHAR(100), @column_name VARCHAR(100))
RETURNS INT
AS
BEGIN
    DECLARE @sum_result INT;

    SET @sum_result = (SELECT SUM(@column_name) FROM @table_name);

    RETURN @sum_result;
END;

Example of code usage:

SELECT dbo.calculate_sum('sales_table', 'amount') AS total_sales_amount;

Unit testing:

-- With a sample sales_table
CREATE TABLE sales_table (
    amount INT
);

INSERT INTO sales_table (amount) VALUES (100), (200), (300);

-- Calling the function
SELECT dbo.calculate_sum('sales_table', 'amount') AS total_sales_amount;
--Expected result: 600

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This SQL script creates a function called calculate_sum that takes a table name and column name as input parameters and returns the sum of the specified column. It includes a usage example and unit testing with a sample table.