I have few tables in my database and I want to count total rows of all those tables based on AppoitmentID for which I use a scalar cursor and a table variable to store some data of those tables based on AppoitmentID. After the end of cursor I count rows of table variable in which I had inserted data using dynamic query in cursor.
But it gives me the following error
Must declare the table variable "@ProcCount".
Is there any other way to get the count of all rows from necessary tables. Below is my Code :
Create FUNCTION [dbo].[ufn_GetProcedureCount]
(
)
RETURNS INT
AS
BEGIN
-- Declare the return variable here
DECLARE @MenuID bigINT, @TableName VARCHAR(150);
DECLARE @Result int
DECLARE @ProcCount TABLE (AppID INT, WoundId bigINT,TableName varchar(150));
DECLARE @sql nvarchar(2000)
DECLARE @Count int
DECLARE Cur_PendSign Cursor For
select Distinct MenuID,TableName from AppointmentTypeRequiredDocumnet A inner join Menu M on M.ID =A.MenuID where m.MenuGroupID = 8
OPEN Cur_PendSign
FETCH Cur_PendSign INTO @MenuID, @TableName
WHILE @@FETCH_STATUS=0
BEGIN
SET @sql='DECLARE @ProcCount TABLE (AppID INT, WoundId bigINT,TableName varchar(150))'
SET @sql=@sql+'INSERT INTO @ProcCount (AppID,WoundId)
SELECT TOP 1 V.AppointmentID, 1
FROM ['+@TableName+'] V WITH(NOLOCK)'
set @sql=@sql+ 'select count(*) from @ProcCount;'
--set @sql=@sql+ 'DECLARE @Count int'
EXECUTE sp_executesql @sql
FETCH Cur_PendSign INTO @MenuID, @TableName
END
CLOSE Cur_PendSign
DEALLOCATE Cur_PendSign
--set @Result = select count(*) from @ProcCount
RETURN @Result
END