The objective of the code is to run a query dynamically and return 0 if there are no rows with data present in the columns and to return 1 if there are rows with data in the columns. This is my code for the stored procedure:
ALTER proc [dbo].[usp_ColumnFieldValidator]
(
@TblName nvarchar(30),
@ColumnName nvarchar(30),
@RetVal bit output
)
as
begin
declare @CountOfRowsQuery as nvarchar(300)
set @CountOfRowsQuery = 'select count('+quotename(@ColumnName)+') from '+quotename(@TblName)+' having count(' +quotename(@ColumnName)+') = nullif(count('+quotename(@ColumnName)+'),0)'
execute sp_executesql @CountOfRowsQuery
select @RetVal = dbo.fn_ColumnValidator(@CountOfRowsQuery)
end
As you can see, a user-defined function is being called to set the value of @RetVal. This is my code for the user-defined function.
ALTER function [dbo].[fn_ColumnValidator]
(
@NullChecker as nvarchar(max)
)
returns bit
as
begin
declare @returnVar as bit
if @NullChecker is null
set @returnVar = 0
else
set @returnVar = 1
return @returnVar
end
The output of @RetVal is always 1 and I have attributed this error to @CountOfRowsQuery storing the entire string rather than the value of the query ie: @CountOfRowsQuery = null if the count of rows is zero else, @CountOfRowsQuery = the number of rows present in the column. To make things clearer I am attaching screenshots of the output when I run the program.
As you can see in list item.2, the sp returns null but the function_returned_value is being set to 1 instead of 0.