views:

34

answers:

2

I am new to SQL Server and just joined a company where somebody had created the following stored procedure which I cannot understand.

I would like all of you to help me to understand what is going on in this procedure and what can be the alternate way of doing it.

Procedure [dbo].[SP_GetUserIncompleteCheckList]
(
@GroupID as int,
@BranchID as numeric)
As
Begin

Declare @DateStart as datetime
if @GroupID = 1 
begin
    set @DateStart = '08/31/2010' --'09/01/2010' 'Getdate()-30
end 
else
begin
    set @DateStart = Getdate()-30
end 

--Select ResponseDate,isNull(Submit,'Incomplete') as Status from CheckList_Response Where BranchID=@BranchID and isNull(Submit,'y') <> 'Complete' and Month(ResponseDate) = Month(GetDate()) and Year(ResponseDate) = Year(GetDate()) order by ResponseDate

declare 
@T table (ResponseDate Datetime,UserResponse int,DailyCount int,WeeklyCount int,MonthlyCount int,QuaterlyCount int,HalfYearlyCount int)

insert into @T (ResponseDate,UserResponse,DailyCount,WeeklyCount,MonthlyCount,QuaterlyCount,HalfYearlyCount) 
Select ResDate,
isNull((Select UserResponse from VUserResponseBranchGroupwise Where ResponseDate=A.ResDate AND CLGroup = @GroupID and BranchID = B.BranchID),0) as UserResponse,

(Select Count(CLID) From CheckList where Frequency = 'Daily' and CLGroup=@GroupID) as DailyCount,
Case Weekly
    When 1 Then (Select Count(CLID) From CheckList where Frequency = 'Weekly' and CLGroup=@GroupID) Else 0
    End as WeeklyCount,
Case Monthly
    When 1 Then (Select Count(CLID) From CheckList where Frequency = 'Monthly' and CLGroup=@GroupID) Else 0
    End as MonthlyCount,
Case Quaterly
    When 1 Then (Select Count(CLID) From CheckList where Frequency = 'Quarterly' and CLGroup=@GroupID) Else 0
    End as QuaterlyCount,
Case HalfYearly
    When 1 Then (Select Count(CLID) From CheckList where Frequency = 'Half Yearly' and CLGroup=@GroupID) Else 0
    End  as HalfYearlyCount
--isNull(Submit,'Incomplete') as Status
--,RoleStatus1,RoleStatus2,RoleStatus3,RoleStatus4,RoleStatus5 */
from dbo.CheckList_DateType A
,dbo.CheckList_Response B
Where A.ResDate=B.ResponseDate
AND B.ResponseDate > @DateStart
AND isNull(B.Submit,'Incomplete') <> 'Complete'
AND B.BranchID = @BranchID

Select ResponseDate,
case UserResponse 
    when 0 Then 'Incomplete'
    else 'Partial'
end as Status
from @T
Where UserResponse < (DailyCount+WeeklyCount+MonthlyCount+QuaterlyCount+HalfYearlyCount)
 order by ResponseDate

As far as I understand its a temporary table or something...

A: 

It is a table variable.

Have a look at

astander
+1  A: 

It's a variable of type TABLE

Same as:

DECLARE @COUNTER INT // variable of type INT  
DECLARE @STR VARCHAR(5) // variable of type STRING  
DECLARE @TAB TABLE(COLUMN1 INT) // variable of type TABLE  

You can assign values to variables using SET statements.
Example:

SET @COUNTER = 1;

But for tables, INSERT statement will do

INSERT INTO @TAB(COLUMN1) VALUES(123)
yonan2236