I have a table which contains a column named WhereClause
DECLARE @UserGroups TABLE (WhereClause nvarchar(1000), totalCount int)
The table has been populated with some values for WhereClause
but none for totalCount
column.
An example of the WhereClause
is "FirstName is null".
Basically for each row in the table, I'd need to calculate the COUNT(*) from another table (Users) and set the totalCount
on the above table.
The below doesn't work:
SELECT UG.WhereClause, U.TotalCount
FROM @UserGroups as UG
OUTER APPLY (SELECT COUNT(*) as 'TotalCount' FROM [Users] WHERE UG.WhereClause)
) U
I tried creating a sql function and calling exec sp_executesql within the function but it's not supported.
CREATE FUNCTION [dbo].[fn_UserGroupCount]
(
@whereClause as NVARCHAR(1000)
)
RETURNS @returnValue TABLE (TotalCount INT)
AS
BEGIN
DECLARE @stmt nvarchar(1500)
SET @stmt = 'SELECT COUNT(*) FROM [dbo].[Users]
WHERE ' + @whereClause
Exec sp_executesql @stmt
RETURN
END
SELECT * FROM [dbo].[fn_UserGroupCount]('Subject is null')
How would that be possible to populate my @UserGroups
table as mentioned?
Thanks