Skip to main content
2 of 5
added 760 characters in body
Kaishu
  • 517
  • 2
  • 12
  • 19

How to Insert/update table by calling function in it?

I have defined function with table value parameter which returns median as per values passed to it. Function defined as:

CREATE FUNCTION [dbo].[fn_GetMedian](@List TypeMedian READONLY)
RETURNS INT
AS
BEGIN
<function body>
END

And Table Type TypeMedian definition as:

CREATE TYPE [dbo].[TypeMedian] AS TABLE(
    [VALUE] [int] NULL
)

I have a table with certain column and wants to fill table with values.

All columns of table would filled by calculating SUM and MEDIAN of columns from another table.

So when I going to fill table I'm doing following operation for each column:

    DECLARE @tbl_Median TypeMedian

    INSERT INTO @tbl_Median
    SELECT L.Col1
    FROM @tbl_Listing L;
    
    UPDATE @tbl_Result
    SET Col1 = dbo.fn_GetMedian(@tbl_Median); --which returns `MEDIAN`

    DELETE FROM @tbl_Median
    INSERT INTO @tbl_Median
    SELECT L.Col2
    FROM @tbl_Listing L;

   UPDATE @tbl_Result
   SET Col2 = dbo.fn_GetMedian(@tbl_Median)
   .
   .
   .

Like above I'm doing this as for all column. How to do that in a single query instead of repeating update query for each column?

Eg.

CREATE TABLE LISTING(
ListingCol1 INT,
ListingCol2 INT,
ListingCol3 INT,
ListingCol4 INT,
ListingCol5 INT)

CREATE TABLE RESULT(
Col1 INT,
Col2 INT,
Col3 INT,
Col4 INT,
Col5 INT
)

DECLARE @tbl_Median TypeMedian

-- For first column insert

INSERT INTO @tbl_Median
SELECT ListingCol1
FROM Listing
    
INSERT INTO RESULT(Col1)
Values(dbo.fn_GetMedian(@tbl_Median))

-- For second column
DELETE FROM @tbl_Median

INSERT INTO @tbl_Median
SELECT ListingCol2
FROM Listing

UPDATE RESULT
SET Col2 = dbo.fn_GetMedian(@tbl_Median); --And this update I repeating for remaining columns
Kaishu
  • 517
  • 2
  • 12
  • 19