The function is seeking to return an integer value that is equal to the sum of the values that appear before zeros in the column and add it to the final value in the column.
CREATE FUNCTION name
(@p1 NVARCHAR(MAX),
@p2 INT,
@p3 INT)
RETURNS INT
AS
BEGIN
DECLARE @total INT = 0
DECLARE @cnt INT = 1;
DECLARE @row INT = 0
DECLARE @nextRow INT = 0;
DECLARE @tmp NVARCHAR(MAX)
SET @tmp = @p1
DECLARE @myTemp TABLE (Col INT, ID1 INT, ID2 INT, reading NVARCHAR(MAX));
DECLARE @zeroCols TABLE(rn INT, Col INT);
INSERT INTO @myTemp
SELECT ROW_NUMBER() OVER(ORDER BY nHeatID) Col, col2, col3, @tmp
FROM schema.table
WHERE col4 = @p2
AND col5 = @p3
SET @total = (SELECT TOP 1 @tmp FROM @myTemp ORDER BY col DESC)
INSERT INTO @zeroCols
SELECT ROW_NUMBER() OVER(ORDER BY col) rn, col
FROM @myTemp
WHERE @tmp = 0
WHILE @cnt <= (SELECT COUNT(Col) FROM @zeroCols)
BEGIN
SET @row = (SELECT Col FROM @zeroCols WHERE rn = @cnt)
IF ((SELECT @tmp FROM @myTemp WHERE col = @row-1) <> 0)
SET @total = @total + (SELECT @tmp FROM @myTemp WHERE col = @row-1);
SET @cnt = @cnt + 1;
END;
RETURN @total
END;
The @myTemp
table place-holds data from my table with row numbers, the @zeroCols
table holds the row numbers where the zeros are.
Then I loop over that set of values and decide if there is a nonzero value before the zero at the column provided and if there is, i add it to the total.
This worked before I tried to make it into a function.
Is it not liking the fact that I'm passing in a nvarchar
as a column name?
And when I call it like so:
SELECT name('val', 0, 0)
I get this error:
Conversion failed when converting the nvarchar value 'val' to data type int