CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_SecGetOrgFeaturesAndActions
  @p0 INT
AS
  select A.WSEC_FEA_ACT_ID, 
         CV1.CONV_STRING as WSEC_ACTION_NAME, 
         A.WSEC_FEA_ACT_PARENT, 
         CV2.CONV_STRING as WSEC_FEATURE_NAME, 
         WSEC_ALLOW, 
         WSEC_DENY 
    from MSP_WEB_SECURITY_FEATURES_ACTIONS A, 
         MSP_WEB_SECURITY_FEATURES_ACTIONS B,
         MSP_WEB_SECURITY_ORG_PERMISSIONS  C,
         MSP_WEB_CONVERSIONS CV1,
         MSP_WEB_CONVERSIONS CV2
   where A.WSEC_FEA_ACT_PARENT=B.WSEC_FEA_ACT_ID 
     and A.WSEC_FEA_ACT_ID=C.WSEC_FEA_ACT_ID 
     and C.WSEC_ACCESS=1 
     and A.WSEC_FEA_ACT_ID not in (102, 740)
     and A.WSEC_FEA_ACT_NAME_ID=CV1.CONV_VALUE  and CV1.LANG_ID=@p0
     and B.WSEC_FEA_ACT_NAME_ID=CV2.CONV_VALUE  and CV2.LANG_ID=@p0
   order by A.WSEC_FEA_ACT_ID
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_SecGetOrgFeaturesAndActions TO MSProjectServerRole
GO



/* Query #265012 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_SecGetAllTemplates
AS
select * from MSP_WEB_SECURITY_TEMPLATES RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_SecGetAllTemplates TO MSProjectServerRole
GO



/* Query #265013 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_SecGetAllAllowedPermissionsForTemplate
   @p0 INT,
   @p1 INT
AS
  select CV.CONV_STRING as WSEC_FEA_ACT_NAME
    from MSP_WEB_SECURITY_TEMPLATE_PERMISSIONS TP,
         MSP_WEB_SECURITY_FEATURES_ACTIONS FA,
         MSP_WEB_CONVERSIONS CV
   where WSEC_TMPL_ID=@p0 
     and WSEC_ACT_ID=WSEC_FEA_ACT_ID 
     and WSEC_IS_ACTION=1 
     and WSEC_ALLOW=1 
     and WSEC_DENY=0
     and FA.WSEC_FEA_ACT_NAME_ID=CV.CONV_VALUE and CV.LANG_ID=@p1
   order by WSEC_FEA_ACT_NAME

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_SecGetAllAllowedPermissionsForTemplate TO MSProjectServerRole
GO



/* Query #265014 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_SecGetAllDeniedPermissionsForTemplate
   @p0 INT,
   @p1 INT
AS
  select CV.CONV_STRING as WSEC_FEA_ACT_NAME
    from MSP_WEB_SECURITY_TEMPLATE_PERMISSIONS TP,
         MSP_WEB_SECURITY_FEATURES_ACTIONS FA,
         MSP_WEB_CONVERSIONS CV
   where WSEC_TMPL_ID=@p0 
     and WSEC_ACT_ID=WSEC_FEA_ACT_ID 
     and WSEC_IS_ACTION=1 
     and WSEC_DENY=1
     and FA.WSEC_FEA_ACT_NAME_ID=CV.CONV_VALUE and CV.LANG_ID=@p1
   order by WSEC_FEA_ACT_NAME
     
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_SecGetAllDeniedPermissionsForTemplate TO MSProjectServerRole
GO



/* Query #265015 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_SecGetTemplateFeaturesAndActions
   @p0 INT,
   @p1 INT
AS
  select A.WSEC_FEA_ACT_ID,
         CV1.CONV_STRING as WSEC_ACTION_NAME,
         A.WSEC_FEA_ACT_PARENT,
         CV2.CONV_STRING as WSEC_FEATURE_NAME,
         C.WSEC_ALLOW,
         C.WSEC_DENY
    from MSP_WEB_SECURITY_FEATURES_ACTIONS A,
         MSP_WEB_SECURITY_FEATURES_ACTIONS B,
         MSP_WEB_SECURITY_TEMPLATE_PERMISSIONS C,
         MSP_WEB_CONVERSIONS CV1,
         MSP_WEB_CONVERSIONS CV2
   where C.WSEC_TMPL_ID=@p0
     and A.WSEC_FEA_ACT_PARENT=B.WSEC_FEA_ACT_ID
     and A.WSEC_FEA_ACT_ID=C.WSEC_ACT_ID
     and A.WSEC_FEA_ACT_NAME_ID=CV1.CONV_VALUE  and CV1.LANG_ID=@p1
     and B.WSEC_FEA_ACT_NAME_ID=CV2.CONV_VALUE  and CV2.LANG_ID=@p1
   order by A.WSEC_FEA_ACT_ID

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_SecGetTemplateFeaturesAndActions TO MSProjectServerRole
GO



/* Query #265016 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_GetProjectsList
AS
   select WP.WPROJ_ID, WP.PROJ_NAME, WR.RES_NAME, WP.PROJ_ID, EP.PROJ_VERSION, EP.PROJ_TYPE,
     (CASE WHEN EP.PROJ_TYPE=1 THEN 4 ELSE WP.WPROJ_TYPE END) as WPROJ_TYPE, WP.WPROJ_LAST_PUB
   from (MSP_WEB_PROJECTS WP LEFT JOIN MSP_WEB_RESOURCES WR ON WP.WRES_ID=WR.WRES_ID)
        LEFT JOIN MSP_PROJECTS EP ON WP.PROJ_ID=EP.PROJ_ID
   where WPROJ_IS_NONWORKING=0
   order by WP.PROJ_NAME
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_GetProjectsList TO MSProjectServerRole
GO



/* Query #265017 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_GetTemplatePermissions
   @p0 INT,
   @p1 TINYINT
AS
select WSEC_ACT_ID, WSEC_ALLOW, WSEC_DENY from MSP_WEB_SECURITY_TEMPLATE_PERMISSIONS, MSP_WEB_SECURITY_FEATURES_ACTIONS where WSEC_TMPL_ID=@p0 and WSEC_ACT_ID=WSEC_FEA_ACT_ID and WSEC_IS_ACTION=1 and WSEC_ON_OBJECT=@p1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_GetTemplatePermissions TO MSProjectServerRole
GO


/* Query #265019 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_GetUserInfo
   @p0 INT
AS
  SELECT WRES_ID, RES_NAME, WRES_NT_ACCOUNT, WRES_USE_NT_LOGON, WRES_EMAIL, WRES_IS_ENABLED, RES_PHONETICS 
    FROM MSP_WEB_RESOURCES 
   WHERE WRES_ID = @p0
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_GetUserInfo TO MSProjectServerRole
GO

/* Query #275000 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_AddModVision
   @p0 INT
AS
Select * From MSP_WEB_VIEW_REPORTS Where WVIEW_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_AddModVision TO MSProjectServerRole
GO



/* Query #275001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_VisionView1
   @p0 INT
AS
Select * From MSP_WEB_VIEW_FAVORITES Where WVIEW_FAV_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_VisionView1 TO MSProjectServerRole
GO



/* Query #275002 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_EntVersions1
AS
Select * From MSP_VERSIONS RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_EntVersions1 TO MSProjectServerRole
GO



/* Query #275003 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_EntCheckin1
AS
Select A.PROJ_ID, A.PROJ_NAME, A.PROJ_TYPE, A.PROJ_VERSION, A.PROJ_CHECKOUTBY, B.WRES_EMAIL, A.PROJ_CHECKOUTDATE, A.PROJ_PROJECT From (MSP_PROJECTS AS A INNER JOIN MSP_WEB_RESOURCES AS B ON  A.PROJ_CHECKOUTBY = B.RES_NAME) WHERE A.PROJ_CHECKEDOUT=1 AND A.PROJ_TYPE < 100 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_EntCheckin1 TO MSProjectServerRole
GO



/* Query #275004 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_EntCheckin2
   @p0 INT
AS
Select PROJ_CHECKOUTBY, PROJ_CHECKOUTDATE, PROJ_CHECKEDOUT From MSP_PROJECTS Where PROJ_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_EntCheckin2 TO MSProjectServerRole
GO



/* Query #275005 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_EntVersions2
   @p0 VARCHAR(50)
AS
Select PROJ_NAME From MSP_PROJECTS Where PROJ_VERSION=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_EntVersions2 TO MSProjectServerRole
GO



/* Query #275006 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_VisionView2
   @p0 INT
AS
Select * From MSP_WEB_VIEW_REPORTS Where WVIEW_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_VisionView2 TO MSProjectServerRole
GO



/* Query #345001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_BUS_GetSelectedTaskListAllFields
   @p0 INT,
   @p3 INT
AS
Select WA.WASSN_ID, WA.WRES_ID, WA.TASK_NAME, WA.WRES_ID_MGR, WA.WPROJ_ID, WP.PROJ_NAME, WP.WPROJ_TYPE, WA.WASSN_PCT_COMP, WA.ASSN_START_DATE, WA.ASSN_FINISH_DATE, WA.WASSN_COMMENTS From MSP_WEB_ASSIGNMENTS WA, MSP_WEB_PROJECTS WP Where WA.WPROJ_ID=WP.WPROJ_ID and WP.WPROJ_TYPE=3 and WA.TASK_ID<0 and WP.WPROJ_ID=(@p3) and ((WA.WRES_ID_MGR=(@p0)) OR (WP.WPROJ_SCOPE=2) OR (WP.WPROJ_SCOPE=1 AND (@p0) in (SELECT WA2.WRES_ID from MSP_WEB_ASSIGNMENTS WA2, MSP_WEB_PROJECTS WP2 where WA2.WPROJ_ID=WP2.WPROJ_ID AND WP2.WPROJ_TYPE=3 AND WA2.TASK_ID<0 AND WP2.WPROJ_ID=(@p3) AND WA2.WRES_ID=(@p0)))) Order By TASK_NAME
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_BUS_GetSelectedTaskListAllFields TO MSProjectServerRole
GO



/* Query #370001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_GetAllProjsForMngId
   @p0 INT,
   @p1 INT
AS
declare @trans_query nvarchar(1000)

set @trans_query = N'
SELECT WPROJ_ID,WPROJ_TYPE,PROJ_NAME,WPROJ_ADMINPROJECT
FROM MSP_WEB_PROJECTS
WHERE WPROJ_ID in (
  SELECT DISTINCT WPROJ_ID 
  FROM MSP_WEB_ASSIGNMENTS INNER JOIN MSP_WEB_TRANSACTIONS ON MSP_WEB_ASSIGNMENTS.WASSN_ID=MSP_WEB_TRANSACTIONS.WASSN_ID
  WHERE WRES_ID_MGR=' + CAST(@p0 as nvarchar) + ' and WTRANS_STATE < 3 
)'

if (@p1 != -1)
   set @trans_query = @trans_query + N'and WPROJ_ID=' + CAST(@p1 as nvarchar)

exec sp_executesql @trans_query

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_GetAllProjsForMngId TO MSProjectServerRole
GO



/* Query #375001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_VisionGetFavoriteInfo
   @p0 INT,
   @p1 INT
AS
Select * From MSP_WEB_VIEW_FAVORITES Where WVIEW_FAV_ID=@p1 and WRES_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_VisionGetFavoriteInfo TO MSProjectServerRole
GO



/* Query #375006 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_VisionGetViewInfo
   @p0 INT,
   @p1 INT
AS
Select WVIEW_DISPLAY_TYPE,WVIEW_DEFAULT_SETTINGS,WVIEW_OWC_PIVOT_XML,WVIEW_OWC_CHART_XML
    from MSP_WEB_SECURITY_GROUP_MEMBERS GM 
         INNER JOIN MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR ON GM.WSEC_GRP_GUID = SCR.WSEC_SP_GUID
         INNER JOIN MSP_WEB_SECURITY_CATEGORY_OBJECTS CO ON SCR.WSEC_CAT_ID = CO.WSEC_CAT_ID
         INNER JOIN MSP_WEB_VIEW_REPORTS VR ON CO.WSEC_OBJ_ID = VR.WVIEW_ID 
         INNER JOIN MSP_WEB_RESOURCES R ON GM.WRES_GUID = R.WRES_GUID
   where R.WRES_ID = @p0
     and WVIEW_ID = @p1
     and CO.WSEC_OBJ_TYPE = 3
     and VR.WVIEW_TYPE = 4
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_VisionGetViewInfo TO MSProjectServerRole
GO


/* Query #390000 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_GetSomeFavoriteViews
   @p0 INT,
   @p1 NTEXT,
   @p2 INT,
   @p3 INT,
   @p4 INT
AS
-- Hebrew strings have a special character at the start - CHARINDEX is aware of this, but LEFT and RIGHT are not, so for enterprise Hebrew strings, one additional character needs to be parsed off to remove the '#ENT#'
Select WF.WVIEW_FAV_ID, WF.WVIEW_FAV_NAME, (case when CHARINDEX('#ENT#',WC.CONV_STRING)=0 then WC.CONV_STRING else RIGHT (WC.CONV_STRING, LEN(WC.CONV_STRING)-(case when LEFT(WC.CONV_STRING, 1) = '#' then 5 else 6 end)) end) CONV_STRING  
From MSP_WEB_VIEW_FAVORITES WF, MSP_WEB_SECURITY_MENUS WM, MSP_WEB_CONVERSIONS WC 
Where WF.WRES_ID=@p0 and 
(WF.WSEC_MENU_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) or @p2 = 1) and 
WF.WSEC_MENU_ID=WM.WSEC_MENU_ID and 
WM.WSEC_MENU_LINKGROUP_NAME_ID= WC.CONV_VALUE and 
WC.LANG_ID = @p3 and 
(@p4=1 or CHARINDEX('#ENT#',WC.CONV_STRING)=0)
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_GetSomeFavoriteViews TO MSProjectServerRole
GO

/* Query #390001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_BUS_GetTransRecordsNeedApproval
   @p0 INT,
   @p1 DATETIME
AS

Select WA.WASSN_NOTE_STATUS, WASSN_CREATED_BY_RES as TNewTaskIndic,WA.WASSN_ID,TASK_ID,TASK_NAME,WRES_ID_MGR,WASSN_UPDATE_STATUS,WWA.WAPPROVAL_STATUS,R1.WRES_ID,R1.RES_NAME,PROJ_NAME,WP.WPROJ_ID, WASSN_CURRENT_TRACKING_MODE, R2.RES_NAME as TManagerName, CASE WHEN (WA.WASSN_UPDATE_STATUS=1 AND WA.WASSN_ACTUALS_PENDING<2) THEN 2 ELSE WA.WASSN_ACTUALS_PENDING+WA.WASSN_UPDATE_STATUS END+ CASE WHEN ((WA.WASSN_ACTUALS_PENDING+WA.WASSN_UPDATE_STATUS = 0) AND NOT EXISTS (SELECT * FROM MSP_WEB_WORK MWW WHERE MWW.WASSN_ID=WA.WASSN_ID AND MWW.WWORK_TYPE <>0 AND MWW.WWORK_VALUE <>0)) THEN 2 ELSE 0 END as TPMAccept,WWA.WRES_ID_APPROVER, WWA.WAPPROVAL_ID, WA.ASSN_START_DATE,WA.ASSN_FINISH_DATE
From (((MSP_WEB_ASSIGNMENTS WA  INNER JOIN MSP_WEB_PROJECTS WP ON WA.WPROJ_ID=WP.WPROJ_ID) INNER JOIN MSP_WEB_RESOURCES R1 ON WA.WRES_ID=R1.WRES_ID) INNER JOIN MSP_WEB_RESOURCES R2 ON WA.WRES_ID_MGR=R2.WRES_ID) INNER JOIN MSP_WEB_WORK_APPROVAL WWA ON WA.WASSN_ID = WWA.WASSN_ID
Where WWA.WAPPROVAL_STATUS = 0 and WA.WRES_ID in (
            -- Permission 212: Approve timesheet permission
            select WRES_ID from MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(@p0, 212, -1)
         )
		 AND WWA.WPRD_START_DATE<= @p1 AND WWA.WPRD_FINISH_DATE>= @p1
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_BUS_GetTransRecordsNeedApproval TO MSProjectServerRole
GO


/* Query #390002 */ 
CREATE     PROCEDURE dbo.MSP_WEB_SP_SEC_GetTSSummaryViewRS
   @res_id       int,
   @dumbParam1	 datetime,
   @dumbParam2	 int,
   @dCurDate     datetime,
   @approvalStatus	 int
AS
BEGIN
  Select WOBJ_DOC_REF_CNT,WOBJ_ISSUE_REF_CNT,WOBJ_RISK_REF_CNT,
	WASSN_ACTUALS_PENDING, WASSN_UPDATE_STATUS,WR0.RES_NAME as TManagerName,
         WASSN_CREATED_BY_RES as TNewTaskIndic,WA.ASSN_START_DATE,WA.ASSN_FINISH_DATE,
         WASSN_IS_NEW_ASSN,WASSN_DELETED_IN_PROJ,WA.WRES_ID,WR.RES_NAME,WA.WPROJ_ID,PROJ_NAME,WPROJ_TYPE,
         WA.WASSN_ID,TASK_UID_SUMMARY,TASK_ID,TASK_UID,TASK_IS_SUMMARY,TASK_IS_MILESTONE,
         WA.TASK_NAME,WA.WASSN_CURRENT_TRACKING_MODE,  
		     CASE WHEN (WA.WASSN_UPDATE_STATUS=1 AND WA.WASSN_ACTUALS_PENDING<2) THEN 2 ELSE WA.WASSN_ACTUALS_PENDING+WA.WASSN_UPDATE_STATUS END+ CASE WHEN ((WA.WASSN_ACTUALS_PENDING+WA.WASSN_UPDATE_STATUS = 0) AND NOT EXISTS (SELECT * FROM MSP_WEB_WORK MWW WHERE MWW.WASSN_ID=WA.WASSN_ID AND MWW.WWORK_TYPE <>0 AND MWW.WWORK_VALUE <>0)) THEN 2 ELSE 0 END as TPMAccept,
         CASE WWA.WAPPROVAL_STATUS WHEN 2 THEN 2 WHEN 1 THEN 1 ELSE 0 END  AS TS_STATUS
    From (((MSP_WEB_ASSIGNMENTS WA INNER JOIN MSP_WEB_PROJECTS ON WA.WPROJ_ID=MSP_WEB_PROJECTS.WPROJ_ID) 
         INNER JOIN MSP_WEB_RESOURCES WR ON WA.WRES_ID=WR.WRES_ID) 
         LEFT JOIN MSP_WEB_RESOURCES WR0 ON WA.WRES_ID_MGR=WR0.WRES_ID) 
         LEFT JOIN MSP_WEB_OBJECTS WO ON (WA.WPROJ_ID=WO.WOBJ_PROJ_ID AND WA.TASK_UID=WO.WOBJ_TASK_ID)
	 LEFT JOIN MSP_WEB_WORK_APPROVAL WWA ON (WWA.WASSN_ID = WA.WASSN_ID AND WWA.WPRD_START_DATE <=@dCurDate and WWA.WPRD_FINISH_DATE>=@dCurDate),
	 MSP_WEB_TIME_PERIODS WTP2
   Where (WA.WASSN_IS_CONFIRMED<>0 OR MSP_WEB_PROJECTS.WPROJ_ADMINPROJECT<>0)
     and WA.WASSN_REMOVED_BY_RESOURCE=0
     and MSP_WEB_PROJECTS.WPROJ_TYPE <> 3
     and WA.WRES_ID in (
            select WRES_ID from MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(@res_id, 212, -1)
         )
	 and WTP2.WPRD_START_DATE<=@dCurDate and WTP2.WPRD_FINISH_DATE>=@dCurDate
	 and ((WA.ASSN_START_DATE < WTP2.WPRD_FINISH_DATE AND WA.ASSN_FINISH_DATE> WTP2.WPRD_START_DATE) 
          OR (WA.WASSN_ACTUALS_PENDING <> 0 AND WA.ASSN_START_DATE<= WTP2.WPRD_FINISH_DATE) 
          OR (WA.WASSN_PCT_COMP< 100 AND WASSN_PCT_COMP>0 AND WA.ASSN_START_DATE<= WTP2.WPRD_FINISH_DATE)) 
	 and ( @approvalStatus = 0  -- All assignments
		OR (@approvalStatus = 1 AND EXISTS  -- 1: Approved
			(SELECT * FROM MSP_WEB_WORK_APPROVAL WWA2 
			 WHERE WTP2.WPRD_START_DATE = WWA2.WPRD_START_DATE AND WTP2.WPRD_FINISH_DATE = WWA2.WPRD_FINISH_DATE AND WWA2.WRES_ID = WA.WRES_ID AND WWA2.WAPPROVAL_STATUS = 1
			) AND NOT EXISTS
			(SELECT * FROM MSP_WEB_WORK_APPROVAL WWA3 
			 WHERE WTP2.WPRD_START_DATE = WWA3.WPRD_START_DATE AND WTP2.WPRD_FINISH_DATE = WWA3.WPRD_FINISH_DATE AND WWA3.WRES_ID = WA.WRES_ID AND (WWA3.WAPPROVAL_STATUS = 0 OR WWA3.WAPPROVAL_STATUS = 2)
			)
		OR (@approvalStatus = 2 AND EXISTS -- 2: rejected
			(SELECT * FROM MSP_WEB_WORK_APPROVAL WWA2 
			 WHERE WTP2.WPRD_START_DATE = WWA2.WPRD_START_DATE AND WTP2.WPRD_FINISH_DATE = WWA2.WPRD_FINISH_DATE AND WWA2.WRES_ID = WA.WRES_ID AND WWA2.WAPPROVAL_STATUS = 2
			) AND NOT EXISTS
			(SELECT * FROM MSP_WEB_WORK_APPROVAL WWA3 
			 WHERE WTP2.WPRD_START_DATE = WWA3.WPRD_START_DATE AND WTP2.WPRD_FINISH_DATE = WWA3.WPRD_FINISH_DATE AND WWA3.WRES_ID = WA.WRES_ID AND WWA3.WAPPROVAL_STATUS = 0
			)
		   )
		OR (@approvalStatus = 3 AND EXISTS -- 3: pending
			(SELECT * FROM MSP_WEB_WORK_APPROVAL WWA2 
			 WHERE WTP2.WPRD_START_DATE = WWA2.WPRD_START_DATE AND WTP2.WPRD_FINISH_DATE = WWA2.WPRD_FINISH_DATE AND WWA2.WRES_ID = WA.WRES_ID AND WWA2.WAPPROVAL_STATUS = 0
			)
		   )
		OR (@approvalStatus = 4 AND NOT EXISTS -- 4: not submitted
			(SELECT * FROM MSP_WEB_WORK_APPROVAL WWA2 
			 WHERE WTP2.WPRD_START_DATE = WWA2.WPRD_START_DATE AND WTP2.WPRD_FINISH_DATE = WWA2.WPRD_FINISH_DATE AND WWA2.WRES_ID = WA.WRES_ID 
			)
		   )
		))
RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetTSSummaryViewRS TO MSProjectServerRole
GO


/* Query #10169 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_AddNewDelegAssns
   @p0 INT,
   @p1 INT,
   @p2 TINYINT
AS
Insert into MSP_WEB_DELEGATION_ASSIGNMENTS (WASSN_ID,WDELEG_ID,WDELEG_KEEP_COPY) values (@p0,@p1,@p2) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_AddNewDelegAssns TO MSProjectServerRole
GO



/* Query #16018 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_InsertViewReportsFields
   @p0 INT,
   @p1 INT,
   @p2 INT,
   @p3 SMALLINT,
   @p4 TINYINT
AS
Insert into MSP_WEB_VIEW_REPORTS_FIELDS (WVIEW_ID,WFIELD_ID,WVIEW_FIELD_ORDER,WVIEW_FIELD_WIDTH,WVIEW_FIELD_AUTOSIZE) values (@p0,@p1,@p2,@p3,@p4) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_InsertViewReportsFields TO MSProjectServerRole
GO



/* Query #16044 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_InsertViewReportsCategories
   @p0 INT,
   @p1 INT
AS
Insert into MSP_WEB_SECURITY_CATEGORY_OBJECTS (WSEC_OBJ_TYPE, WSEC_OBJ_ID, WSEC_CAT_ID) values (3,@p0,@p1) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_InsertViewReportsCategories TO MSProjectServerRole
GO



/* Query #30009 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_AddNewFieldInfoIdToWPWI
   @p0 INT,
   @p1 INT
AS
Insert Into MSP_WEB_PROJECT_WORKGROUP_INFO (WPROJ_ID, CUSTFIELD_INFO_ID) VALUES (@p0,@p1) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_AddNewFieldInfoIdToWPWI TO MSProjectServerRole
GO



/* Query #30010 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_AddWorkGroupFieldsAssignment
   @p0 INT,
   @p1 INT
AS
Insert Into MSP_WEB_WORKGROUP_FIELDS (WASSN_ID, FIELD_ID, CUSTFIELD_TYPE, INT_VAL, WWORKGRP_INFO_IS_READONLY) VALUES (@p0, 1073741849, 2, @p1, 1) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_AddWorkGroupFieldsAssignment TO MSProjectServerRole
GO

/* Query #30014 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_AddTasklistSummary
   @p0 INT,
   @p1 NVARCHAR(255)
AS
Insert into MSP_WEB_ASSIGNMENTS (WRES_ID,WASSN_PARENT_ID,WPROJ_ID,WRES_ID_MGR,ASSN_UID,TASK_UID,TASK_ID,TASK_UID_SUMMARY,TASK_NAME,ASSN_START_DATE,ASSN_FINISH_DATE,WASSN_COMMENTS,WASSN_PCT_COMP) values (-1,-1,@p0,-1,-1,-1,0,-1,@p1,null,null,null,null) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_AddTasklistSummary TO MSProjectServerRole
GO



/* Query #35000 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_AddNewTaskTransaction
   @p0 INT,
   @p1 INT,
   @p2 INT,
   @p3 INT,
   @p4 DATETIME,
   @p5 INT,
   @p6 INT
AS
INSERT INTO MSP_WEB_TRANSACTIONS (WASSN_ID,WTRANS_TYPE,WTRANS_STATE,WTRANS_ACTION,WTRANS_DATE,WRES_ID_TRANS_SENDER,WDELEG_ID) VALUES (@p0,@p1,@p2,@p3,@p4,@p5,@p6) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_AddNewTaskTransaction TO MSProjectServerRole
GO



/* Query #60001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_InsertDataSpace
   @p0 UNIQUEIDENTIFIER,
   @p1 INT,
   @p2 NTEXT
AS
insert into MSP_WEB_RESOURCE_SETTINGS (WRES_GUID,WSEC_PAGE_ID,WSET_VALUE) values (@p0,@p1,@p2) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_InsertDataSpace TO MSProjectServerRole
GO



/* Query #65046 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_AddNotificationRecord
   @p0 INT,
   @p1 INT,
   @p2 TINYINT
AS
insert into MSP_WEB_NOTIFICATIONS (WNTFY_OWNER_ID, WNTFY_EVENT_ID, WNTFY_IS_ENABLED) values (@p0, @p1, @p2) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_AddNotificationRecord TO MSProjectServerRole
GO



/* Query #67100 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_InsertGroupMember
   @p0 UNIQUEIDENTIFIER,
   @p1 UNIQUEIDENTIFIER
AS
   If (@p0 = @p1)
     Begin
     insert into MSP_WEB_SECURITY_GROUP_MEMBERS (WSEC_GRP_GUID, WRES_GUID)
     (
       select WRES_GUID, WRES_GUID from MSP_WEB_RESOURCES where WRES_GUID=@p0
     )
     End
   Else
     Begin
     insert into MSP_WEB_SECURITY_GROUP_MEMBERS (WSEC_GRP_GUID, WRES_GUID)
     (
       select WG.WSEC_GRP_GUID, WR.WRES_GUID
         from MSP_WEB_RESOURCES WR,
              MSP_WEB_SECURITY_GROUPS WG
        where WR.WRES_GUID=@p1
              and WG.WSEC_GRP_GUID=@p0
     )
     End
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_InsertGroupMember TO MSProjectServerRole
GO



/* Query #67103 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_InsertSpCatPermission
   @p0 INT,
   @p1 INT,
   @p2 TINYINT,
   @p3 TINYINT,
   @p4 TINYINT
AS
insert into MSP_WEB_SECURITY_SP_CAT_PERMISSIONS (WSEC_REL_ID, WSEC_FEA_ACT_ID, WSEC_ALLOW, WSEC_DENY, WSEC_ACCESS) values (@p0, @p1, @p2, @p3, @p4) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_InsertSpCatPermission TO MSProjectServerRole
GO



/* Query #67114 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_InsertCatgoryRulesByCatID
   @p0 INT,
   @p1 INT,
   @p2 TINYINT
AS
insert into MSP_WEB_SECURITY_CATEGORY_RULES (WSEC_CAT_ID, WSEC_OBJ_TYPE, WSEC_OBJ_RULE_TYPE) values (@p0, @p1, @p2) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_InsertCatgoryRulesByCatID TO MSProjectServerRole
GO



/* Query #67115 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_InsertCategoryObjects
   @p0 INT,
   @p1 INT,
   @p2 INT
AS
insert into MSP_WEB_SECURITY_CATEGORY_OBJECTS (WSEC_CAT_ID, WSEC_OBJ_TYPE, WSEC_OBJ_ID) values (@p0, @p1, @p2) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_InsertCategoryObjects TO MSProjectServerRole
GO



/* Query #67131 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_InsertCustomMenu
   @p0 NVARCHAR(100),
   @p1 INT,
   @p2 SMALLINT,
   @p3 NVARCHAR(100),
   @p4 INT,
   @p5 TINYINT
AS
Insert into MSP_WEB_SECURITY_MENUS (WSEC_MENU_CUSTOM_NAME, WSEC_MENU_PARENT_ID, WSEC_MENU_SEQ, WSEC_MENU_CUSTOM_DESC, WSEC_MENU_PAGE_ID, WSEC_MENU_IS_CUSTOM, WSEC_MENU_IS_TOP_LEVEL) values(@p0, @p1, @p2, @p3, @p4, 1, @p5) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_InsertCustomMenu TO MSProjectServerRole
GO



/* Query #67134 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_InsertNewTemplatePermissions
   @p0 INT
AS
insert into MSP_WEB_SECURITY_TEMPLATE_PERMISSIONS (WSEC_TMPL_ID, WSEC_ACT_ID, WSEC_ALLOW, WSEC_DENY, WSEC_ACCESS) select @p0, WSEC_FEA_ACT_ID, 0, 0, 1 from MSP_WEB_SECURITY_FEATURES_ACTIONS RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_InsertNewTemplatePermissions TO MSProjectServerRole
GO



/* Query #210234 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_InsertALink
   @p0 NVARCHAR(255),
   @p1 NVARCHAR(500)
AS
Insert into MSP_WEB_ADMIN_LINKS (WLINKS_NAME, WLINKS_HREF, WLINKS_TYPE) values (@p0,@p1,0) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_InsertALink TO MSProjectServerRole
GO



/* Query #210235 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_InsertAContent
   @p0 NVARCHAR(255),
   @p1 NVARCHAR(500),
   @p2 NVARCHAR(255)
AS
Insert into MSP_WEB_ADMIN_LINKS (WLINKS_NAME, WLINKS_HREF,WLINKS_HEIGHT, WLINKS_TYPE) values (@p0,@p1,@p2,1) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_InsertAContent TO MSProjectServerRole
GO



/* Query #16003 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_RenameScheme
   @p0 INT,
   @p1 NVARCHAR(50)
AS
Update MSP_WEB_GANTT_SCHEMES set WGANTT_SCHEME_NAME=@p1 Where WGANTT_SCHEME_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_RenameScheme TO MSProjectServerRole
GO



/* Query #40008 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetObjectID
   @p0 NTEXT
AS
SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_DESC LIKE @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetObjectID TO MSProjectServerRole
GO



/* Query #40011 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetObjectForInsert
   @p0 NTEXT
AS
SELECT WOBJ_ID, WOBJ_TYPE, WOBJ_DESC FROM MSP_WEB_OBJECTS WHERE WOBJ_DESC LIKE @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetObjectForInsert TO MSProjectServerRole
GO



/* Query #50010 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewTasks_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_PROJ_TASKS_STD where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewTasks_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #50011 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewTasks_DeleteViewTable1
   @p0 INT
AS
delete from MSP_VIEW_PROJ_TASKS_CF  where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewTasks_DeleteViewTable1 TO MSProjectServerRole
GO



/* Query #50012 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewTasks_DeleteViewTable2
   @p0 INT
AS
delete from MSP_VIEW_PROJ_TASKS_ENT where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewTasks_DeleteViewTable2 TO MSProjectServerRole
GO



/* Query #50020 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewTasks_SelectEmptyRst0
AS
select * from MSP_VIEW_PROJ_TASKS_STD WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewTasks_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #50021 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewTasks_SelectEmptyRst1
AS
select * from MSP_VIEW_PROJ_TASKS_CF WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewTasks_SelectEmptyRst1 TO MSProjectServerRole
GO



/* Query #50022 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewTasks_SelectEmptyRst2
AS
select * from MSP_VIEW_PROJ_TASKS_ENT WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewTasks_SelectEmptyRst2 TO MSProjectServerRole
GO



/* Query #50110 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewRes_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_PROJ_RES_STD where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewRes_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #50111 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewRes_DeleteViewTable1
   @p0 INT
AS
delete from MSP_VIEW_PROJ_RES_CF  where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewRes_DeleteViewTable1 TO MSProjectServerRole
GO



/* Query #50112 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewRes_DeleteViewTable2
   @p0 INT
AS
delete from MSP_VIEW_PROJ_RES_ENT where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewRes_DeleteViewTable2 TO MSProjectServerRole
GO



/* Query #50120 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewRes_SelectEmptyRst0
AS
select * from MSP_VIEW_PROJ_RES_STD WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewRes_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #50121 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewRes_SelectEmptyRst1
AS
select * from MSP_VIEW_PROJ_RES_CF WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewRes_SelectEmptyRst1 TO MSProjectServerRole
GO



/* Query #50122 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewRes_SelectEmptyRst2
AS
select * from MSP_VIEW_PROJ_RES_ENT WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewRes_SelectEmptyRst2 TO MSProjectServerRole
GO



/* Query #50210 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewAssn_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_PROJ_ASSN_STD where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewAssn_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #50211 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewAssn_DeleteViewTable1
   @p0 INT
AS
delete from MSP_VIEW_PROJ_ASSN_CF  where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewAssn_DeleteViewTable1 TO MSProjectServerRole
GO



/* Query #50212 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewAssn_DeleteViewTable2
   @p0 INT
AS
delete from MSP_VIEW_PROJ_ASSN_ENT where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewAssn_DeleteViewTable2 TO MSProjectServerRole
GO



/* Query #50220 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewAssn_SelectEmptyRst0
AS
select * from MSP_VIEW_PROJ_ASSN_STD WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewAssn_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #50221 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewAssn_SelectEmptyRst1
AS
select * from MSP_VIEW_PROJ_ASSN_CF WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewAssn_SelectEmptyRst1 TO MSProjectServerRole
GO



/* Query #50222 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewAssn_SelectEmptyRst2
AS
select * from MSP_VIEW_PROJ_ASSN_ENT WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewAssn_SelectEmptyRst2 TO MSProjectServerRole
GO



/* Query #50310 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewProject_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_PROJ_PROJECTS_STD where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewProject_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #50311 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewProject_DeleteViewTable1
   @p0 INT
AS
delete from MSP_VIEW_PROJ_PROJECTS_ENT where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewProject_DeleteViewTable1 TO MSProjectServerRole
GO



/* Query #50320 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewProject_SelectEmptyRst0
AS
select * from MSP_VIEW_PROJ_PROJECTS_STD WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewProject_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #50321 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewProject_SelectEmptyRst1
AS
select * from MSP_VIEW_PROJ_PROJECTS_ENT WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewProject_SelectEmptyRst1 TO MSProjectServerRole
GO



/* Query #50410 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewTaskSplits_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_PROJ_TASKSPLITS where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewTaskSplits_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #50420 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewTaskSplits_SelectEmptyRst0
AS
select * from MSP_VIEW_PROJ_TASKSPLITS WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewTaskSplits_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #50510 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewPredecessors_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_PROJ_PRED where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewPredecessors_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #50520 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewPredecessors_SelectEmptyRst0
AS
select * from MSP_VIEW_PROJ_PRED WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewPredecessors_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #50610 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewSuccessors_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_PROJ_SUCC where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewSuccessors_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #50620 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewSuccessors_SelectEmptyRst0
AS
select * from MSP_VIEW_PROJ_SUCC WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewSuccessors_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #50710 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewAssignmentTimephasedByDay_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_PROJ_ASSN_TP_BY_DAY where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewAssignmentTimephasedByDay_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #50720 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewAssignmentTimephasedByDay_SelectEmptyRst0
AS
select * from MSP_VIEW_PROJ_ASSN_TP_BY_DAY WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewAssignmentTimephasedByDay_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #51010 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewEntRes_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_RES_STD where ResourceUniqueID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewEntRes_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #51011 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewEntRes_DeleteViewTable1
   @p0 INT
AS
delete from MSP_VIEW_RES_CF  where CF_ResourceUniqueID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewEntRes_DeleteViewTable1 TO MSProjectServerRole
GO



/* Query #51012 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewEntRes_DeleteViewTable2
   @p0 INT
AS
delete from MSP_VIEW_RES_ENT where ENT_ResourceUniqueID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewEntRes_DeleteViewTable2 TO MSProjectServerRole
GO



/* Query #51020 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewEntRes_SelectEmptyRst0
AS
select * from MSP_VIEW_RES_STD WITH (READPAST) where ResourceUniqueID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewEntRes_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #51021 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewEntRes_SelectEmptyRst1
AS
select * from MSP_VIEW_RES_CF WITH (READPAST) where CF_ResourceUniqueID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewEntRes_SelectEmptyRst1 TO MSProjectServerRole
GO



/* Query #51022 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewEntRes_SelectEmptyRst2
AS
select * from MSP_VIEW_RES_ENT WITH (READPAST) where ENT_ResourceUniqueID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewEntRes_SelectEmptyRst2 TO MSProjectServerRole
GO



/* Query #51110 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewResourceAssignmentByDay_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_RES_TP_BY_DAY where ResourceUniqueID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewResourceAssignmentByDay_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #51120 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewResourceAssignmentByDay_SelectEmptyRst0
AS
select * from MSP_VIEW_RES_TP_BY_DAY WITH (READPAST) where ResourceUniqueID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewResourceAssignmentByDay_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #54011 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetProjDBIDFromEntProjID
   @p0 INT
AS
select WPROJ_ID from MSP_WEB_PROJECTS where PROJ_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetProjDBIDFromEntProjID TO MSProjectServerRole
GO



/* Query #35501 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetOutlineCodesForViews
   @p1 INT
AS
select WWFI.CUSTFIELD_INFO_ID as TFieldName, OC_CACHED_FULL_NAME, OC_DESCRIPTION, CODE_UID 
from 
MSP_WEB_VIEW_REPORTS_FIELDS WVRF
INNER JOIN MSP_FIELD_ATTRIBUTES MFA ON WVRF.WFIELD_ID=MFA.ATTRIB_FIELD_ID
INNER JOIN MSP_OUTLINE_CODES MOC ON (MFA.ATTRIB_FIELD_ID=MOC.OC_FIELD_ID or (MFA.ATTRIB_VALUE=MOC.OC_FIELD_ID and ATTRIB_ID=212))
INNER JOIN MSP_PROJECTS MP ON (MOC.PROJ_ID=MP.PROJ_ID and MFA.PROJ_ID=MP.PROJ_ID)
INNER JOIN MSP_WEB_WORKGROUP_FIELDS_INFO WWFI ON MFA.ATTRIB_FIELD_ID=WWFI.FIELD_ID
where WVIEW_ID=@p1 and MP.PROJ_TYPE=2 and OC_CACHED_FULL_NAME is not null 
and (ATTRIB_ID=200 or ATTRIB_ID=212)
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetOutlineCodesForViews TO MSProjectServerRole
GO


/* Query #35502 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetOutlineCodeMasksForTasks
   @p0 NTEXT
AS
select  WWFI.CUSTFIELD_INFO_ID as TFieldName, AS_VALUE as TMask , CASE WHEN MFA2.ATTRIB_VALUE IS NOT NULL THEN 1 ELSE 0 END as TRequiredField 
from MSP_ATTRIBUTE_STRINGS MAS 
INNER JOIN MSP_FIELD_ATTRIBUTES MFA ON (MAS.AS_ID=MFA.AS_ID and MAS.PROJ_ID=MFA.PROJ_ID)
INNER JOIN MSP_PROJECTS MP ON MAS.PROJ_ID=MP.PROJ_ID
INNER JOIN MSP_WEB_WORKGROUP_FIELDS_INFO WWFI ON ATTRIB_FIELD_ID=WWFI.FIELD_ID 
LEFT  JOIN MSP_FIELD_ATTRIBUTES MFA2 ON MFA2.PROJ_ID = MP.PROJ_ID AND MFA2.ATTRIB_FIELD_ID=WWFI.FIELD_ID AND MFA2.ATTRIB_ID = 213
where MP.PROJ_TYPE=2 and MFA.ATTRIB_ID=200 and WWFI.CUSTFIELD_INFO_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))
union
select WWFI.CUSTFIELD_INFO_ID as TFieldName, AS_VALUE as TMask,CASE WHEN MFA3.ATTRIB_VALUE IS NOT NULL THEN 1 ELSE 0 END as TRequiredField  
from MSP_FIELD_ATTRIBUTES MFA inner join MSP_FIELD_ATTRIBUTES MFA2 on MFA2.ATTRIB_VALUE=MFA.ATTRIB_FIELD_ID
INNER JOIN MSP_ATTRIBUTE_STRINGS MAS ON (MAS.AS_ID=MFA.AS_ID and MAS.PROJ_ID=MFA.PROJ_ID)
INNER JOIN MSP_PROJECTS MP ON MAS.PROJ_ID=MP.PROJ_ID
INNER JOIN MSP_WEB_WORKGROUP_FIELDS_INFO WWFI ON MFA2.ATTRIB_FIELD_ID=WWFI.FIELD_ID 
LEFT  JOIN MSP_FIELD_ATTRIBUTES MFA3 ON MFA3.PROJ_ID = MP.PROJ_ID AND MFA3.ATTRIB_FIELD_ID=WWFI.FIELD_ID AND MFA3.ATTRIB_ID = 213
where MP.PROJ_TYPE=2 and MFA.ATTRIB_ID=200 and MFA2.ATTRIB_ID=212 and WWFI.CUSTFIELD_INFO_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetOutlineCodeMasksForTasks TO MSProjectServerRole
GO


/* Query #35503 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetOutlineCodesForTasks
   @p0 NTEXT
AS
select WWFI.CUSTFIELD_INFO_ID as TFieldName, OC_CACHED_FULL_NAME, OC_DESCRIPTION, CODE_UID 
from 
MSP_FIELD_ATTRIBUTES MFA
INNER JOIN MSP_OUTLINE_CODES MOC ON (MFA.ATTRIB_FIELD_ID=MOC.OC_FIELD_ID or (MFA.ATTRIB_VALUE=MOC.OC_FIELD_ID and ATTRIB_ID=212))
INNER JOIN MSP_PROJECTS MP ON (MOC.PROJ_ID=MP.PROJ_ID and MFA.PROJ_ID=MP.PROJ_ID)
INNER JOIN MSP_WEB_WORKGROUP_FIELDS_INFO WWFI ON MFA.ATTRIB_FIELD_ID=WWFI.FIELD_ID
where MP.PROJ_TYPE=2 and OC_CACHED_FULL_NAME is not null 
and (ATTRIB_ID=200 or ATTRIB_ID=212) and WWFI.CUSTFIELD_INFO_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetOutlineCodesForTasks TO MSProjectServerRole
GO


/* Query #75000 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_CubeSettings
AS
select * from MSP_WEB_ADMIN_CUBE RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_CubeSettings TO MSProjectServerRole
GO



/* Query #75001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_VisionViewsXML
   @p0 INT
AS
select * From MSP_WEB_VIEW_REPORTS Where WVIEW_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_VisionViewsXML TO MSProjectServerRole
GO



/* Query #75002 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_ENT_Mode
AS
select * From MSP_WEB_ADMIN RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_ENT_Mode TO MSProjectServerRole
GO



/* Query #75003 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_ENT_Settings
AS
select WADMIN_ENABLE_ENTERPRISE, WADMIN_DISPLAY_MASTER_IN_ENTERPRISE, WADMIN_ALLOW_LOCAL_BASE_CALS_IN_ENTERPRISE, 
WADMIN_ENFORCE_CURRENCY From MSP_WEB_ADMIN RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_ENT_Settings TO MSProjectServerRole
GO



/* Query #75004 */
CREATE PROCEDURE dbo.MSP_WEB_SP_VSN_Currency_Format
AS
SELECT PROJ_OPT_CURRENCY_SYMBOL,PROJ_OPT_CURRENCY_POSITION,PROJ_OPT_CURRENCY_DIGITS,PROJ_OPT_MINUTES_PER_DAY From MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE) WHERE PROJ_TYPE=2 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_VSN_Currency_Format TO MSProjectServerRole
GO



/* Query #85000 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetModels
AS
SELECT WMOD_MODEL_UID, WMOD_MODEL_NAME, WMOD_MODEL_DESC, WMOD_CREATE_DATE, WMOD_UPDATE_DATE, WMOD_CREATED_BY, WMOD_LAST_UPDATED_BY, WMOD_LOCKED_BY, WMOD_CREATED_BY_ID, WMOD_LAST_UPDATED_BY_ID, WMOD_LOCKED_BY_ID FROM MSP_WEB_MODELS ORDER BY WMOD_MODEL_NAME RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetModels TO MSProjectServerRole
GO



/* Query #85001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetModelDetails
   @p0 INT
AS
SELECT * FROM MSP_WEB_MODELS WHERE WMOD_MODEL_UID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetModelDetails TO MSProjectServerRole
GO



/* Query #85002 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjects
AS
SELECT ProjectUniqueID, PROJ_NAME FROM MSP_VIEW_PROJ_PROJECTS_STD INNER JOIN MSP_WEB_PROJECTS ON MSP_VIEW_PROJ_PROJECTS_STD.WPROJ_ID = MSP_WEB_PROJECTS.WPROJ_ID WHERE WPROJ_IS_CONSOLIDATED_PROJECT = 0 ORDER BY PROJ_NAME RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjects TO MSProjectServerRole
GO



/* Query #85003 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetResources
AS
SELECT ResourceUniqueID, ResourceName FROM MSP_VIEW_RES_STD INNER JOIN MSP_VIEW_RES_ENT ON ResourceUniqueID = ENT_ResourceUniqueID WHERE ResourceType=0 AND ResourceEnterpriseGeneric=0 ORDER BY ResourceName RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetResources TO MSProjectServerRole
GO



/* Query #85004 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjUIDByType
   @p0 INT
AS
SELECT PROJ_ID FROM MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE) WHERE PROJ_TYPE=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjUIDByType TO MSProjectServerRole
GO



/* Query #85005 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjResList
AS
SELECT MSP_RESOURCES.PROJ_ID, MSP_RESOURCES.RES_EUID FROM MSP_PROJECTS INNER JOIN MSP_RESOURCES ON MSP_PROJECTS.PROJ_ID = MSP_RESOURCES.PROJ_ID WHERE MSP_RESOURCES.RES_UID > 0 AND MSP_RESOURCES.RES_EUID IS NOT NULL AND MSP_PROJECTS.PROJ_TYPE = 0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjResList TO MSProjectServerRole
GO



/* Query #85006 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjResListByVersion
   @p0 VARCHAR(50)
AS
SELECT MSP_RESOURCES.PROJ_ID, MSP_RESOURCES.RES_EUID FROM MSP_PROJECTS INNER JOIN MSP_RESOURCES ON MSP_PROJECTS.PROJ_ID = MSP_RESOURCES.PROJ_ID WHERE MSP_RESOURCES.RES_UID > 0 AND MSP_RESOURCES.RES_EUID IS NOT NULL  AND MSP_PROJECTS.PROJ_TYPE = 0 AND (MSP_PROJECTS.PROJ_VERSION = (@p0) OR MSP_PROJECTS.PROJ_VERSION = (select VERS_VERSION FROM MSP_VERSIONS WHERE VERS_DEFAULT = 1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjResListByVersion TO MSProjectServerRole
GO



/* Query #85007 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetCPLinks
   @p0 INT,
   @p1 INT,
   @p2 INT
AS
SELECT DISTINCT PROJ_ID, TEXT_VALUE FROM MSP_TEXT_FIELDS WHERE TEXT_CATEGORY = @p0 AND (TEXT_FIELD_ID = @p1 OR TEXT_FIELD_ID = @p2 ) ORDER BY PROJ_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetCPLinks TO MSProjectServerRole
GO



/* Query #85008 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetUIDForProjName
   @p0 NVARCHAR(255)
AS
SELECT PROJ_ID, PROJ_PROJECT, PROJ_VERSION FROM MSP_PROJECTS WHERE PROJ_NAME = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetUIDForProjName TO MSProjectServerRole
GO



/* Query #85009 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjNameForUID
   @p0 INT
AS
SELECT PROJ_NAME, PROJ_DATA_SOURCE, PROJ_PROJECT, PROJ_VERSION FROM MSP_PROJECTS WHERE PROJ_ID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjNameForUID TO MSProjectServerRole
GO



/* Query #85010 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetLastIdentityValue
AS
SELECT @@identity AS IDENTITYVALUE RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetLastIdentityValue TO MSProjectServerRole
GO



/* Query #85011 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjHeader
   @p0 INT
AS
SELECT PROJ_NAME, TaskPriority, ProjectStartDate, ProjectFinishDate, MSP_PROJECTS.PROJ_ADMINPROJECT FROM 
((MSP_VIEW_PROJ_PROJECTS_STD INNER JOIN MSP_PROJECTS ON MSP_VIEW_PROJ_PROJECTS_STD.ProjectUniqueID = MSP_PROJECTS.PROJ_ID) 
INNER JOIN MSP_VIEW_PROJ_TASKS_STD ON MSP_VIEW_PROJ_PROJECTS_STD.ProjectUniqueID = MSP_VIEW_PROJ_TASKS_STD.ProjectUniqueID) 
WHERE MSP_VIEW_PROJ_TASKS_STD.TaskUniqueID = 0 AND MSP_VIEW_PROJ_PROJECTS_STD.ProjectUniqueID = @p0 
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjHeader TO MSProjectServerRole
GO



/* Query #85014 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetOutlcodesForProject
   @p0 INT
AS
SELECT CODE_UID, OC_FIELD_ID, OC_PARENT, OC_NAME, OC_CACHED_FULL_NAME
FROM MSP_OUTLINE_CODES MOC INNER JOIN MSP_FIELD_ATTRIBUTES MFA ON
(MOC.PROJ_ID=MFA.PROJ_ID AND MOC.OC_FIELD_ID=MFA.ATTRIB_FIELD_ID AND MFA.ATTRIB_ID=209)
WHERE (MFA.PROJ_ID = @p0) AND (MOC.CODE_UID > 0) AND (MFA.ATTRIB_VALUE & 32 > 0) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetOutlcodesForProject TO MSProjectServerRole
GO


/* Query #85017 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetRBSnames
   @p0 INT
AS
SELECT CODE_UID, OC_PARENT, OC_NAME, OC_CACHED_FULL_NAME FROM MSP_OUTLINE_CODES WHERE (PROJ_ID = @p0 ) AND (CODE_UID > 0) AND (OC_FIELD_ID = dbo.MSP_WEB_FN_GetRBSFieldID()) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetRBSnames TO MSProjectServerRole
GO


-----------------------------------------
-- Portfolio Modeling Helper functions --
-----------------------------------------
if EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.MSP_WEB_FN_MDL_GetViewProjResStd')
and xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.MSP_WEB_FN_MDL_GetViewProjResStd
GO


-------------------------------------------------------------------------------
--
-- FUNCTION: MSP_WEB_FN_MDL_GetViewProjResStd
-- INPUTS:
-- @ProjUID    Unique ID of the project whose resources we want
--
-- RETURNS:
-- A subset of MSP_VIEW_PROJ_RES_STD
--
-------------------------------------------------------------------------------
CREATE FUNCTION dbo.MSP_WEB_FN_MDL_GetViewProjResStd(
   @ProjUID    int
)
RETURNS @ResStd table (
      WPROJ_ID                                  int NOT NULL,
      ProjectUniqueID                           int NOT NULL,
      ResourceUniqueID                          int NOT NULL,
      ResourceEnterpriseUniqueID                int NULL,
      ResourceName                              nvarchar (255) NULL,
      ResourceStandardRate                      decimal (25,6) NULL,
      ResourceCost                              decimal (25,6) NULL,
      ResourceOvertimeRate                      decimal (25,6) NULL,
      ResourceCostPerUse                        decimal (25,6) NULL,
      ResourceMaxUnits                          decimal (25,6) NULL,
      ResourceCanLevel                          tinyint NULL,
      ResourceType                              smallint null,
      ResourceBookingType                       smallint null,
      ResourceInactive                          tinyint null
      )
as
BEGIN
   INSERT INTO @ResStd 
      SELECT WPROJ_ID, ProjectUniqueID, ResourceUniqueID, ResourceEnterpriseUniqueID, ResourceName, ResourceStandardRate, ResourceCost, ResourceOvertimeRate, ResourceCostPerUse, ResourceMaxUnits, ResourceCanLevel, ResourceType, ResourceBookingType, ResourceInactive
      FROM MSP_VIEW_PROJ_RES_STD 
      WHERE ProjectUniqueID = (@ProjUID)
   return
END
GO
GRANT SELECT ON dbo.MSP_WEB_FN_MDL_GetViewProjResStd TO MSProjectServerRole
GO


/* Query #85053 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetViewProjRes
   @p0 INT
AS
BEGIN
   SELECT ResourceUniqueID, RES_EUID AS ResourceEnterpriseUniqueID, ResourceName, ResourceStandardRate, ResourceCost, ResourceOvertimeRate, ResourceCostPerUse, ResourceMaxUnits, ResourceCanLevel, ResourceBookingType, ResourceEnterpriseOutlineCode1ID, ResourceEnterpriseOutlineCode2ID, ResourceEnterpriseOutlineCode3ID, ResourceEnterpriseOutlineCode4ID, ResourceEnterpriseOutlineCode5ID, ResourceEnterpriseOutlineCode6ID, ResourceEnterpriseOutlineCode7ID, ResourceEnterpriseOutlineCode8ID, ResourceEnterpriseOutlineCode9ID, ResourceEnterpriseOutlineCode10ID, ResourceEnterpriseOutlineCode11ID, ResourceEnterpriseOutlineCode12ID, ResourceEnterpriseOutlineCode13ID, ResourceEnterpriseOutlineCode14ID, ResourceEnterpriseOutlineCode15ID, ResourceEnterpriseOutlineCode16ID, ResourceEnterpriseOutlineCode17ID, ResourceEnterpriseOutlineCode18ID, ResourceEnterpriseOutlineCode19ID, ResourceEnterpriseOutlineCode20ID, ResourceEnterpriseOutlineCode21ID, ResourceEnterpriseOutlineCode22ID, ResourceEnterpriseOutlineCode23ID, ResourceEnterpriseOutlineCode24ID, ResourceEnterpriseOutlineCode25ID, ResourceEnterpriseOutlineCode26ID, ResourceEnterpriseOutlineCode27ID, ResourceEnterpriseOutlineCode28ID, ResourceEnterpriseOutlineCode29ID, ResourceEnterpriseOutlineCode30ID, ResourceEnterpriseRMV20ID, ResourceEnterpriseRMV21ID, ResourceEnterpriseRMV22ID, ResourceEnterpriseRMV23ID, ResourceEnterpriseRMV24ID, ResourceEnterpriseRMV25ID, ResourceEnterpriseRMV26ID, ResourceEnterpriseRMV27ID, ResourceEnterpriseRMV28ID, ResourceEnterpriseRMV29ID,ResourceType, ResourceEnterpriseGeneric, ResourceInactive, WRES_IS_ENABLED FROM MSP_WEB_FN_MDL_GetViewProjResStd(@p0) INNER JOIN MSP_VIEW_PROJ_RES_ENT ON (ProjectUniqueID = ENT_ProjectUniqueID AND ResourceUniqueID = ENT_ResourceUniqueID) LEFT OUTER JOIN MSP_WEB_RESOURCES ON (ResourceEnterpriseUniqueID = RES_EUID)
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetViewProjRes TO MSProjectServerRole
GO

/* Query #85056 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetViewProjAssns
   @p0 INT
AS
BEGIN
   declare @WPROJ_ID int
   select @WPROJ_ID = WPROJ_ID from MSP_VIEW_PROJ_PROJECTS_STD WHERE ProjectUniqueID = @p0

   SELECT AssignmentUniqueID, TaskUniqueID, A.ResourceUniqueID, AssignmentWork, AssignmentActualWork, AssignmentDelay, AssignmentUnits, AssignmentActualStart, 
          AssignmentActualFinish, AssignmentStart, AssignmentFinish, AssignmentEnterpriseOutlineCode1ID, AssignmentEnterpriseOutlineCode2ID, AssignmentEnterpriseOutlineCode3ID, 
          AssignmentEnterpriseOutlineCode4ID, AssignmentEnterpriseOutlineCode5ID, AssignmentEnterpriseOutlineCode6ID, AssignmentEnterpriseOutlineCode7ID, 
          AssignmentEnterpriseOutlineCode8ID, AssignmentEnterpriseOutlineCode9ID, AssignmentEnterpriseOutlineCode10ID, AssignmentEnterpriseOutlineCode11ID, 
          AssignmentEnterpriseOutlineCode12ID, AssignmentEnterpriseOutlineCode13ID, AssignmentEnterpriseOutlineCode14ID, AssignmentEnterpriseOutlineCode15ID, 
          AssignmentEnterpriseOutlineCode16ID, AssignmentEnterpriseOutlineCode17ID, AssignmentEnterpriseOutlineCode18ID, AssignmentEnterpriseOutlineCode19ID, 
          AssignmentEnterpriseOutlineCode20ID, AssignmentEnterpriseOutlineCode21ID, AssignmentEnterpriseOutlineCode22ID, AssignmentEnterpriseOutlineCode23ID, 
          AssignmentEnterpriseOutlineCode24ID, AssignmentEnterpriseOutlineCode25ID, AssignmentEnterpriseOutlineCode26ID, AssignmentEnterpriseOutlineCode27ID, 
          AssignmentEnterpriseOutlineCode28ID, AssignmentEnterpriseOutlineCode29ID, AssignmentEnterpriseOutlineCode30ID, 
          AssignmentEnterpriseRMV20ID, AssignmentEnterpriseRMV21ID, 
          AssignmentEnterpriseRMV22ID, AssignmentEnterpriseRMV23ID, 
          AssignmentEnterpriseRMV24ID, AssignmentEnterpriseRMV25ID, 
          AssignmentEnterpriseRMV26ID, AssignmentEnterpriseRMV27ID, 
          AssignmentEnterpriseRMV28ID, AssignmentEnterpriseRMV29ID,
AssignmentResourceRequestType, AssignmentWorkContour, ResourceType, ResourceBookingType, ResourceInactive 
      FROM((SELECT WPROJ_ID, ProjectUniqueID, AssignmentUniqueID, TaskUniqueID, ResourceEnterpriseUniqueID, ResourceUniqueID, AssignmentWork, AssignmentActualWork, 
                   AssignmentDelay, AssignmentUnits, AssignmentActualStart, AssignmentActualFinish, AssignmentStart, AssignmentFinish, AssignmentResourceRequestType, AssignmentWorkContour 
            FROM MSP_VIEW_PROJ_ASSN_STD WITH (NOLOCK) WHERE ProjectUniqueID = (@p0) AND ResourceUniqueID > 0) as A 
      INNER JOIN MSP_VIEW_PROJ_ASSN_ENT ON (AssignmentUniqueID = ENT_AssignmentUniqueID)) 
      INNER JOIN MSP_WEB_FN_MDL_GetViewProjResStd(@p0) as R ON A.ResourceUniqueID = R.ResourceUniqueID 
      WHERE MSP_VIEW_PROJ_ASSN_ENT.WPROJ_ID = @WPROJ_ID
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetViewProjAssns TO MSProjectServerRole
GO


/* Query #30038 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetSubwebSvrSTSUserPasswdForProjID
   @p0 INT
AS
SELECT WP.PROJ_NAME, WP.WPROJ_STS_SUBWEB_NAME, WP.WPROJ_ISSUE_LIST_NAME, WP.WPROJ_RISK_LIST_NAME, WS.*, WA.WADMIN_EXTRANET_SERVER_URL, WA.WADMIN_INTRANET_SERVER_URL, WA.WADMIN_STS_TEMPLATE_LCID FROM (MSP_WEB_PROJECTS WP INNER JOIN MSP_WEB_STS_SERVERS WS ON WP.WSTS_SERVER_ID=WS.WSTS_SERVER_ID), MSP_WEB_ADMIN WA WHERE WP.WPROJ_ID=(@p0) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetSubwebSvrSTSUserPasswdForProjID TO MSProjectServerRole
GO



/* Query #40026 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllTasksForIssuesEditForm
   @p0 INT,
   @p1 INT,
   @p2 INT,
   @p3 INT,
   @p4 UNIQUEIDENTIFIER
AS

SELECT TaskUniqueID as TASK_UID, TaskID as TASK_ID, 0 as WRES_ID, TaskName as TASK_NAME, TaskSummary as TASK_IS_SUMMARY, TaskOutlineLevel, o.WOBJ_ID, (CASE WHEN l1.WOBJLINK_TYPE IS NOT NULL THEN l1.WOBJLINK_TYPE WHEN l2.WOBJLINK_TYPE IS NOT NULL THEN l2.WOBJLINK_TYPE ELSE 0 END) AS WOBJLINK_TYPE 
FROM MSP_VIEW_PROJ_TASKS_STD VPTS LEFT JOIN MSP_WEB_ASSIGNMENTS WA ON (VPTS.WPROJ_ID=WA.WPROJ_ID and VPTS.TaskUniqueID=WA.TASK_UID)
LEFT JOIN MSP_WEB_OBJECTS o on VPTS.WPROJ_ID=o.WOBJ_PROJ_ID and VPTS.TaskUniqueID=o.WOBJ_TASK_ID and o.WOBJ_TYPE = 2 
LEFT JOIN MSP_WEB_OBJECT_LINKS l1 ON o.WOBJ_ID = l1.WOBJLINK_OBJECT1 AND l1.WOBJLINK_OBJECT2 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p3 AND WOBJ_TP_ID = @p1 AND WOBJ_LIST_NAME = @p4)
LEFT JOIN MSP_WEB_OBJECT_LINKS l2 ON o.WOBJ_ID = l2.WOBJLINK_OBJECT2 AND l2.WOBJLINK_OBJECT1 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p3 AND WOBJ_TP_ID = @p1 AND WOBJ_LIST_NAME = @p4)
WHERE VPTS.WPROJ_ID=@p0 AND TaskUniqueID>0 
and TaskUniqueID NOT IN (  SELECT WA2.TASK_UID 
                           FROM MSP_WEB_ASSIGNMENTS WA2 
                           WHERE WA2.WRES_ID=@p2 and WA2.WPROJ_ID=@p0 and WASSN_DELETED_IN_PROJ=0 and WASSN_REMOVED_BY_RESOURCE=0)
UNION 
SELECT TaskUniqueID as TASK_UID, TaskID as TASK_ID, WA.WRES_ID, TaskName as TASK_NAME, TaskSummary as TASK_IS_SUMMARY, TaskOutlineLevel, o.WOBJ_ID, (CASE WHEN l1.WOBJLINK_TYPE IS NOT NULL THEN l1.WOBJLINK_TYPE WHEN l2.WOBJLINK_TYPE IS NOT NULL THEN l2.WOBJLINK_TYPE ELSE 0 END) AS WOBJLINK_TYPE 
FROM MSP_VIEW_PROJ_TASKS_STD VPTS LEFT JOIN MSP_WEB_ASSIGNMENTS WA ON (VPTS.WPROJ_ID=WA.WPROJ_ID and VPTS.TaskUniqueID=WA.TASK_UID)
LEFT JOIN MSP_WEB_OBJECTS o on VPTS.WPROJ_ID=o.WOBJ_PROJ_ID and VPTS.TaskUniqueID=o.WOBJ_TASK_ID and o.WOBJ_TYPE = 2 
LEFT JOIN MSP_WEB_OBJECT_LINKS l1 ON o.WOBJ_ID = l1.WOBJLINK_OBJECT1 AND l1.WOBJLINK_OBJECT2 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p3 AND WOBJ_TP_ID = @p1 AND WOBJ_LIST_NAME = @p4)
LEFT JOIN MSP_WEB_OBJECT_LINKS l2 ON o.WOBJ_ID = l2.WOBJLINK_OBJECT2 AND l2.WOBJLINK_OBJECT1 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p3 AND WOBJ_TP_ID = @p1 AND WOBJ_LIST_NAME = @p4)
WHERE WRES_ID=@p2 and WASSN_DELETED_IN_PROJ=0 and WASSN_REMOVED_BY_RESOURCE=0 and VPTS.WPROJ_ID=@p0 and TaskUniqueID>0 and TASK_UID<>TASK_UID_SUMMARY 

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllTasksForIssuesEditForm TO MSProjectServerRole
GO



/* Query #40040 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllTasksForIssuesEditFormForResources
   @p0 INT,
   @p1 INT,
   @p2 INT,
   @p3 NTEXT,
   @p4 INT,
   @p5 UNIQUEIDENTIFIER
AS

SELECT TaskUniqueID as TASK_UID, TaskID as TASK_ID, 0 as WRES_ID, TaskName as TASK_NAME, TaskSummary as TASK_IS_SUMMARY, TaskOutlineLevel, o.WOBJ_ID, (CASE WHEN l1.WOBJLINK_TYPE IS NOT NULL THEN l1.WOBJLINK_TYPE WHEN l2.WOBJLINK_TYPE IS NOT NULL THEN l2.WOBJLINK_TYPE ELSE 0 END) AS WOBJLINK_TYPE 
FROM MSP_VIEW_PROJ_TASKS_STD VPTS LEFT JOIN MSP_WEB_ASSIGNMENTS WA ON (VPTS.WPROJ_ID=WA.WPROJ_ID and VPTS.TaskUniqueID=WA.TASK_UID)
LEFT JOIN MSP_WEB_OBJECTS o on VPTS.WPROJ_ID=o.WOBJ_PROJ_ID and VPTS.TaskUniqueID=o.WOBJ_TASK_ID and o.WOBJ_TYPE = 2 
LEFT JOIN MSP_WEB_OBJECT_LINKS l1 ON o.WOBJ_ID = l1.WOBJLINK_OBJECT1 AND l1.WOBJLINK_OBJECT2 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p4 AND WOBJ_TP_ID = @p1 AND WOBJ_LIST_NAME = @p5) 
LEFT JOIN MSP_WEB_OBJECT_LINKS l2 ON o.WOBJ_ID = l2.WOBJLINK_OBJECT2 AND l2.WOBJLINK_OBJECT1 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p4 AND WOBJ_TP_ID = @p1 AND WOBJ_LIST_NAME = @p5) 
WHERE VPTS.WPROJ_ID=@p0 AND TaskUniqueID>0 AND WA.WRES_ID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p3)) 
and TaskUniqueID NOT IN (  SELECT WA2.TASK_UID 
                           FROM MSP_WEB_ASSIGNMENTS WA2 
                           WHERE WA2.WRES_ID=@p2 and WA2.WPROJ_ID=@p0 and WASSN_DELETED_IN_PROJ=0 and WASSN_REMOVED_BY_RESOURCE=0)
UNION 
SELECT TaskUniqueID as TASK_UID, TaskID as TASK_ID, WA.WRES_ID, TaskName as TASK_NAME, TaskSummary as TASK_IS_SUMMARY, TaskOutlineLevel, o.WOBJ_ID, (CASE WHEN l1.WOBJLINK_TYPE IS NOT NULL THEN l1.WOBJLINK_TYPE WHEN l2.WOBJLINK_TYPE IS NOT NULL THEN l2.WOBJLINK_TYPE ELSE 0 END) AS WOBJLINK_TYPE 
FROM MSP_VIEW_PROJ_TASKS_STD VPTS LEFT JOIN MSP_WEB_ASSIGNMENTS WA ON (VPTS.WPROJ_ID=WA.WPROJ_ID and VPTS.TaskUniqueID=WA.TASK_UID)
LEFT JOIN MSP_WEB_OBJECTS o on VPTS.WPROJ_ID=o.WOBJ_PROJ_ID and VPTS.TaskUniqueID=o.WOBJ_TASK_ID and o.WOBJ_TYPE = 2 
LEFT JOIN MSP_WEB_OBJECT_LINKS l1 ON o.WOBJ_ID = l1.WOBJLINK_OBJECT1 AND l1.WOBJLINK_OBJECT2 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p4 AND WOBJ_TP_ID = @p1 AND WOBJ_LIST_NAME = @p5) 
LEFT JOIN MSP_WEB_OBJECT_LINKS l2 ON o.WOBJ_ID = l2.WOBJLINK_OBJECT2 AND l2.WOBJLINK_OBJECT1 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p4 AND WOBJ_TP_ID = @p1 AND WOBJ_LIST_NAME = @p5) 
WHERE WRES_ID=@p2 and WASSN_DELETED_IN_PROJ=0 and WASSN_REMOVED_BY_RESOURCE=0 and VPTS.WPROJ_ID=@p0 and TaskUniqueID>0 and TASK_UID<>TASK_UID_SUMMARY 

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllTasksForIssuesEditFormForResources TO MSProjectServerRole
GO



/* Query #40041 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllTasksForIssuesEditFormForResourcesNotMe
   @p0 INT,
   @p1 INT,
   @p2 INT,
   @p3 NTEXT,
   @p4 INT,
   @p5 UNIQUEIDENTIFIER
AS

SELECT DISTINCT TaskUniqueID as TASK_UID, TaskID as TASK_ID, 0 as WRES_ID, TaskName as TASK_NAME, TaskSummary as TASK_IS_SUMMARY, TaskOutlineLevel, o.WOBJ_ID, (CASE WHEN l1.WOBJLINK_TYPE IS NOT NULL THEN l1.WOBJLINK_TYPE WHEN l2.WOBJLINK_TYPE IS NOT NULL THEN l2.WOBJLINK_TYPE ELSE 0 END) AS WOBJLINK_TYPE 
FROM MSP_VIEW_PROJ_TASKS_STD VPTS LEFT JOIN MSP_WEB_ASSIGNMENTS WA ON (VPTS.WPROJ_ID=WA.WPROJ_ID and VPTS.TaskUniqueID=WA.TASK_UID)
LEFT JOIN MSP_WEB_OBJECTS o on VPTS.WPROJ_ID=o.WOBJ_PROJ_ID and VPTS.TaskUniqueID=o.WOBJ_TASK_ID and o.WOBJ_TYPE = 2 
LEFT JOIN MSP_WEB_OBJECT_LINKS l1 ON o.WOBJ_ID = l1.WOBJLINK_OBJECT1 AND l1.WOBJLINK_OBJECT2 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p4 AND WOBJ_TP_ID = @p1 AND WOBJ_LIST_NAME = @p5) 
LEFT JOIN MSP_WEB_OBJECT_LINKS l2 ON o.WOBJ_ID = l2.WOBJLINK_OBJECT2 AND l2.WOBJLINK_OBJECT1 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p4 AND WOBJ_TP_ID = @p1 AND WOBJ_LIST_NAME = @p5) 
WHERE VPTS.WPROJ_ID=@p0 AND TaskUniqueID>0 AND WA.WRES_ID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p3)) 

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllTasksForIssuesEditFormForResourcesNotMe TO MSProjectServerRole
GO



/* Query #40043 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllTasksForIssuesEditFormForMe
   @p0 INT,
   @p1 INT,
   @p2 INT,
   @p3 INT,
   @p4 UNIQUEIDENTIFIER
AS

SELECT DISTINCT TaskUniqueID as TASK_UID, TaskID as TASK_ID, WA.WRES_ID, TaskName as TASK_NAME, TaskSummary as TASK_IS_SUMMARY, TaskOutlineLevel, o.WOBJ_ID, (CASE WHEN l1.WOBJLINK_TYPE IS NOT NULL THEN l1.WOBJLINK_TYPE WHEN l2.WOBJLINK_TYPE IS NOT NULL THEN l2.WOBJLINK_TYPE ELSE 0 END) AS WOBJLINK_TYPE 
FROM MSP_VIEW_PROJ_TASKS_STD VPTS LEFT JOIN MSP_WEB_ASSIGNMENTS WA ON (VPTS.WPROJ_ID=WA.WPROJ_ID and VPTS.TaskUniqueID=WA.TASK_UID)
LEFT JOIN MSP_WEB_OBJECTS o on VPTS.WPROJ_ID=o.WOBJ_PROJ_ID and VPTS.TaskUniqueID=o.WOBJ_TASK_ID and o.WOBJ_TYPE = 2 
LEFT JOIN MSP_WEB_OBJECT_LINKS l1 ON o.WOBJ_ID = l1.WOBJLINK_OBJECT1 AND l1.WOBJLINK_OBJECT2 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p3 AND WOBJ_TP_ID = @p1 AND WOBJ_LIST_NAME = @p4) 
LEFT JOIN MSP_WEB_OBJECT_LINKS l2 ON o.WOBJ_ID = l2.WOBJLINK_OBJECT2 AND l2.WOBJLINK_OBJECT1 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p3 AND WOBJ_TP_ID = @p1 AND WOBJ_LIST_NAME = @p4) 
WHERE WRES_ID=@p2 and WASSN_DELETED_IN_PROJ=0 and WASSN_REMOVED_BY_RESOURCE=0 and VPTS.WPROJ_ID=@p0 and TaskUniqueID>0 and TASK_UID<>TASK_UID_SUMMARY 

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllTasksForIssuesEditFormForMe TO MSProjectServerRole
GO



/* Query #85018 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_DeleteModel
   @p0 INT
AS
DELETE FROM MSP_WEB_MODELS WHERE WMOD_MODEL_UID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_DeleteModel TO MSProjectServerRole
GO



/* Query #85020 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetSpecificRBSName
   @p0 INT,
   @p1 INT
AS
SELECT CODE_UID, OC_PARENT, OC_NAME, OC_CACHED_FULL_NAME FROM MSP_OUTLINE_CODES WHERE (PROJ_ID = @p0 ) AND (CODE_UID = @p1) AND (OC_FIELD_ID = dbo.MSP_WEB_FN_GetRBSFieldID()) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetSpecificRBSName TO MSProjectServerRole
GO



/* Query #85058 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetViewProjCal
   @p0 int
as
BEGIN

SELECT WPROJ_ID, ProjectUniqueID, CalendarUniqueID, CalendarWeekday, CalendarWorking,
	CalendarFromDate, CalendarToDate,
	CalendarFromTime1, CalendarToTime1, CalendarFromTime2, CalendarToTime2, CalendarFromTime3, 
	CalendarToTime3, CalendarFromTime4, CalendarToTime4, 	CalendarFromTime5, CalendarToTime5
	from MSP_VIEW_PROJ_CAL_DATA where ProjectUniqueID = @p0
UNION
select WPROJ_ID, ProjectUniqueID, CalendarUniqueID, 0 as CalendarWeekday, CalendarExceptionWorking as CalendarWorking,
	CalendarExceptionFromDate as CalendarFromDate, CalendarExceptionToDate As CalendarToDate,
	CalendarExceptionFromTime1 As CalendarFromTime1, CalendarExceptionToTime1 As CalendarToTime1,
	CalendarExceptionFromTime2 As CalendarFromTime2, CalendarExceptionToTime2 As CalendarToTime2,
	CalendarExceptionFromTime3 As CalendarFromTime3, CalendarExceptionToTime3 As CalendarToTime3,
	Null As CalendarFromTime4, Null As CalendarToTime4,
	Null As CalendarFromTime5, Null As CalendarToTime5
	from MSP_VIEW_PROJ_CAL_EXCEPTIONS where ProjectUniqueID = @p0
ORDER BY ProjectUniqueID, CalendarUniqueID

return
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetViewProjCal TO MSProjectServerRole
GO



/* Query #365000 */
CREATE PROCEDURE dbo.MSP_WEB_SP_BUS_GetToDoListXMLInfo
   @p0 INT
AS
select P.PROJ_NAME, A.WASSN_ID, A.WRES_ID, 
       R.RES_NAME, R.WRES_USE_NT_LOGON, R.WRES_NT_ACCOUNT, 
       R.WRES_EMAIL, R.WRES_IS_ENABLED, R.RES_PHONETICS, 
       TASK_NAME, ASSN_START_DATE, ASSN_FINISH_DATE, 
       WASSN_PCT_COMP, WASSN_COMMENTS, F.INT_VAL 
  from ((MSP_WEB_PROJECTS P INNER JOIN MSP_WEB_ASSIGNMENTS A ON P.WPROJ_ID=A.WPROJ_ID)
       LEFT JOIN MSP_WEB_RESOURCES R ON A.WRES_ID=R.WRES_ID)
       INNER JOIN MSP_WEB_WORKGROUP_FIELDS F ON A.WASSN_ID=F.WASSN_ID
 where P.WPROJ_ID=@p0
   and A.WRES_ID<>-1 
   and F.FIELD_ID=1073741849 

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_BUS_GetToDoListXMLInfo TO MSProjectServerRole
GO



/* Query #10025 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetDistinctResInfoForAssnId
   @p0 NTEXT
AS
Select Distinct MSP_WEB_RESOURCES.WRES_ID, MSP_WEB_RESOURCES.RESERVED_DATA3, MSP_WEB_RESOURCES.RESERVED_DATA4 From MSP_WEB_RESOURCES, MSP_WEB_ASSIGNMENTS Where WRES_IS_ENABLED<>0 and MSP_WEB_RESOURCES.WRES_ID = MSP_WEB_ASSIGNMENTS.WRES_ID and MSP_WEB_ASSIGNMENTS.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetDistinctResInfoForAssnId TO MSProjectServerRole
GO



/* Query #10026 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetDistinctMgrResInfoForAssnId
   @p0 NTEXT
AS
Select Distinct MSP_WEB_RESOURCES.WRES_ID, MSP_WEB_RESOURCES.RESERVED_DATA3, MSP_WEB_RESOURCES.RESERVED_DATA4 From MSP_WEB_RESOURCES, MSP_WEB_ASSIGNMENTS Where WRES_IS_ENABLED<>0 and MSP_WEB_RESOURCES.WRES_ID = MSP_WEB_ASSIGNMENTS.WRES_ID_MGR and MSP_WEB_ASSIGNMENTS.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetDistinctMgrResInfoForAssnId TO MSProjectServerRole
GO



/* Query #10029 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetBatchCustomFieldsForAssnIDFieldID
   @p0 NTEXT,
   @p1 NTEXT
AS
Select * from MSP_WEB_WORKGROUP_FIELDS where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and FIELD_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetBatchCustomFieldsForAssnIDFieldID TO MSProjectServerRole
GO



/* Query #10050 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAssnCreatedByResForProjList
   @p0 INT,
   @p1 NTEXT
AS
Select WASSN_ID,WASSN_CREATED_BY_RES From MSP_WEB_ASSIGNMENTS Where WRES_ID_MGR=@p0 and WASSN_CREATED_BY_RES=4 and WASSN_IS_CONFIRMED<>0 and WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAssnCreatedByResForProjList TO MSProjectServerRole
GO



/* Query #10052 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_SelectedNewTasksCreatedByResForMgr
   @p0 INT,
   @p1 NTEXT
AS
Select WASSN_ID,WASSN_CREATED_BY_RES,WASSN_ASSIGNED_TO_EXISTING,WASSN_SEND_UPDATE_DATE,WRES_ID_MGR,WA.WPROJ_ID,PROJ_NAME,RES_NAME from MSP_WEB_ASSIGNMENTS WA,MSP_WEB_PROJECTS WP,MSP_WEB_RESOURCES WR Where WA.WPROJ_ID=WP.WPROJ_ID and WA.WRES_ID_MGR=WR.WRES_ID and WA.WRES_ID=@p0 and WASSN_CREATED_BY_RES=1 and WASSN_REMOVED_BY_RESOURCE=0 and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) order by RES_NAME,WA.WPROJ_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_SelectedNewTasksCreatedByResForMgr TO MSProjectServerRole
GO



/* Query #10080 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetMsgIDFromList
   @p0 NTEXT
AS
Select WMSG_ID From MSP_WEB_MESSAGES_ASSIGNMENTS Where WMSG_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetMsgIDFromList TO MSProjectServerRole
GO



/* Query #10084 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetRequestsNotInList
   @p0 INT,
   @p1 NTEXT
AS
Select * From MSP_WEB_STATUS_REQUESTS Where WSR_ID=@p0 and WRES_ID_RECEIVER not in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) Order By WRES_ID_RECEIVER RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetRequestsNotInList TO MSProjectServerRole
GO



/* Query #10114 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetActualsForResID
   @p0 INT,
   @p1 NTEXT
AS
Select * from MSP_WEB_WORK Where WRES_ID=@p0 and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetActualsForResID TO MSProjectServerRole
GO



/* Query #10120 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteBatchActualsForAssnIDAndType
   @p0 NTEXT,
   @p1 NTEXT
AS
Delete from MSP_WEB_WORK Where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and WWORK_TYPE in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteBatchActualsForAssnIDAndType TO MSProjectServerRole
GO



/* Query #10122 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetCFInfoForFieldID
   @p0 NTEXT
AS
Select * From MSP_WEB_WORKGROUP_FIELDS_INFO Where FIELD_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetCFInfoForFieldID TO MSProjectServerRole
GO



/* Query #10123 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetMsgIDForResID
   @p0 INT,
   @p1 NTEXT
AS
Select WMSG_ID,WMSG_PROJ_TYPE From MSP_WEB_MESSAGES Where WRES_ID_RECEIVER=@p0 and WMSG_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetMsgIDForResID TO MSProjectServerRole
GO



/* Query #10130 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetBatchAllAssnForFileIdAssnProjIdNoResId
   @p0 INT,
   @p1 NTEXT
AS
Select * From MSP_WEB_ASSIGNMENTS Where WPROJ_ID=@p0 and ASSN_UID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetBatchAllAssnForFileIdAssnProjIdNoResId TO MSProjectServerRole
GO



/* Query #10131 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetBatchAllAssnForFileIdAssnIdNoResId
   @p0 INT,
   @p1 NTEXT
AS
Select * From MSP_WEB_ASSIGNMENTS Where WPROJ_ID=@p0 and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetBatchAllAssnForFileIdAssnIdNoResId TO MSProjectServerRole
GO



/* Query #10132 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetBatchAllAssnForFileIdAssnProjIdOrAssnIdNoResId
   @p0 INT,
   @p1 NTEXT,
   @p2 NTEXT
AS
Select * From MSP_WEB_ASSIGNMENTS Where WPROJ_ID=@p0 and (ASSN_UID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) or WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p2))) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetBatchAllAssnForFileIdAssnProjIdOrAssnIdNoResId TO MSProjectServerRole
GO



/* Query #10133 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetBatchAllAssnForFileIdAssnProjId
   @p0 INT,
   @p1 INT,
   @p2 NTEXT
AS
Select * From MSP_WEB_ASSIGNMENTS Where WPROJ_ID=@p0 and WRES_ID=@p1 and ASSN_UID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p2)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetBatchAllAssnForFileIdAssnProjId TO MSProjectServerRole
GO



/* Query #10134 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetBatchAllAssnForFileIdAssnId
   @p0 INT,
   @p1 INT,
   @p2 NTEXT
AS
Select * From MSP_WEB_ASSIGNMENTS Where WPROJ_ID=@p0 and WRES_ID=@p1 and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p2)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetBatchAllAssnForFileIdAssnId TO MSProjectServerRole
GO



/* Query #10135 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetBatchAllAssnForFileIdAssnProjIdOrAssnId
   @p0 INT,
   @p1 INT,
   @p2 NTEXT,
   @p3 NTEXT
AS
Select * From MSP_WEB_ASSIGNMENTS Where WPROJ_ID=@p0 and WRES_ID=@p1 and (ASSN_UID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p2)) or WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p3))) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetBatchAllAssnForFileIdAssnProjIdOrAssnId TO MSProjectServerRole
GO



/* Query #10138 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteProjectCFInfoForFileIDAndCFIds
   @p0 INT,
   @p1 NTEXT
AS
delete From MSP_WEB_PROJECT_WORKGROUP_INFO Where WPROJ_ID=@p0 and CUSTFIELD_INFO_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteProjectCFInfoForFileIDAndCFIds TO MSProjectServerRole
GO



/* Query #10167 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_RemoveFromTasksPage
   @p0 NTEXT,
   @p1 INT
AS
Update MSP_WEB_ASSIGNMENTS set WASSN_REMOVED_BY_RESOURCE=1 where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and WRES_ID=@p1 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_RemoveFromTasksPage TO MSProjectServerRole
GO



/* Query #10168 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_UpdateOldDelegKeepCopys
   @p0 NTEXT,
   @p1 INT,
   @p2 TINYINT
AS
Update MSP_WEB_DELEGATION_ASSIGNMENTS set WDELEG_KEEP_COPY=@p2 where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and WDELEG_ID in (Select WD.WDELEG_ID From MSP_WEB_DELEGATIONS WD Where WD.WRES_ID_DELEGATOR=@p1) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_UpdateOldDelegKeepCopys TO MSProjectServerRole
GO



/* Query #10170 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAssnFromList
   @p0 NTEXT,
   @p1 INT
AS
Select TASK_NAME,ASSN_START_DATE,ASSN_FINISH_DATE,ASSN_WORK,ASSN_REM_WORK,ASSN_ACT_WORK,WASSN_COMMENTS,WASSN_PCT_COMP,WASSN_IS_CONFIRMED,WASSN_MGR_UPDATED,WASSN_CREATED_BY_RES,WASSN_DELETED_IN_PROJ,WASSN_SEND_UPDATE_NEEDED,WASSN_DELEG_ACCEPTED,WASSN_DELEG_APPROVED,WASSN_LAST_DELEG_ID,WASSN_DELEG_PENDING,WASSN_REQUEST_UPDATE,WASSN_RESOURCE_UPDATE,WRES_ID_TEAM_LEAD,WASSN_IS_DELEGATED,WASSN_IS_NEW_ASSN,WASSN_REMOVED_BY_RESOURCE,WASSN_ID,ASSN_UID,WASSN_PARENT_ID,TASK_ID,TASK_UID,TASK_IS_SUMMARY,TASK_UID_SUMMARY,WRES_ID_MGR,WRES_ID_TEAM_LEAD,WASSN_CURRENT_TRACKING_MODE,WASSN_UPDATE_TRACKING_MODE,WA.WRES_ID,WA.RESERVED_DATA1,WA.RESERVED_DATA2,WA.RESERVED_DATA3,WPROJ_ID From MSP_WEB_ASSIGNMENTS WA Where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and WA.WRES_ID=@p1 ORDER BY WRES_ID_MGR RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAssnFromList TO MSProjectServerRole
GO



/* Query #10178 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetDistinctDelegMsgResInfoForAssnID
   @p0 NTEXT
AS
Select Distinct MSP_WEB_RESOURCES.WRES_ID, MSP_WEB_RESOURCES.RESERVED_DATA3, MSP_WEB_RESOURCES.RESERVED_DATA4 From MSP_WEB_RESOURCES,MSP_WEB_ASSIGNMENTS Where WRES_IS_ENABLED<>0 and MSP_WEB_ASSIGNMENTS.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and MSP_WEB_ASSIGNMENTS.WRES_ID=MSP_WEB_RESOURCES.WRES_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetDistinctDelegMsgResInfoForAssnID TO MSProjectServerRole
GO



/* Query #10186 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetDistinctProjectsForAssnIDList
   @p0 NTEXT
AS
Select Distinct PROJ_NAME From MSP_WEB_PROJECTS,MSP_WEB_ASSIGNMENTS Where MSP_WEB_ASSIGNMENTS.WPROJ_ID=MSP_WEB_PROJECTS.WPROJ_ID and MSP_WEB_ASSIGNMENTS.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) Order By PROJ_NAME RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetDistinctProjectsForAssnIDList TO MSProjectServerRole
GO



/* Query #10187 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetDistinctResourcesForAssnIDList
   @p0 NTEXT
AS
Select Distinct RES_NAME From MSP_WEB_RESOURCES,MSP_WEB_ASSIGNMENTS Where WRES_IS_ENABLED<>0 and MSP_WEB_ASSIGNMENTS.WRES_ID=MSP_WEB_RESOURCES.WRES_ID and MSP_WEB_ASSIGNMENTS.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) Order By RES_NAME RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetDistinctResourcesForAssnIDList TO MSProjectServerRole
GO



/* Query #10188 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetLeadAssignmentsForAssnList
   @p0 INT,
   @p1 NTEXT
AS
Select WASSN_ID,WRES_ID,WASSN_REQUEST_UPDATE,WASSN_REMOVED_BY_RESOURCE,WPROJ_ID 
From MSP_WEB_ASSIGNMENTS 
Where WRES_ID_TEAM_LEAD=@p0 and
WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) 
Order By WPROJ_ID,WRES_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetLeadAssignmentsForAssnList TO MSProjectServerRole
GO



/* Query #10191 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetDistinctResourcesForLeadChange
   @p0 INT,
   @p1 NTEXT
AS
Select Distinct RES_NAME From MSP_WEB_RESOURCES Where WRES_IS_ENABLED<>0 and WRES_ID in (Select WRES_ID From MSP_WEB_ASSIGNMENTS Where WRES_ID_TEAM_LEAD=@p0 and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1))) or WRES_ID in (Select WRES_ID_MGR From MSP_WEB_ASSIGNMENTS Where WRES_ID_TEAM_LEAD=@p0 and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1))) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetDistinctResourcesForLeadChange TO MSProjectServerRole
GO



/* Query #10192 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetDistinctManagersForDelegation
   @p0 INT,
   @p1 NTEXT
AS
Select Distinct RES_NAME From MSP_WEB_RESOURCES Where WRES_IS_ENABLED<>0 and WRES_ID in (Select WRES_ID_MGR From MSP_WEB_ASSIGNMENTS Where WRES_ID=@p0 and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1))) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetDistinctManagersForDelegation TO MSProjectServerRole
GO



/* Query #10193 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetDistinctTeamLeadResInfoForAssnId
   @p0 NTEXT
AS
Select Distinct MSP_WEB_RESOURCES.WRES_ID, MSP_WEB_RESOURCES.RESERVED_DATA3, MSP_WEB_RESOURCES.RESERVED_DATA4 From MSP_WEB_RESOURCES, MSP_WEB_ASSIGNMENTS Where WRES_IS_ENABLED<>0 and MSP_WEB_RESOURCES.WRES_ID = MSP_WEB_ASSIGNMENTS.WRES_ID_TEAM_LEAD and MSP_WEB_ASSIGNMENTS.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetDistinctTeamLeadResInfoForAssnId TO MSProjectServerRole
GO



/* Query #10194 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAssnsFromListOrderByResID
   @p0 NTEXT
AS
Select WASSN_REMOVED_BY_RESOURCE,WASSN_ID,WRES_ID,WRES_ID_TEAM_LEAD,WPROJ_ID 
From MSP_WEB_ASSIGNMENTS 
Where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) 
Order By WPROJ_ID,WRES_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAssnsFromListOrderByResID TO MSProjectServerRole
GO



/* Query #10195 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAssnsFromListOrderByResIDTeamLead
   @p0 NTEXT
AS
Select WASSN_REMOVED_BY_RESOURCE,WASSN_ID,WRES_ID_TEAM_LEAD,WPROJ_ID From MSP_WEB_ASSIGNMENTS Where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) Order By WPROJ_ID,WRES_ID_TEAM_LEAD RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAssnsFromListOrderByResIDTeamLead TO MSProjectServerRole
GO



/* Query #10196 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAssnsFromListOrderByResIDMgr
   @p0 NTEXT
AS
Select WASSN_REMOVED_BY_RESOURCE,WASSN_ID,WRES_ID_MGR,WPROJ_ID From MSP_WEB_ASSIGNMENTS Where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) Order By WPROJ_ID,WRES_ID_MGR RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAssnsFromListOrderByResIDMgr TO MSProjectServerRole
GO



/* Query #10198 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_SelectTasksToDelegate
   @p0 NTEXT
AS
SELECT WASSN_NOTE_STATUS, (case when WASSN_HISTORY_NOTES is not null then 1 else 0 end) as bIsHistory, WASSN_ID, TASK_ID, TASK_NAME, WASSN_COMMENTS, PROJ_NAME, WRES_ID_TEAM_LEAD, WR1.RES_NAME, WR2.RES_NAME AS MGR_RES_NAME FROM MSP_WEB_ASSIGNMENTS WA,MSP_WEB_PROJECTS,MSP_WEB_RESOURCES WR1,MSP_WEB_RESOURCES WR2 WHERE WA.WPROJ_ID=MSP_WEB_PROJECTS.WPROJ_ID and WA.WRES_ID=WR1.WRES_ID and WA.WRES_ID_MGR=WR2.WRES_ID and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) Order By WA.WPROJ_ID,WA.TASK_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_SelectTasksToDelegate TO MSProjectServerRole
GO



/* Query #10199 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_SelectResNameFromResList
   @p0 NTEXT
AS
Select WRES_ID,RES_NAME From MSP_WEB_RESOURCES Where WRES_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_SelectResNameFromResList TO MSProjectServerRole
GO



/* Query #13001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetNewTasksFromAssnID
   @p0 NTEXT
AS
Select 
ASSN_UID,
WLOCAL_PATH,
MSP_WEB_RESOURCES.RES_NAME,
MSP_WEB_RESOURCES.WRES_USE_NT_LOGON,
MSP_WEB_RESOURCES.WRES_NT_ACCOUNT,
TASK_NAME,
ASSN_START_DATE,
ASSN_FINISH_DATE,
ASSN_WORK,
ASSN_REM_WORK,
WASSN_COMMENTS,
TASK_UID_SUMMARY,
WASSN_ID,
WASSN_PARENT_ID,
TASK_UID, 
WASSN_PCT_COMP,
WASSN_CURRENT_TRACKING_MODE,
WASSN_UPDATE_TRACKING_MODE
From MSP_WEB_ASSIGNMENTS
INNER JOIN MSP_WEB_PROJECTS  ON MSP_WEB_ASSIGNMENTS.WPROJ_ID=MSP_WEB_PROJECTS.WPROJ_ID
INNER JOIN MSP_WEB_RESOURCES ON MSP_WEB_ASSIGNMENTS.WRES_ID=MSP_WEB_RESOURCES.WRES_ID
Where WRES_IS_ENABLED<>0 and MSP_WEB_ASSIGNMENTS.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetNewTasksFromAssnID TO MSProjectServerRole
GO



/* Query #13002 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAcceptedTasksFromAssnID
   @p0 NTEXT
AS
Select WASSN_ID,ASSN_UID, WRES_ID,TASK_NAME,ASSN_START_DATE,ASSN_FINISH_DATE,ASSN_WORK,ASSN_REM_WORK,WASSN_COMMENTS,WASSN_IS_CONFIRMED,WASSN_DELETED_IN_PROJ,WASSN_SEND_UPDATE_NEEDED,WASSN_PCT_COMP,WASSN_CURRENT_TRACKING_MODE,WASSN_UPDATE_TRACKING_MODE From MSP_WEB_ASSIGNMENTS Where WASSN_ID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAcceptedTasksFromAssnID TO MSProjectServerRole
GO



/* Query #15001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetLeafTasksForListOfSumTasks
   @p0 INT,
   @p1 NTEXT
AS
select WASSN_ID,WASSN_PARENT_ID,WPROJ_ID,TASK_UID_SUMMARY from MSP_WEB_ASSIGNMENTS where TASK_IS_SUMMARY=0 and WRES_ID=@p0 and WASSN_PARENT_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetLeafTasksForListOfSumTasks TO MSProjectServerRole
GO



/* Query #15002 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteListOfAssignmentsFromAssnTable
   @p0 NTEXT
AS
delete from MSP_WEB_MESSAGES_ASSIGNMENTS where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteListOfAssignmentsFromAssnTable TO MSProjectServerRole
GO



/* Query #15003 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteListOfAssignMsgFromMsgAssnTable
   @p0 NTEXT
AS
delete from MSP_WEB_ASSIGNMENTS where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteListOfAssignMsgFromMsgAssnTable TO MSProjectServerRole
GO



/* Query #15004 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetLeafTasksForListOfSumTasksWDeleg
   @p0 INT,
   @p1 NTEXT
AS
select WASSN_ID,WASSN_PARENT_ID,WPROJ_ID,TASK_UID_SUMMARY
from MSP_WEB_ASSIGNMENTS 
where TASK_IS_SUMMARY=0 and 
      WRES_ID=@p0 and 
      WASSN_PARENT_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) 
union 
select WA.WASSN_ID,WASSN_PARENT_ID,WPROJ_ID,TASK_UID_SUMMARY 
from MSP_WEB_ASSIGNMENTS WA
where WA.WASSN_ID in (
                      select WDA.WASSN_ID 
                      from MSP_WEB_DELEGATION_ASSIGNMENTS WDA INNER JOIN MSP_WEB_DELEGATIONS WD ON WDA.WDELEG_ID=WD.WDELEG_ID 
                      where WD.WRES_ID_DELEGATOR=@p0 and WDA.WDELEG_KEEP_COPY<>0 and WD.WDELEG_REJECT=0)
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetLeafTasksForListOfSumTasksWDeleg TO MSProjectServerRole
GO



/* Query #15020 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ReQueryAssnsForManualMerging
   @p0 NTEXT
AS

select * from MSP_WEB_ASSIGNMENTS where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ReQueryAssnsForManualMerging TO MSProjectServerRole
GO



/* Query #15021 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ReQueryCustomsForManualMerging
   @p0 NTEXT,
   @p1 NTEXT
AS
select MSP_WEB_WORKGROUP_FIELDS.* from MSP_WEB_WORKGROUP_FIELDS where MSP_WEB_WORKGROUP_FIELDS.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and MSP_WEB_WORKGROUP_FIELDS.FIELD_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ReQueryCustomsForManualMerging TO MSProjectServerRole
GO



/* Query #15022 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetActualsForIntegrityCheck
   @p0 INT,
   @p1 NTEXT,
   @p2 DATETIME,
   @p3 DATETIME
AS
select WASSN_ID,WWORK_START,WWORK_FINISH,WWORK_TYPE from MSP_WEB_WORK where WRES_ID=@p0 and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) and ((WWORK_START>=@p2 and WWORK_START<=@p3) or (WWORK_START<@p2 and WWORK_FINISH>=@p2)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetActualsForIntegrityCheck TO MSProjectServerRole
GO



/* Query #15023 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetConflictNames
   @p0 NTEXT,
   @p1 NTEXT
AS
select TASK_NAME,CUSTFIELD_NAME from MSP_WEB_ASSIGNMENTS,MSP_WEB_WORKGROUP_FIELDS,MSP_WEB_WORKGROUP_FIELDS_INFO,MSP_WEB_PROJECT_WORKGROUP_INFO where MSP_WEB_ASSIGNMENTS.WASSN_ID=MSP_WEB_WORKGROUP_FIELDS.WASSN_ID and MSP_WEB_WORKGROUP_FIELDS.FIELD_ID=MSP_WEB_WORKGROUP_FIELDS_INFO.FIELD_ID and MSP_WEB_WORKGROUP_FIELDS_INFO.CUSTFIELD_INFO_ID=MSP_WEB_PROJECT_WORKGROUP_INFO.CUSTFIELD_INFO_ID and MSP_WEB_PROJECT_WORKGROUP_INFO.WPROJ_ID=MSP_WEB_ASSIGNMENTS.WPROJ_ID and MSP_WEB_ASSIGNMENTS.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and MSP_WEB_WORKGROUP_FIELDS.FIELD_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetConflictNames TO MSProjectServerRole
GO

/* Query #15024 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ReQueryApprovalForManualMerging
   @p0 NTEXT
AS
  SELECT WAPPROVAL_ID,WASSN_ID, WRES_ID_APPROVER, WAPPROVAL_STATUS 
  FROM MSP_WEB_WORK_APPROVAL WWA
  INNER JOIN dbo.MSP_WEB_FN_ConvertListToTable(@p0) LT ON (LT.TokenVal = WWA.WAPPROVAL_ID)
  
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ReQueryApprovalForManualMerging TO MSProjectServerRole
GO




/* Query #16036 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteAllObsoleteNonNormalViewsWExceptions
   @p0 INT,
   @p1 NTEXT
AS
Delete From MSP_WEB_VIEW_REPORTS Where WVIEW_REPORT_KIND<>0 and WVIEW_TYPE=@p0 and WVIEW_ID not in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteAllObsoleteNonNormalViewsWExceptions TO MSProjectServerRole
GO



/* Query #16057 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_WebclientViewAllFieldList
   @p0 INT,
   @p2 INT,
   @p3 NTEXT
AS
SELECT VF.WFIELD_ID,WC.CONV_STRING,WFIELD_NAME_SQL,WFIELD_TEXTCONV_TYPE,WFIELD_IS_CUSTOM_FIELD,WFI.CUSTFIELD_INFO_ID,VRF.WVIEW_FIELD_WIDTH,VRF.WVIEW_FIELD_AUTOSIZE,((CASE WHEN CUSTFIELD_NAME is null OR CUSTFIELD_NAME=N'' THEN WC2.CONV_STRING ELSE CUSTFIELD_NAME END)) as CUSTFIELD_NAME
FROM 
MSP_WEB_VIEW_REPORTS VR INNER JOIN MSP_WEB_VIEW_REPORTS_FIELDS VRF ON VR.WVIEW_ID=VRF.WVIEW_ID
INNER JOIN MSP_WEB_VIEW_FIELDS VF ON VRF.WFIELD_ID=VF.WFIELD_ID 
INNER JOIN MSP_WEB_CONVERSIONS WC ON VF.WFIELD_NAME_CONV_VALUE=WC.CONV_VALUE 
LEFT JOIN MSP_WEB_WORKGROUP_FIELDS_INFO WFI ON VF.WFIELD_ID=WFI.FIELD_ID 
LEFT JOIN MSP_WEB_CONVERSIONS WC2 ON (WFI.CONV_VALUE=WC2.CONV_VALUE and WC2.LANG_ID=@p2) 
WHERE VR.WVIEW_ID=@p0 and WC.LANG_ID=@p2 and (WFI.CUSTFIELD_INFO_ID Is Null or WFI.CUSTFIELD_INFO_ID in (SELECT DISTINCT PWI.CUSTFIELD_INFO_ID FROM MSP_WEB_ASSIGNMENTS WA INNER JOIN MSP_WEB_PROJECT_WORKGROUP_INFO PWI ON WA.WPROJ_ID=PWI.WPROJ_ID WHERE WA.WRES_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p3)))) Order By WVIEW_FIELD_ORDER RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_WebclientViewAllFieldList TO MSProjectServerRole
GO



/* Query #16058 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetEOrDViewByViewNameAndType
   @p0 NVARCHAR(255),
   @p1 INT
AS
  Select WVIEW_ID From MSP_WEB_VIEW_REPORTS Where lower(WVIEW_NAME)=lower(@p0) and WVIEW_TYPE=@p1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetEOrDViewByViewNameAndType TO MSProjectServerRole
GO



/* Query #17213 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteAssnForAssnIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_ASSIGNMENTS where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteAssnForAssnIDs TO MSProjectServerRole
GO



/* Query #17214 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteActualsForAssnIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_WORK where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteActualsForAssnIDs TO MSProjectServerRole
GO



/* Query #17215 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteCFForAssnIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_WORKGROUP_FIELDS where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteCFForAssnIDs TO MSProjectServerRole
GO



/* Query #17216 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteMsgAssnLinkForAssnIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_MESSAGES_ASSIGNMENTS where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteMsgAssnLinkForAssnIDs TO MSProjectServerRole
GO



/* Query #17217 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DelegationsForAssnIDs
   @p0 NTEXT
AS
delete from MSP_WEB_DELEGATIONS where WDELEG_ID in (select WDELEG_ID from MSP_WEB_DELEGATION_ASSIGNMENTS where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) and WDELEG_ID not in (select WDELEG_ID from MSP_WEB_DELEGATION_ASSIGNMENTS where WASSN_ID not in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DelegationsForAssnIDs TO MSProjectServerRole
GO



/* Query #17218 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DelegationAssnsForAssnIDs
   @p0 NTEXT
AS
Delete from MSP_WEB_DELEGATION_ASSIGNMENTS where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DelegationAssnsForAssnIDs TO MSProjectServerRole
GO



/* Query #17231 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteMsgForMsgIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_MESSAGES where WMSG_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteMsgForMsgIDs TO MSProjectServerRole
GO



/* Query #17232 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteMsgAssnLinkForMsgIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_MESSAGES_ASSIGNMENTS where WMSG_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteMsgAssnLinkForMsgIDs TO MSProjectServerRole
GO



/* Query #17234 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteMsgNonworkingForMsgIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_MESSAGES_NONWORKING where WMSG_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteMsgNonworkingForMsgIDs TO MSProjectServerRole
GO



/* Query #17235 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteNonworkingForMsgIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_NONWORKING where WNONWORK_ID in (select WNONWORK_ID from MSP_WEB_MESSAGES_NONWORKING where WMSG_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) and WNONWORK_ID not in (select WNONWORK_ID from MSP_WEB_MESSAGES_NONWORKING where WMSG_ID not in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteNonworkingForMsgIDs TO MSProjectServerRole
GO



/* Query #17251 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteSRespForSRespIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_STATUS_RESPONSES where WRESP_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteSRespForSRespIDs TO MSProjectServerRole
GO



/* Query #17252 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteSDistForSRespIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_STATUS_DISTRIBUTION where WRESP_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteSDistForSRespIDs TO MSProjectServerRole
GO



/* Query #17261 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetProjForProjNames
   @p0 NTEXT
AS
Select WPROJ_ID from MSP_WEB_PROJECTS where PROJ_NAME in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetProjForProjNames TO MSProjectServerRole
GO



/* Query #17262 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAssnForProjIDs
   @p0 NTEXT
AS
Select WASSN_ID from MSP_WEB_ASSIGNMENTS where (WNWRK_ID=-1 or WNWRK_ID is NULL) and WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAssnForProjIDs TO MSProjectServerRole
GO



/* Query #17263 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetMsgForProjIDs
   @p0 NTEXT
AS
Select WMSG_ID from MSP_WEB_MESSAGES where WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetMsgForProjIDs TO MSProjectServerRole
GO



/* Query #17271 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteProjRecordForProjIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_PROJECTS where WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteProjRecordForProjIDs TO MSProjectServerRole
GO



/* Query #17273 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteProjCategoriesForProjIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_PROJECT_WORKGROUP_INFO where WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteProjCategoriesForProjIDs TO MSProjectServerRole
GO



/* Query #17274 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteRuleItemsForProjIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_MGR_RULES_LISTS WHERE ITEM_TYPE=0 AND ITEM_ID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteRuleItemsForProjIDs TO MSProjectServerRole
GO



/* Query #17275 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteViewTableEntriesForProjIDs
   @p0 INT
AS
BEGIN
   SET XACT_ABORT ON

   delete from MSP_VIEW_PROJ_PROJECTS_STD    where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_PROJECTS_ENT    where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_PRED            where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_SUCC            where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_TASKS_STD       where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_TASKS_CF        where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_TASKS_ENT       where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_TASKSPLITS      where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_TASK_TP_BY_DAY  where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_RES_STD         where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_RES_CF          where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_RES_ENT         where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_ASSN_STD        where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_ASSN_CF         where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_ASSN_ENT        where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_ASSN_TP_BY_DAY  where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_CAL             where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_CAL_DATA        where WPROJ_ID=@p0
   delete from MSP_VIEW_PROJ_CAL_EXCEPTIONS  where WPROJ_ID=@p0

   SET XACT_ABORT OFF
RETURN(0)
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteViewTableEntriesForProjIDs TO MSProjectServerRole
GO



/* Query #17614 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteActualsForAssnForProjIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_WORK where WASSN_ID in (Select WASSN_ID from MSP_WEB_ASSIGNMENTS where (WNWRK_ID=-1 or WNWRK_ID is NULL) and WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteActualsForAssnForProjIDs TO MSProjectServerRole
GO



/* Query #17615 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteCFForAssnForProjIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_WORKGROUP_FIELDS where WASSN_ID in (Select WASSN_ID from MSP_WEB_ASSIGNMENTS where (WNWRK_ID=-1 or WNWRK_ID is NULL) and WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteCFForAssnForProjIDs TO MSProjectServerRole
GO



/* Query #17616 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteMsgAssnLinkForAssnForProjIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_MESSAGES_ASSIGNMENTS where WASSN_ID in (Select WASSN_ID from MSP_WEB_ASSIGNMENTS where (WNWRK_ID=-1 or WNWRK_ID is NULL) and WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteMsgAssnLinkForAssnForProjIDs TO MSProjectServerRole
GO



/* Query #17617 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DelegationsForAssnForProjIDs
   @p0 NTEXT
AS
Delete from MSP_WEB_DELEGATIONS where WDELEG_ID in (select WDELEG_ID from MSP_WEB_DELEGATION_ASSIGNMENTS where WASSN_ID in (Select WASSN_ID from MSP_WEB_ASSIGNMENTS where (WNWRK_ID=-1 or WNWRK_ID is NULL) and WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)))) and WDELEG_ID not in (select WDELEG_ID from MSP_WEB_DELEGATION_ASSIGNMENTS where WASSN_ID not in (Select WASSN_ID from MSP_WEB_ASSIGNMENTS where (WNWRK_ID=-1 or WNWRK_ID is NULL) and WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DelegationsForAssnForProjIDs TO MSProjectServerRole
GO



/* Query #17618 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DelegationAssnsForAssnForProjIDs
   @p0 NTEXT
AS
Delete from MSP_WEB_DELEGATION_ASSIGNMENTS where WASSN_ID in (Select WASSN_ID from MSP_WEB_ASSIGNMENTS where (WNWRK_ID=-1 or WNWRK_ID is NULL) and WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DelegationAssnsForAssnForProjIDs TO MSProjectServerRole
GO



/* Query #17619 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteAssnForAssnForProjIDs
   @p0 NTEXT
AS

Delete From MSP_WEB_WORK_ADJUSTED where WASSN_ID in (Select WASSN_ID from MSP_WEB_ASSIGNMENTS where (WNWRK_ID=-1 or WNWRK_ID is NULL) and WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)))

Delete From MSP_WEB_WORK_APPROVAL where WASSN_ID in (Select WASSN_ID from MSP_WEB_ASSIGNMENTS where (WNWRK_ID=-1 or WNWRK_ID is NULL) and WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)))

Delete From MSP_WEB_ASSIGNMENTS where WASSN_ID in (Select WASSN_ID from MSP_WEB_ASSIGNMENTS where (WNWRK_ID=-1 or WNWRK_ID is NULL) and WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteAssnForAssnForProjIDs TO MSProjectServerRole
GO



/* Query #17620 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteMsgAssnLinkForMsgForProjIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_MESSAGES_ASSIGNMENTS where WMSG_ID in (Select WMSG_ID from MSP_WEB_MESSAGES where WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteMsgAssnLinkForMsgForProjIDs TO MSProjectServerRole
GO



/* Query #17622 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteMsgNonworkingForMsgForProjIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_MESSAGES_NONWORKING where WMSG_ID in (Select WMSG_ID from MSP_WEB_MESSAGES where WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteMsgNonworkingForMsgForProjIDs TO MSProjectServerRole
GO



/* Query #17623 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteNonworkingForMsgForProjIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_NONWORKING where WNONWORK_ID in (select WNONWORK_ID from MSP_WEB_MESSAGES_NONWORKING where WMSG_ID in (Select WMSG_ID from MSP_WEB_MESSAGES where WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)))) and WNONWORK_ID not in (select WNONWORK_ID from MSP_WEB_MESSAGES_NONWORKING where WMSG_ID not in (Select WMSG_ID from MSP_WEB_MESSAGES where WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteNonworkingForMsgForProjIDs TO MSProjectServerRole
GO



/* Query #17624 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteMsgForMsgForProjIDs
   @p0 NTEXT
AS
Delete From MSP_WEB_MESSAGES where WMSG_ID in (Select WMSG_ID from MSP_WEB_MESSAGES where WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteMsgForMsgForProjIDs TO MSProjectServerRole
GO


/* Query #17625 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteTransactionsForProjIDs
   @p0 NTEXT
AS
  Delete From MSP_WEB_TRANSACTIONS 
   where WASSN_ID in 
         ( Select WASSN_ID from MSP_WEB_ASSIGNMENTS 
            where WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))
         )

  RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteTransactionsForProjIDs TO MSProjectServerRole
GO


/* Query #17626 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteTransactions
AS
  Delete From MSP_WEB_TRANSACTIONS Where WTRANS_STATE <> 3

  RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteTransactions TO MSProjectServerRole
GO


/* Query #17627 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteTransactionsForResId
   @p0 INT
AS
  Delete From MSP_WEB_TRANSACTIONS Where WRES_ID_TRANS_SENDER = @p0 and WTRANS_STATE <> 3

  RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteTransactionsForResId TO MSProjectServerRole
GO


/* Query #17628 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteTransactionsOlderThan
   @p0 DATETIME
AS
  Delete From MSP_WEB_TRANSACTIONS Where WTRANS_DATE < @p0 and WTRANS_STATE <> 3

  RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteTransactionsOlderThan TO MSProjectServerRole
GO


/* Query #17629 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteTransactionsOlderThanForResId
   @p0 DATETIME,
   @p1 INT
AS
  Delete From MSP_WEB_TRANSACTIONS Where WTRANS_DATE < @p0 and WRES_ID_TRANS_SENDER = @p1 and WTRANS_STATE <> 3

  RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteTransactionsOlderThanForResId TO MSProjectServerRole
GO



/* Query #17630 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteTransactionsSentBtw
   @p0 DATETIME,
   @p1 DATETIME
AS
  Delete From MSP_WEB_TRANSACTIONS Where WTRANS_DATE >= @p0 and WTRANS_DATE < @p1+1 and WTRANS_STATE <> 3

  RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteTransactionsSentBtw TO MSProjectServerRole
GO


/* Query #17631 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteTransactionsSentBtwForResId
   @p0 DATETIME,
   @p1 DATETIME,
   @p2 INT
AS
  Delete From MSP_WEB_TRANSACTIONS Where WTRANS_DATE >= @p0 and WTRANS_DATE < @p1+1 and WRES_ID_TRANS_SENDER = @p2 and WTRANS_STATE <> 3

  RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteTransactionsSentBtwForResId TO MSProjectServerRole
GO


/* Query #30003 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteViewFavorite
   @p0 NTEXT,
   @p1 NTEXT
AS
Delete From MSP_WEB_VIEW_FAVORITES Where WVIEW_FAV_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and WRES_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteViewFavorite TO MSProjectServerRole
GO



/* Query #35007 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetRejectAssignments
   @p0 INT,
   @p1 NTEXT
AS
SELECT WA.*,PROJ_NAME,RES_NAME,WRES_ID_DELEGATOR,WRES_ID_DELEGATEE,WDELEG_REJECT FROM ((MSP_WEB_ASSIGNMENTS WA INNER JOIN MSP_WEB_PROJECTS WP ON WA.WPROJ_ID=WP.WPROJ_ID) INNER JOIN MSP_WEB_RESOURCES WR on WA.WRES_ID_MGR=WR.WRES_ID) LEFT JOIN MSP_WEB_DELEGATIONS WD ON WA.WASSN_LAST_DELEG_ID=WD.WDELEG_ID WHERE WA.WRES_ID=@p0 and WA.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) ORDER BY WA.WPROJ_ID,WRES_ID_MGR RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetRejectAssignments TO MSProjectServerRole
GO



/* Query #35011 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeclineAssignedTask
   @p0 NVARCHAR (4000)
AS
UPDATE MSP_WEB_ASSIGNMENTS SET WASSN_IS_CONFIRMED=0 WHERE WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeclineAssignedTask TO MSProjectServerRole
GO



/* Query #35013 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetSelectedTasksIDs
   @p0 INT,
   @p1 NTEXT
AS
select
  WA.WASSN_ID,
  WA.WRES_ID_MGR,
  WA.WPROJ_ID,
  WP.PROJ_NAME,
  WP.WPROJ_TYPE,
  WA.WASSN_ACTUALS_PENDING,
  WA.WASSN_RESOURCE_UPDATE,
  WA.WASSN_SEND_UPDATE_NEEDED,
  WA.WASSN_REQUEST_UPDATE,
  WA.WASSN_SEND_UPDATE_DATE
from
  (
    select WASSN_ID from MSP_WEB_ASSIGNMENTS where WRES_ID=@p0 and WRES_ID_TEAM_LEAD is null
    union
    select WASSN_ID from MSP_WEB_ASSIGNMENTS WAT2 (index=I_ASSIGN_WRESID_TEAM_LEAD) where WAT2.WRES_ID_TEAM_LEAD=@p0
  ) as WAT
  inner join (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) LT on WAT.WASSN_ID=LT.TokenVal
  inner join MSP_WEB_ASSIGNMENTS WA on LT.TokenVal=WA.WASSN_ID
  inner join MSP_WEB_PROJECTS WP on WA.WPROJ_ID=WP.WPROJ_ID
where WPROJ_IS_NONWORKING=0
	and WASSN_SEND_UPDATE_NEEDED<>0
	and WASSN_IS_CONFIRMED<>0
	and WASSN_CREATED_BY_RES<>3
	and WASSN_CREATED_BY_RES<>1
	and WASSN_REMOVED_BY_RESOURCE=0
order by WA.WPROJ_ID, WRES_ID_MGR

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetSelectedTasksIDs TO MSProjectServerRole
GO



/* Query #35014 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetSelectedTasksThatIReportToLeads
   @p0 INT,
   @p1 NTEXT
AS
Select WASSN_ID,WASSN_RESOURCE_UPDATE,WASSN_REQUEST_UPDATE,WRES_ID_TEAM_LEAD,WASSN_SEND_UPDATE_DATE,WA.WPROJ_ID,PROJ_NAME From MSP_WEB_ASSIGNMENTS WA,MSP_WEB_PROJECTS WP Where WA.WPROJ_ID=WP.WPROJ_ID and WA.WRES_ID=@p0 and WRES_ID_TEAM_LEAD is Not Null and WASSN_SEND_UPDATE_NEEDED<>0 and WASSN_REMOVED_BY_RESOURCE=0 and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) Order By WA.WPROJ_ID,WRES_ID_TEAM_LEAD RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetSelectedTasksThatIReportToLeads TO MSProjectServerRole
GO



/* Query #35024 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetDelegatorContentForNotifications
   @p0 NTEXT
AS
SELECT TASK_NAME,ASSN_START_DATE,ASSN_FINISH_DATE,ASSN_WORK,ASSN_REM_WORK,RES_NAME as TDelegatorName FROM MSP_WEB_ASSIGNMENTS,MSP_WEB_DELEGATIONS,MSP_WEB_RESOURCES WHERE MSP_WEB_ASSIGNMENTS.WASSN_LAST_DELEG_ID=MSP_WEB_DELEGATIONS.WDELEG_ID and MSP_WEB_DELEGATIONS.WRES_ID_DELEGATOR=MSP_WEB_RESOURCES.WRES_ID and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetDelegatorContentForNotifications TO MSProjectServerRole
GO



/* Query #35025 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetDelegateeContentForNotifications
   @p0 NTEXT
AS
SELECT TASK_NAME,ASSN_START_DATE,ASSN_FINISH_DATE,ASSN_WORK,ASSN_REM_WORK,RES_NAME as TDelegateeName FROM MSP_WEB_ASSIGNMENTS,MSP_WEB_DELEGATIONS,MSP_WEB_RESOURCES WHERE MSP_WEB_ASSIGNMENTS.WASSN_LAST_DELEG_ID=MSP_WEB_DELEGATIONS.WDELEG_ID and MSP_WEB_DELEGATIONS.WRES_ID_DELEGATEE=MSP_WEB_RESOURCES.WRES_ID and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetDelegateeContentForNotifications TO MSProjectServerRole
GO



/* Query #35027 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetNumTaskUpdatesAndManagerNames
   @p0 NTEXT,
   @p1 NTEXT
AS
SELECT COUNT(WRES_ID) AS TNumAssns
			, MAX(RES_NAME) AS TToResNames 
FROM (
			SELECT MSP_WEB_RESOURCES.WRES_ID, RES_NAME, WASSN_ID
			FROM MSP_WEB_RESOURCES
			INNER JOIN MSP_WEB_ASSIGNMENTS ON MSP_WEB_RESOURCES.WRES_ID=MSP_WEB_ASSIGNMENTS.WRES_ID_MGR
			INNER JOIN MSP_WEB_PROJECTS ON MSP_WEB_ASSIGNMENTS.WPROJ_ID=MSP_WEB_PROJECTS.WPROJ_ID
			WHERE (WASSN_ID in (SELECT TokenVal FROM dbo.MSP_WEB_FN_ConvertListToTable(@p0)) AND WPROJ_TYPE<>3) 
		union
			SELECT MSP_WEB_RESOURCES.WRES_ID, RES_NAME, WASSN_ID
			FROM MSP_WEB_RESOURCES
			INNER JOIN MSP_WEB_ASSIGNMENTS ON MSP_WEB_RESOURCES.WRES_ID=MSP_WEB_ASSIGNMENTS.WRES_ID_TEAM_LEAD 
			INNER JOIN MSP_WEB_PROJECTS ON MSP_WEB_ASSIGNMENTS.WPROJ_ID=MSP_WEB_PROJECTS.WPROJ_ID
			WHERE WASSN_ID in (SELECT TokenVal FROM dbo.MSP_WEB_FN_ConvertListToTable(@p1)) AND WPROJ_TYPE<>3
				) AS A
			GROUP BY RES_NAME 
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetNumTaskUpdatesAndManagerNames TO MSProjectServerRole
GO



/* Query #35200 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetTodoListsForNotification
   @p0 INT,
   @p1 NTEXT
AS
Select WASSN_ID,WA.WRES_ID,WA.WPROJ_ID,PROJ_NAME From MSP_WEB_ASSIGNMENTS WA INNER JOIN MSP_WEB_PROJECTS WP ON WA.WPROJ_ID=WP.WPROJ_ID Where WP.WRES_ID=@p0 and WPROJ_TYPE=3 and WA.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) Order By WA.WPROJ_ID,WA.WRES_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetTodoListsForNotification TO MSProjectServerRole
GO



/* Query #40020 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetTaskObjects
   @p0 INT,
   @p1 INT,
   @p2 NTEXT
AS
SELECT WOBJ_ID, WOBJ_TASK_ID, WOBJ_PROJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p1 AND WOBJ_TASK_ID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p2)) ORDER BY WOBJ_TASK_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetTaskObjects TO MSProjectServerRole
GO



/* Query #40023 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllIssuesForIssuesEditForm
   @p0 INT,
   @p1 INT,
   @p2 INT
AS
SELECT o.WOBJ_ID, o.WOBJ_TP_ID, (CASE WHEN l1.WOBJLINK_TYPE IS NOT NULL THEN l1.WOBJLINK_TYPE WHEN l2.WOBJLINK_TYPE IS NOT NULL THEN l2.WOBJLINK_TYPE ELSE 0 END) AS WOBJLINK_TYPE FROM MSP_WEB_OBJECTS o LEFT JOIN MSP_WEB_OBJECT_LINKS l1 ON o.WOBJ_ID = l1.WOBJLINK_OBJECT1 AND l1.WOBJLINK_OBJECT2 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p1 AND WOBJ_TP_ID = @p2) LEFT JOIN MSP_WEB_OBJECT_LINKS l2 ON o.WOBJ_ID = l2.WOBJLINK_OBJECT2 AND l2.WOBJLINK_OBJECT1 = (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID = @p0 AND WOBJ_TYPE = @p1 AND WOBJ_TP_ID = @p2) WHERE o.WOBJ_PROJ_ID = @p0 AND o.WOBJ_TYPE = @p1 AND o.WOBJ_TP_ID <> @p2 ORDER BY o.WOBJ_TP_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllIssuesForIssuesEditForm TO MSProjectServerRole
GO



/* Query #40028 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_SetLinkType
   @p0 INT,
   @p1 INT,
   @p2 INT
AS
UPDATE MSP_WEB_OBJECT_LINKS SET WOBJLINK_TYPE=@p2 WHERE (WOBJLINK_OBJECT1 = @p0 AND WOBJLINK_OBJECT2 = @p1) OR (WOBJLINK_OBJECT1 = @p1 AND WOBJLINK_OBJECT2 = @p0) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_SetLinkType TO MSProjectServerRole
GO



/* Query #40029 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetProjectIssues
   @p0 INT
AS
SELECT *  FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID=@p0 AND WOBJ_TYPE=4 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetProjectIssues TO MSProjectServerRole
GO



/* Query #65031 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetENTasks
   @p0 NTEXT
AS
select TASK_NAME, ASSN_START_DATE, ASSN_FINISH_DATE, ASSN_WORK, ASSN_REM_WORK from MSP_WEB_ASSIGNMENTS where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) order by ASSN_START_DATE RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetENTasks TO MSProjectServerRole
GO



/* Query #65032 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetENDelegationTasks
   @p0 NTEXT
AS
select TASK_NAME, ASSN_START_DATE, ASSN_FINISH_DATE, ASSN_WORK, ASSN_REM_WORK, RES_NAME from MSP_WEB_ASSIGNMENTS a, MSP_WEB_RESOURCES r where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and a.WRES_ID=r.WRES_ID order by ASSN_START_DATE RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetENDelegationTasks TO MSProjectServerRole
GO



/* Query #65033 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetENStatusReports
   @p0 NTEXT
AS
select WREPORT_NAME, RES_NAME, WDUE_ON from MSP_WEB_STATUS_REPORTS rp, MSP_WEB_STATUS_REQUESTS sq, MSP_WEB_RESOURCES rs where rp.WSR_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and rp.WSR_ID=sq.WSR_ID and rp.WRES_ID_MGR=rs.WRES_ID order by WDUE_ON RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetENStatusReports TO MSProjectServerRole
GO



/* Query #65035 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetENStrings
   @p0 INT,
   @p1 NTEXT
AS
select * from MSP_WEB_CONVERSIONS where STRING_TYPE_ID=3 and LANG_ID=@p0 and CONV_VALUE in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetENStrings TO MSProjectServerRole
GO



/* Query #65041 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetENDelegationTasksWLeadResInfo
   @p0 NTEXT
AS
select TASK_NAME, ASSN_START_DATE, ASSN_FINISH_DATE, ASSN_WORK, ASSN_REM_WORK, r.RES_NAME, r2.RES_NAME as TLeadName from (MSP_WEB_ASSIGNMENTS a INNER JOIN MSP_WEB_RESOURCES r ON a.WRES_ID=r.WRES_ID) LEFT JOIN MSP_WEB_RESOURCES r2 ON a.WRES_ID_TEAM_LEAD=r2.WRES_ID where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) order by ASSN_START_DATE RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetENDelegationTasksWLeadResInfo TO MSProjectServerRole
GO



/* Query #65042 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetENCalendarTransactionsInfo
   @p0 NTEXT
AS
select WNONWORK_SUBJECT,WNONWORK_START,WNONWORK_END from MSP_WEB_NONWORKING where WNONWORK_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetENCalendarTransactionsInfo TO MSProjectServerRole
GO



/* Query #66025 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetResourceInfoFromResIDs
   @p0 NTEXT
AS
select * from MSP_WEB_RESOURCES where WRES_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetResourceInfoFromResIDs TO MSProjectServerRole
GO



/* Query #66029 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetProjectsExceptInCategoryList
   @p0 NTEXT
AS
select P.WPROJ_ID, P.WPROJ_DEFAULT_WPROJ_ID, P.PROJ_NAME, R.RES_NAME from MSP_WEB_PROJECTS P, MSP_WEB_RESOURCES R where WPROJ_IS_NONWORKING=0 and WPROJ_TYPE<>3 and P.WRES_ID=R.WRES_ID and WPROJ_ID not in (select WSEC_OBJ_ID from MSP_WEB_SECURITY_CATEGORY_OBJECTS where WSEC_OBJ_TYPE=1 and WSEC_CAT_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) order by P.WPROJ_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetProjectsExceptInCategoryList TO MSProjectServerRole
GO



/* Query #66030 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetProjectsInCategoriesAllowedMinusDenied
   @p0 NTEXT,
   @p1 NTEXT
AS
select P.WPROJ_ID, P.WPROJ_DEFAULT_WPROJ_ID, P.PROJ_NAME, R.RES_NAME from MSP_WEB_PROJECTS P, MSP_WEB_RESOURCES R where WPROJ_IS_NONWORKING=0 and WPROJ_TYPE<>3 and P.WRES_ID=R.WRES_ID and WPROJ_ID in (select WSEC_OBJ_ID from MSP_WEB_SECURITY_CATEGORY_OBJECTS where WSEC_OBJ_TYPE=1 and WSEC_CAT_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) and WPROJ_ID not in (select WSEC_OBJ_ID from MSP_WEB_SECURITY_CATEGORY_OBJECTS where WSEC_OBJ_TYPE=1 and WSEC_CAT_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1))) order by P.WPROJ_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetProjectsInCategoriesAllowedMinusDenied TO MSProjectServerRole
GO



/* Query #66036 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetWRESIDsFromEUIDs
   @p0 NTEXT
AS
select WRES_ID from MSP_WEB_RESOURCES where RES_EUID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetWRESIDsFromEUIDs TO MSProjectServerRole
GO



/* Query #66037 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetIssueProjectInfoFromProjList
   @p0 NTEXT
AS

SELECT DISTINCT
   P.WPROJ_ID,
   P.PROJ_NAME,
   P.WPROJ_STS_SUBWEB_NAME,
   P.WPROJ_ISSUE_LIST_NAME,
   P.WPROJ_RISK_LIST_NAME,
   P.WPROJ_DEFAULT_WPROJ_ID,
   R.RES_NAME,
   S.*
FROM
   MSP_WEB_PROJECTS P INNER JOIN
   MSP_WEB_RESOURCES R ON P.WRES_ID = R.WRES_ID LEFT OUTER JOIN
   MSP_WEB_STS_SERVERS S ON S.WSTS_SERVER_ID = P.WSTS_SERVER_ID
WHERE
   P.WPROJ_ID IN (SELECT TokenVal FROM dbo.MSP_WEB_FN_ConvertListToTable(@p0))
ORDER BY P.WPROJ_ID
RETURN

GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetIssueProjectInfoFromProjList TO MSProjectServerRole
GO



/* Query #70000 */
CREATE PROCEDURE dbo.MSP_WEB_SP_BUS_DeleteCalendarTransMessages
   @p0 NTEXT,
   @p1 NTEXT
AS
delete MSP_WEB_MESSAGES from MSP_WEB_MESSAGES, MSP_WEB_MESSAGES_NONWORKING where MSP_WEB_MESSAGES.WMSG_ID = MSP_WEB_MESSAGES_NONWORKING.WMSG_ID and MSP_WEB_MESSAGES_NONWORKING.WMSGNONWORK_ID  in  (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and MSP_WEB_MESSAGES.WMSG_ID not in (Select MSP_WEB_MESSAGES.WMSG_ID from MSP_WEB_MESSAGES, MSP_WEB_MESSAGES_NONWORKING where MSP_WEB_MESSAGES.WMSG_ID  = MSP_WEB_MESSAGES_NONWORKING.WMSG_ID and MSP_WEB_MESSAGES_NONWORKING.WMSGNONWORK_ID not in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_BUS_DeleteCalendarTransMessages TO MSProjectServerRole
GO



/* Query #70001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_BUS_DeleteCalendarTransNonWorking
   @p0 NTEXT,
   @p1 NTEXT
AS
delete MSP_WEB_NONWORKING from MSP_WEB_NONWORKING, MSP_WEB_MESSAGES_NONWORKING where MSP_WEB_NONWORKING.WNONWORK_ID  = MSP_WEB_MESSAGES_NONWORKING.WNONWORK_ID and MSP_WEB_MESSAGES_NONWORKING.WMSGNONWORK_ID  in  (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and MSP_WEB_NONWORKING.WNONWORK_ID not in (Select MSP_WEB_NONWORKING.WNONWORK_ID from MSP_WEB_NONWORKING, MSP_WEB_MESSAGES_NONWORKING where MSP_WEB_NONWORKING.WNONWORK_ID = MSP_WEB_MESSAGES_NONWORKING.WNONWORK_ID and MSP_WEB_MESSAGES_NONWORKING.WMSGNONWORK_ID not in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_BUS_DeleteCalendarTransNonWorking TO MSProjectServerRole
GO



/* Query #70002 */
CREATE PROCEDURE dbo.MSP_WEB_SP_BUS_DeleteCalendarTransMessagesNonWorking
   @p0 NTEXT
AS
delete MSP_WEB_MESSAGES_NONWORKING from MSP_WEB_MESSAGES_NONWORKING where MSP_WEB_MESSAGES_NONWORKING.WMSGNONWORK_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_BUS_DeleteCalendarTransMessagesNonWorking TO MSProjectServerRole
GO



/* Query #90005 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetActualsRecordset
   @p0 DATETIME,
   @p1 DATETIME,
   @p2 NTEXT
AS
	SELECT MWW.*
	FROM MSP_WEB_WORK MWW 
	     INNER JOIN dbo.MSP_WEB_FN_ConvertListToTable(@p2) LT ON (LT.TokenVal = WASSN_ID)
	Where ((WWORK_START>=@p0 and WWORK_START<=@p1) or (WWORK_START<@p0 and WWORK_FINISH>=@p0)) 
	Order By MWW.WASSN_ID,MWW.WWORK_START,MWW.WWORK_TYPE RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetActualsRecordset TO MSProjectServerRole
GO



/* Query #90006 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetCustomfieldRecordset
   @p0 NTEXT,
   @p1 INT
AS

SET NOCOUNT ON

SELECT WA.WPROJ_ID, WA.WASSN_ID
INTO #tmp1
FROM MSP_WEB_ASSIGNMENTS WA 
	INNER JOIN dbo.MSP_WEB_FN_ConvertListToTable(@p0) LT ON WA.WASSN_ID = LT.TokenVal

CREATE INDEX IX_temp on #tmp1(WPROJ_ID, WASSN_ID)


Select WWF.*,WWFI.CUSTFIELD_INFO_ID,(CASE WHEN CUSTFIELD_NAME is null OR CUSTFIELD_NAME=N'' THEN CONV_STRING ELSE CUSTFIELD_NAME END) as CUSTFIELD_NAME 
From
#tmp1 WA
INNER JOIN MSP_WEB_WORKGROUP_FIELDS WWF ON WA.WASSN_ID=WWF.WASSN_ID
INNER JOIN MSP_WEB_WORKGROUP_FIELDS_INFO WWFI ON WWF.FIELD_ID=WWFI.FIELD_ID
INNER JOIN MSP_WEB_PROJECT_WORKGROUP_INFO WPWI ON (WA.WPROJ_ID=WPWI.WPROJ_ID and WWFI.CUSTFIELD_INFO_ID=WPWI.CUSTFIELD_INFO_ID)
LEFT JOIN MSP_WEB_CONVERSIONS WC ON (WWFI.CONV_VALUE=WC.CONV_VALUE and LANG_ID=@p1)
Order By WWF.WASSN_ID,WWFI.CUSTFIELD_INFO_ID

SET NOCOUNT OFF

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetCustomfieldRecordset TO MSProjectServerRole
GO



/* Query #90007 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetCustomfieldInfoRecordset
   @p0 NTEXT,
   @p1 INT
AS

SET NOCOUNT ON

SELECT WA.WPROJ_ID, WA.WASSN_ID
INTO #tmp1
FROM MSP_WEB_ASSIGNMENTS WA 
	INNER JOIN dbo.MSP_WEB_FN_ConvertListToTable(@p0) LT ON WA.WASSN_ID = LT.TokenVal

CREATE INDEX IX_temp on #tmp1(WPROJ_ID, WASSN_ID)

Select Distinct WWF.FIELD_ID,WWFI.CUSTFIELD_INFO_ID,(CASE WHEN CUSTFIELD_NAME is null OR CUSTFIELD_NAME=N'' THEN CONV_STRING ELSE CUSTFIELD_NAME END) as CUSTFIELD_NAME 
From 
#tmp1 WA
INNER JOIN MSP_WEB_WORKGROUP_FIELDS WWF ON WA.WASSN_ID=WWF.WASSN_ID
INNER JOIN MSP_WEB_WORKGROUP_FIELDS_INFO WWFI ON WWF.FIELD_ID=WWFI.FIELD_ID
INNER JOIN MSP_WEB_PROJECT_WORKGROUP_INFO WPWI ON (WA.WPROJ_ID=WPWI.WPROJ_ID and WWFI.CUSTFIELD_INFO_ID=WPWI.CUSTFIELD_INFO_ID)
LEFT JOIN MSP_WEB_CONVERSIONS WC ON (WWFI.CONV_VALUE=WC.CONV_VALUE and LANG_ID=@p1)
Order By WWFI.CUSTFIELD_INFO_ID 

SET NOCOUNT OFF

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetCustomfieldInfoRecordset TO MSProjectServerRole
GO



/* Query #90008 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetCustomfieldRecordsetForViews
   @p0 NTEXT,
   @p1 INT,
   @p2 INT
AS

SET NOCOUNT ON

select WA.WPROJ_ID, WA.WASSN_ID
into #tmp1
from MSP_WEB_ASSIGNMENTS WA 
	inner join dbo.MSP_WEB_FN_ConvertListToTable(@p0) LT ON WA.WASSN_ID = LT.TokenVal

create index IX_temp on #tmp1(WPROJ_ID, WASSN_ID)

select
	WF.*,WFI.CUSTFIELD_INFO_ID,
	(case when CUSTFIELD_NAME is null OR CUSTFIELD_NAME=N'' then CONV_STRING else CUSTFIELD_NAME end) as CUSTFIELD_NAME 
from MSP_WEB_WORKGROUP_FIELDS_INFO WFI
	inner join MSP_WEB_PROJECT_WORKGROUP_INFO PWI on PWI.CUSTFIELD_INFO_ID = WFI.CUSTFIELD_INFO_ID
		inner join #tmp1 WA ON PWI.WPROJ_ID = WA.WPROJ_ID
			inner join MSP_WEB_WORKGROUP_FIELDS WF on (WA.WASSN_ID = WF.WASSN_ID and WFI.FIELD_ID = WF.FIELD_ID)
	inner join MSP_WEB_VIEW_REPORTS_FIELDS VRF on WFI.FIELD_ID = VRF.WFIELD_ID
	left join MSP_WEB_CONVERSIONS WC on (WFI.CONV_VALUE = WC.CONV_VALUE and LANG_ID = @p2)
where VRF.WVIEW_ID = @p1
order By WF.WASSN_ID, WFI.CUSTFIELD_INFO_ID 

SET NOCOUNT OFF

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetCustomfieldRecordsetForViews TO MSProjectServerRole
GO



/* Query #90009 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetCustomfieldInfoRecordsetForViews
   @p0 NTEXT,
   @p1 INT,
   @p2 INT
AS

SET NOCOUNT ON

select WA.WPROJ_ID, WA.WASSN_ID
into #tmp1
from MSP_WEB_ASSIGNMENTS WA 
	inner JOIN dbo.MSP_WEB_FN_ConvertListToTable(@p0) LT ON WA.WASSN_ID = LT.TokenVal

create index IX_temp on #tmp1(WPROJ_ID, WASSN_ID)

select distinct
	WFI.FIELD_ID,WFI.CUSTFIELD_INFO_ID,
	case when (CUSTFIELD_NAME is null OR CUSTFIELD_NAME=N'') then CONV_STRING else CUSTFIELD_NAME end as 'CUSTFIELD_NAME'
from #tmp1 WA
	inner join MSP_WEB_PROJECT_WORKGROUP_INFO PWI on PWI.WPROJ_ID = WA.WPROJ_ID
		inner join MSP_WEB_WORKGROUP_FIELDS_INFO WFI on WFI.CUSTFIELD_INFO_ID = PWI.CUSTFIELD_INFO_ID
			inner join MSP_WEB_VIEW_REPORTS_FIELDS VRF on VRF.WFIELD_ID = WFI.FIELD_ID
	left join MSP_WEB_CONVERSIONS WC on (WFI.CONV_VALUE = WC.CONV_VALUE and LANG_ID = @p2)
where VRF.WVIEW_ID = @p1
order by WFI.CUSTFIELD_INFO_ID 


SET NOCOUNT OFF

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetCustomfieldInfoRecordsetForViews TO MSProjectServerRole
GO



/* Query #90010 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetFavoriteViews
   @p0 INT,
   @p1 NTEXT
AS
Select WVIEW_FAV_ID, WVIEW_FAV_NAME, WVIEW_FAV_URL, WSEC_MENU_ID From MSP_WEB_VIEW_FAVORITES WVF Where WRES_ID=@p0 and WSEC_MENU_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) Order By WVIEW_FAV_NAME RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetFavoriteViews TO MSProjectServerRole
GO



/* Query #90011 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteFavoriteViews
   @p0 NTEXT,
   @p1 INT
AS
Delete From MSP_WEB_VIEW_FAVORITES Where WVIEW_FAV_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and WRES_ID= @p1 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteFavoriteViews TO MSProjectServerRole
GO

/* Query #90029 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetTransActualsRS
   @p0 DATETIME,
   @p1 DATETIME,
   @p2 NTEXT
AS
	SELECT MWW.*, (CASE WHEN dbo.MSP_WEB_FN_SEC_CheckOrgPermission(211)=0 OR EXISTS (SELECT * FROM MSP_WEB_WORK_APPROVAL WWA WHERE WWA.WASSN_ID = MWW.WASSN_ID AND WWA.WPRD_START_DATE<=MWW.WWORK_START AND WWA.WPRD_FINISH_DATE>=MWW.WWORK_FINISH AND WWA.WAPPROVAL_STATUS = 1 AND MWW.WWORK_TYPE !=0) THEN 1 ELSE 0 END) AS TAPPROVAL_STATUS
	FROM MSP_WEB_WORK MWW
	Where ((WWORK_START>=@p0 and WWORK_START<=@p1) or (WWORK_START<@p0 and WWORK_FINISH>=@p0)) 
		and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p2))

GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetTransActualsRS TO MSProjectServerRole
GO

/* Query #90030 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ClearApprovalDirtyFlagForActuals
   @p0 int
AS
	UPDATE MSP_WEB_WORK
	SET WWORK_APPROVAL_STATUS = 0
	WHERE WASSN_ID = (SELECT WASSN_ID FROM MSP_WEB_WORK_APPROVAL WHERE WAPPROVAL_ID = @p0 AND WWORK_START<=WPRD_FINISH_DATE AND WWORK_FINISH>=WPRD_START_DATE)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ClearApprovalDirtyFlagForActuals TO MSProjectServerRole
GO



/* Query #85012 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetPoolResCalendars
   @p0 INT,
   @p1 NTEXT
as
BEGIN
declare @EntGlobalUID int
select @EntGlobalUID = PROJ_ID from MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE) where PROJ_TYPE = 2

SELECT c.PROJ_ID, c.CAL_UID, c.CAL_NAME, c.CAL_BASE_UID, c.CAL_IS_BASE_CAL, t.CD_UID, t.CD_DAY_OR_EXCEPTION, t.CD_WORKING, t.CD_FROM_DATE, t.CD_TO_DATE, t.CD_FROM_TIME1, t.CD_TO_TIME1, t.CD_FROM_TIME2, t.CD_TO_TIME2, t.CD_FROM_TIME3, t.CD_TO_TIME3, t.CD_FROM_TIME4, t.CD_TO_TIME4, t.CD_FROM_TIME5, t.CD_TO_TIME5 
FROM MSP_CALENDARS as c LEFT JOIN MSP_CALENDAR_DATA As t ON (c.CAL_UID = t.CAL_UID) AND (c.PROJ_ID= t.PROJ_ID) 
WHERE (c.PROJ_ID=@p0) AND (c.CAL_UID > 0) AND (c.RES_UID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)))
UNION
SELECT c.PROJ_ID, c.CAL_UID, c.CAL_NAME, c.CAL_BASE_UID, c.CAL_IS_BASE_CAL, t.CD_UID, t.CD_DAY_OR_EXCEPTION, t.CD_WORKING, t.CD_FROM_DATE, t.CD_TO_DATE, t.CD_FROM_TIME1, t.CD_TO_TIME1, t.CD_FROM_TIME2, t.CD_TO_TIME2, t.CD_FROM_TIME3, t.CD_TO_TIME3, t.CD_FROM_TIME4, t.CD_TO_TIME4, t.CD_FROM_TIME5, t.CD_TO_TIME5 
FROM (MSP_CALENDARS as c INNER JOIN MSP_CALENDARS As g ON c.CAL_NAME = g.CAL_NAME) LEFT JOIN MSP_CALENDAR_DATA As t ON (g.CAL_UID = t.CAL_UID) AND (t.PROJ_ID = @EntGlobalUID) 
WHERE (c.PROJ_ID=@p0) AND (g.PROJ_ID=@EntGlobalUID) AND (c.CAL_UID > 0) AND (c.CAL_IS_BASE_CAL <> 0) AND t.CD_UID IS NOT NULL

return
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetPoolResCalendars TO MSProjectServerRole
GO




/* Query #85013 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetPoolResources
   @p0 INT,
   @p1 NTEXT
AS
SELECT ER.*, WR.WRES_IS_ENABLED FROM MSP_RESOURCES ER INNER JOIN MSP_WEB_RESOURCES WR ON (WR.RES_EUID=ER.RES_EUID) WHERE ER.PROJ_ID=@p0 AND ER.RES_UID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetPoolResources TO MSProjectServerRole
GO



/* Query #85016 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetEntResUIDs
   @p0 NTEXT
AS
SELECT DISTINCT ENT_ResourceEnterpriseUniqueID FROM MSP_VIEW_PROJ_RES_ENT WHERE (ENT_ResourceEnterpriseUniqueID > 0) AND (ENT_ResourceEnterpriseUniqueID Is Not Null) AND (ENT_ProjectUniqueID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetEntResUIDs TO MSProjectServerRole
GO



/* Query #85019 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetResNames
   @p0 INT,
   @p1 NTEXT
AS
SELECT ResourceUniqueID, ResourceName, ResourceStandardRate, ResourceOvertimeRate FROM MSP_VIEW_PROJ_RES_STD WHERE ProjectUniqueID = (@p0) AND ResourceUniqueID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetResNames TO MSProjectServerRole
GO



/* Query #310213 */
CREATE PROCEDURE dbo.MSP_WEB_SP_BUS_GetTasksAssignmentsForAssnIDList
   @p0 INT,
   @p1 DATETIME,
   @p2 INT,
   @p3 NTEXT
AS
Select WASSN_COMMENTS,WASSN_NOTE_STATUS,abs(WDELEG_REJECT)+abs(WASSN_DELEG_PENDING-1)+(case when MSP_WEB_DELEGATIONS.WRES_ID_DELEGATOR is null then 0 else 1 end)+(case when WA.WRES_ID_TEAM_LEAD is null then -1 else 2 end) as TDelegIndicator,WASSN_DELEG_PENDING as TReadOnly,WASSN_REQUEST_UPDATE,WASSN_RESOURCE_UPDATE,WASSN_ID,TASK_UID_SUMMARY,TASK_UID,TASK_ID,TASK_NAME,ASSN_START_DATE,ASSN_FINISH_DATE,ASSN_WORK,ASSN_REM_WORK,TASK_IS_SUMMARY,WASSN_MGR_UPDATED,WASSN_CREATED_BY_RES,WA.RESERVED_DATA1 as TDelegeeID,WA.RESERVED_DATA2 as TDelegKeepCopy,WA.RESERVED_DATA3 as TDelegIsLead,WA.WRES_ID,WA.WPROJ_ID,WRES_ID_TEAM_LEAD as TTeamLeadID,PROJ_NAME,WDELEG_DATE,WR1.RES_NAME AS TDelegatorName,WR2.RES_NAME AS TDelegeeName,WR3.RES_NAME AS TLeadName From (((((MSP_WEB_ASSIGNMENTS WA INNER JOIN MSP_WEB_PROJECTS ON WA.WPROJ_ID=MSP_WEB_PROJECTS.WPROJ_ID) INNER JOIN MSP_WEB_RESOURCES ON WA.WRES_ID=MSP_WEB_RESOURCES.WRES_ID) LEFT JOIN MSP_WEB_DELEGATIONS ON WA.WASSN_LAST_DELEG_ID=MSP_WEB_DELEGATIONS.WDELEG_ID) LEFT JOIN MSP_WEB_RESOURCES WR1 ON MSP_WEB_DELEGATIONS.WRES_ID_DELEGATOR=WR1.WRES_ID) LEFT JOIN MSP_WEB_RESOURCES WR2 ON MSP_WEB_DELEGATIONS.WRES_ID_DELEGATEE=WR2.WRES_ID) LEFT JOIN MSP_WEB_RESOURCES WR3 ON WA.WRES_ID_TEAM_LEAD=WR3.WRES_ID Where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p3)) and WA.WRES_ID=@p0 Order By WA.WPROJ_ID,WA.TASK_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_BUS_GetTasksAssignmentsForAssnIDList TO MSProjectServerRole
GO



/* Query #310308 */
CREATE PROCEDURE dbo.MSP_WEB_SP_BUS_GetLeadAssignmentsForAssnList
   @p0 INT,
   @p1 DATETIME,
   @p2 INT,
   @p3 NTEXT
AS
Select WASSN_COMMENTS,WASSN_NOTE_STATUS,abs(WDELEG_REJECT)+abs(WASSN_DELEG_PENDING-1)+(CASE WHEN WR1.WRES_ID is not null THEN 1 ELSE 0 END)+(case when WRES_ID_TEAM_LEAD is null then -1 else 2 end) as TDelegIndicator,WASSN_DELEG_PENDING as TReadOnly,WRES_ID_TEAM_LEAD as TDelegeeID, MSP_WEB_ASSIGNMENTS.RESERVED_DATA2 as TDelegKeepCopy, WDELEG_DATE,WASSN_REQUEST_UPDATE,WASSN_ACTUALS_PENDING,WASSN_ID,TASK_UID_SUMMARY,TASK_UID,TASK_ID,TASK_NAME,ASSN_START_DATE,ASSN_FINISH_DATE,ASSN_WORK,ASSN_REM_WORK,WASSN_PCT_COMP,TASK_IS_SUMMARY,WASSN_CREATED_BY_RES,MSP_WEB_ASSIGNMENTS.WPROJ_ID,PROJ_NAME,OPT_DEF_START_TIME,OPT_DEF_FINISH_TIME,WR2.RES_NAME as TDelegatorName,WR3.RES_NAME as TDelegeeName From ((((MSP_WEB_ASSIGNMENTS INNER JOIN MSP_WEB_PROJECTS ON MSP_WEB_ASSIGNMENTS.WPROJ_ID = MSP_WEB_PROJECTS.WPROJ_ID) LEFT JOIN MSP_WEB_DELEGATIONS ON MSP_WEB_ASSIGNMENTS.WASSN_LAST_DELEG_ID = MSP_WEB_DELEGATIONS.WDELEG_ID) LEFT JOIN MSP_WEB_RESOURCES WR1 ON MSP_WEB_ASSIGNMENTS.WRES_ID_TEAM_LEAD = WR1.WRES_ID) LEFT JOIN MSP_WEB_RESOURCES WR2 ON MSP_WEB_DELEGATIONS.WRES_ID_DELEGATOR = WR2.WRES_ID) LEFT JOIN MSP_WEB_RESOURCES WR3 ON MSP_WEB_DELEGATIONS.WRES_ID_DELEGATEE = WR3.WRES_ID Where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p3)) and MSP_WEB_ASSIGNMENTS.WRES_ID_TEAM_LEAD=@p0 Order By MSP_WEB_ASSIGNMENTS.WPROJ_ID,TASK_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_BUS_GetLeadAssignmentsForAssnList TO MSProjectServerRole
GO



/* Query #10404 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetStatusReqAssnsFailedCheckRules
   @p0 INT,
   @p1 INT,
   @p2 INT,
   @p3 NTEXT
AS
Select distinct WA.WASSN_ID 
From MSP_WEB_ASSIGNMENTS WA 
  inner join MSP_WEB_TRANSACTIONS WT on WA.WASSN_ID=WT.WASSN_ID
  inner join MSP_WEB_RESOURCES WR on WA.WRES_ID_MGR=WR.WRES_ID
Where WA.WRES_ID_MGR=@p0 and 
      TASK_IS_SUMMARY=0 and
      WT.WTRANS_STATE < 3 and
      WT.WTRANS_TYPE  < 3 and
      WR.RESERVED_DATA3=@p1 and 
      WR.RESERVED_DATA4=@p2 and
      WA.WASSN_ID not in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p3)) 
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetStatusReqAssnsFailedCheckRules TO MSProjectServerRole
GO



/* Query #310405 */
CREATE PROCEDURE dbo.MSP_WEB_SP_BUS_UpdateCreatedByResFlagForAssnIDs
   @p0 INT,
   @p1 NTEXT
AS
update MSP_WEB_ASSIGNMENTS 
set WASSN_CREATED_BY_RES=0 
where WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) 
and WRES_ID_MGR = @p0

RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_BUS_UpdateCreatedByResFlagForAssnIDs TO MSProjectServerRole
GO


/* Query #335800 */
CREATE PROCEDURE dbo.MSP_WEB_SP_BUS_GetResGraphMainRecords
   @p0 NTEXT,
   @p1 nvarchar(200),
   @p2 INT
AS
BEGIN
  declare @sVer       nvarchar(50)
 
  select @sVer = VERS_VERSION from MSP_VERSIONS where VERS_DEFAULT=1 
  if (@@ROWCOUNT <> 1) RETURN

  select (VPAS.WPROJ_ID*cast (67108864 as float(53)) + AssignmentUniqueID) as WASSN_ID,VPAS.WPROJ_ID,AssignmentUniqueID,AssignmentTaskName,AssignmentResourceName,WP.PROJ_NAME 
    from MSP_VIEW_PROJ_ASSN_STD VPAS INNER JOIN MSP_WEB_PROJECTS WP ON VPAS.WPROJ_ID=WP.WPROJ_ID 
         INNER JOIN MSP_PROJECTS MSPP ON (MSPP.PROJ_ID=WP.PROJ_ID and MSPP.PROJ_VERSION=@sVer)
   where VPAS.ResourceEnterpriseUniqueID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))
     and (AssignmentBookingType<=(@p2))
UNION
  select (-cast (67108864 as float(53)) + ResourceUniqueID) as WASSN_ID,-1 as WPROJ_ID,VRS.ResourceUniqueID as AssignmentUniqueID,@p1 as AssignmentTaskName,ResourceName as AssignmentResourceName,@p1 as PROJ_NAME 
    from MSP_VIEW_RES_STD VRS 
   where VRS.ResourceUniqueID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))

RETURN
END

GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_BUS_GetResGraphMainRecords TO MSProjectServerRole
GO



/* Query #335801 */
CREATE PROCEDURE dbo.MSP_WEB_SP_BUS_GetResGraphTimephasedRecords
   @p0 NTEXT,
   @p1 DATETIME,
   @p2 DATETIME,
   @p3 INT
AS
BEGIN
(
  select (PAS.WPROJ_ID*cast (67108864 as float(53)) + PATBD.AssignmentUniqueID) as WASSN_ID,PAS.WPROJ_ID,PATBD.AssignmentUniqueID,0 as WWORK_TYPE,AssignmentTimeStart as WWORK_START,AssignmentTimeStart as WWORK_FINISH,AssignmentTimeWork as WWORK_VALUE,0 as RESERVED_DATA1 
    from MSP_VIEW_PROJ_ASSN_STD PAS INNER JOIN MSP_VIEW_PROJ_ASSN_TP_BY_DAY PATBD ON (PAS.AssignmentUniqueID=PATBD.AssignmentUniqueID and PAS.WPROJ_ID=PATBD.WPROJ_ID) 
   where ResourceEnterpriseUniqueID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) 
     and (AssignmentTimeStart>=(@p1) and AssignmentTimeFinish<=(@p2)) and (AssignmentBookingType<=(@p2)) 
UNION
  select (-cast (67108864 as float(53)) + ResourceUniqueID) as WASSN_ID,-1 as WPROJ_ID,ResourceUniqueID as AssignmentUniqueID,3 as WWORK_TYPE,ResourceTimeStart as WWORK_START,ResourceTimeStart as WWORK_FINISH,ResourceTimeWorkAvailability as WWORK_VALUE,0 as RESERVED_DATA1 
    from MSP_VIEW_RES_TP_BY_DAY 
   where ResourceUniqueID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))
     and (ResourceTimeStart>=(@p1) and ResourceTimeFinish<=(@p2))
) 
ORDER BY WASSN_ID,WWORK_START,WWORK_TYPE
RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_BUS_GetResGraphTimephasedRecords TO MSProjectServerRole
GO



/* Query #335111 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_SetTaskUpdateTransStateToUpdated
   @p0 INT,
   @p1 NTEXT,
   @p4 INT,
   @p5 DATETIME,
   @p6 INT
AS
UPDATE MSP_WEB_TRANSACTIONS 
SET WTRANS_STATE=@p4,WTRANS_PROJ_UPDATE_DATE=@p5 
WHERE WTRANS_STATE<2 
and WTRANS_ACTION>0 
and (WTRANS_TYPE < 1 - @p6 or WTRANS_TYPE = @p6) 
and WASSN_ID in (
                 SELECT WA.WASSN_ID 
                 FROM MSP_WEB_ASSIGNMENTS WA 
                 WHERE WA.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) 
                       and WA.WRES_ID_MGR=@p0) 
RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_SetTaskUpdateTransStateToUpdated TO MSProjectServerRole
GO

/* Query #335112 */
CREATE PROCEDURE dbo.MSP_WEB_SP_BUS_UpdateAssnDirtyFlagTrackingForAssnId
   @p0 INT,
   @p1 NTEXT
AS
UPDATE MSP_WEB_ASSIGNMENTS 
SET WASSN_SEND_UPDATE_NEEDED=0,
    WASSN_ACTUALS_PENDING=0,
    WASSN_UPDATE_STATUS=0,
    WASSN_UPDATE_TRACKING_MODE=WASSN_CURRENT_TRACKING_MODE 
WHERE WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) and WRES_ID_MGR=@p0 
RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_BUS_UpdateAssnDirtyFlagTrackingForAssnId TO MSProjectServerRole
GO



/* Query #335113 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_GetActualsInfoAssnList
   @p0 NTEXT,
   @p1 INT,
   @p2 INT
AS
Select min(WWORK_START) as WWORK_START,max(WWORK_FINISH) as WWORK_FINISH 
from MSP_WEB_WORK INNER JOIN MSP_WEB_ASSIGNMENTS WA ON MSP_WEB_WORK.WASSN_ID=WA.WASSN_ID 
where WA.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and 
WA.WRES_ID_MGR=@p1 and 
(WWORK_TYPE>0 or @p2=1)
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_GetActualsInfoAssnList TO MSProjectServerRole
GO

/* Query #335115 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_GetAllCustomFieldsForAssnList
   @p0 NTEXT,
   @p1 INT
AS
Select distinct WWF.FIELD_ID,CUSTFIELD_TYPE,WWORKGRP_INFO_IS_READONLY 
from 
MSP_WEB_ASSIGNMENTS WA 
INNER JOIN MSP_WEB_WORKGROUP_FIELDS WWF ON WA.WASSN_ID=WWF.WASSN_ID
INNER JOIN MSP_WEB_WORKGROUP_FIELDS_INFO WWFI ON WWF.FIELD_ID=WWFI.FIELD_ID
INNER JOIN MSP_WEB_PROJECT_WORKGROUP_INFO WPWI ON (WWFI.CUSTFIELD_INFO_ID=WPWI.CUSTFIELD_INFO_ID and WA.WPROJ_ID=WPWI.WPROJ_ID)
where 
WA.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and 
WA.WRES_ID_MGR=@p1 
order by WWF.FIELD_ID 
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_GetAllCustomFieldsForAssnList TO MSProjectServerRole
GO



/* Query #335116 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_MoveCurrentNotesToHistoryOnTransUpdate
   @p0 INT,
   @p1 nvarchar(400),
   @p2 NTEXT
AS

UPDATE MSP_WEB_ASSIGNMENTS SET
  WASSN_HISTORY_NOTES = (@p1 + CHAR(10) + CAST(WASSN_COMMENTS as nvarchar(4000)) + CHAR(10) + CHAR(10) + (CASE WHEN WASSN_HISTORY_NOTES IS NULL THEN N'' ELSE CAST(WASSN_HISTORY_NOTES as nvarchar(4000)) END)),
  WASSN_COMMENTS=NULL,
  WASSN_NOTE_STATUS=2 
WHERE WASSN_COMMENTS IS NOT NULL and 
  WASSN_COMMENTS LIKE N'_%' and 
  WASSN_ID in (
	SELECT WA.WASSN_ID 
  FROM MSP_WEB_ASSIGNMENTS WA INNER JOIN
       MSP_WEB_TRANSACTIONS WT ON WA.WASSN_ID = WT.WASSN_ID 
  WHERE WA.WRES_ID_MGR = @p0 and WA.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p2))
    and WTRANS_ACTION = 1
    and WTRANS_STATE < 3)
RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_MoveCurrentNotesToHistoryOnTransUpdate TO MSProjectServerRole
GO


/* Query #335117 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_MoveCurrentNotesToHistoryForTransType
   @p0 INT,
   @p1 nvarchar(400),
   @p2 INT,
   @p3 INT
AS

UPDATE MSP_WEB_ASSIGNMENTS SET
  WASSN_HISTORY_NOTES = (@p1 + CHAR(10) + CAST(WASSN_COMMENTS as nvarchar(4000)) + CHAR(10) + CHAR(10) + (CASE WHEN WASSN_HISTORY_NOTES IS NULL THEN N'' ELSE CAST(WASSN_HISTORY_NOTES as nvarchar(4000)) END)),
  WASSN_COMMENTS=NULL,
  WASSN_NOTE_STATUS=2 
WHERE WASSN_COMMENTS IS NOT NULL and
  WASSN_COMMENTS LIKE N'_%' and 
  WASSN_ID in (
	SELECT WA.WASSN_ID 
  FROM MSP_WEB_ASSIGNMENTS WA INNER JOIN
       MSP_WEB_TRANSACTIONS WT ON WA.WASSN_ID = WT.WASSN_ID 
  WHERE WA.WRES_ID_MGR = @p0 
    and WPROJ_ID = @p2
    and WTRANS_ACTION = 1
    and WTRANS_STATE < 3
    and WTRANS_TYPE = @p3)
RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_MoveCurrentNotesToHistoryForTransType TO MSProjectServerRole
GO




/* Query #335118 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_UpdateAssnDirtyFlagForActualsForP2000
   @p0 INT,
   @p1 NTEXT
AS
UPDATE MSP_WEB_WORK 
   SET WWORK_UPDATE_STATUS = 0 
 WHERE WASSN_ID in (SELECT WA.WASSN_ID 
                      FROM MSP_WEB_ASSIGNMENTS WA
                     WHERE WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) and WRES_ID_MGR=@p0)
RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_UpdateAssnDirtyFlagForActualsForP2000 TO MSProjectServerRole
GO


/* Query #335119 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_UpdateAssnDirtyFlagForCustomFieldsForP2000
   @p0 INT,
   @p1 NTEXT
AS
--UPDATE MSP_WEB_WORKGROUP_FIELDS SET WWORKGRP_UPDATE_STATUS=0 WHERE WASSN_ID in (SELECT WA.WASSN_ID FROM MSP_WEB_ASSIGNMENTS WA, MSP_WEB_TRANSACTIONS WT WHERE WA.WASSN_ID=WT.WASSN_ID and WA.WPROJ_ID=@p0 and WA.WRES_ID_MGR=@p1 and WT.WTRANS_STATE=2 and WT.WTRANS_TYPE<3 and WT.WTRANS_ACTION=1) RETURN(0)
UPDATE MSP_WEB_WORKGROUP_FIELDS 
   SET WWORKGRP_UPDATE_STATUS = 0 
 WHERE WASSN_ID in (SELECT WA.WASSN_ID 
                      FROM MSP_WEB_ASSIGNMENTS WA
                     WHERE WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) and WRES_ID_MGR=@p0)
RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_UpdateAssnDirtyFlagForCustomFieldsForP2000 TO MSProjectServerRole
GO



/* Query #335120 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_GetResCheckedOutProjectsByResID
   @p0 INT
AS
Select A.PROJ_ID, A.PROJ_NAME, A.PROJ_TYPE, A.PROJ_VERSION, A.PROJ_CHECKOUTBY, B.WRES_EMAIL, A.PROJ_CHECKOUTDATE, A.PROJ_PROJECT From (MSP_PROJECTS AS A INNER JOIN MSP_WEB_RESOURCES AS B ON  A.PROJ_CHECKOUTBY = B.RES_NAME) WHERE A.PROJ_CHECKEDOUT=1 AND A.PROJ_TYPE < 100 and B.WRES_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_GetResCheckedOutProjectsByResID TO MSProjectServerRole
GO


/* Query #335121 */
CREATE PROCEDURE dbo.MSP_WEB_SP_GetResAdminProjectsByResID
   @p0 INT
AS
Select WP.WPROJ_ID, PROJ_NAME, WLOCAL_PATH, PROJ_ID, WPROJ_TYPE 
from MSP_WEB_PROJECTS WP 
INNER JOIN dbo.MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID(@p0, 1013, -1, 3) PL ON WP.WPROJ_ID=PL.WPROJ_ID 
Where WP.WPROJ_ADMINPROJECT=1
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_GetResAdminProjectsByResID TO MSProjectServerRole
GO


/* Query #335122 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_GetProjectTasksForProjID
   @p0 INT,
   @p1 INT
AS

SELECT TaskID,TaskUniqueID,TaskName,TaskWork,TaskStart,TaskFinish,TaskResourceNames,TaskSummary,TaskOutlineLevel,WRES_ID
FROM 
MSP_VIEW_PROJ_TASKS_STD VPS
LEFT OUTER JOIN MSP_WEB_ASSIGNMENTS WA ON (VPS.TaskUniqueID=WA.TASK_UID and WA.WPROJ_ID=@p1 and WA.WRES_ID=@p0 and WASSN_DELETED_IN_PROJ=0 and WASSN_REMOVED_BY_RESOURCE=0)
WHERE VPS.WPROJ_ID=@p1 and (TASK_IS_SUMMARY=1 or WRES_ID is null)

RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_GetProjectTasksForProjID TO MSProjectServerRole
GO



/* Query #370000 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CHK_GetCalendarTransRecords
   @p0 NTEXT,
   @p1 INT,
   @p2 INT
AS
select MSP_WEB_NONWORKING.*,MSP_WEB_RESOURCES.RES_NAME,MSP_WEB_RESOURCES.WRES_USE_NT_LOGON,MSP_WEB_RESOURCES.WRES_NT_ACCOUNT 
from MSP_WEB_NONWORKING,MSP_WEB_MESSAGES,MSP_WEB_MESSAGES_NONWORKING,MSP_WEB_RESOURCES,MSP_WEB_RESOURCES R2 where MSP_WEB_NONWORKING.WNONWORK_ID in ( select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0) ) and MSP_WEB_MESSAGES.WRES_ID_RECEIVER=R2.WRES_ID and R2.RESERVED_DATA3=@p1 and R2.RESERVED_DATA4=@p2 and MSP_WEB_MESSAGES.WMSG_ID=MSP_WEB_MESSAGES_NONWORKING.WMSG_ID and MSP_WEB_MESSAGES_NONWORKING.WNONWORK_ID=MSP_WEB_NONWORKING.WNONWORK_ID and MSP_WEB_RESOURCES.WRES_ID=MSP_WEB_MESSAGES.WRES_ID_SENDER order by MSP_WEB_MESSAGES.WMSG_TIME RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CHK_GetCalendarTransRecords TO MSProjectServerRole
GO


/* Query #65054 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetResIDFromGUID
   @p0 UNIQUEIDENTIFIER
AS
select WRES_ID from MSP_WEB_RESOURCES where WRES_GUID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetResIDFromGUID TO MSProjectServerRole
GO



/* Query #65055 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_CheckSOInCategoryList
   @p0 INT,
   @p1 INT,
   @p2 NTEXT
AS
select 1 where exists(select * from MSP_WEB_SECURITY_CATEGORY_OBJECTS where WSEC_OBJ_TYPE=@p0 and WSEC_OBJ_ID=@p1 and WSEC_CAT_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p2))) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_CheckSOInCategoryList TO MSProjectServerRole
GO



/* Query #65056 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_CheckResHasAssignmentFromMgr
   @p0 INT,
   @p1 INT
AS
select 1 where exists(select * from MSP_WEB_ASSIGNMENTS where WRES_ID=@p0 and WRES_ID_MGR=@p1) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_CheckResHasAssignmentFromMgr TO MSProjectServerRole
GO



/* Query #65057 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_AddNewTAResourceAsManager
   @res_guid uniqueidentifier
AS
   insert into MSP_WEB_SECURITY_GROUP_MEMBERS (WSEC_GRP_GUID, WRES_GUID) values (@res_guid, @res_guid)
   insert into MSP_WEB_SECURITY_GROUP_MEMBERS (WSEC_GRP_GUID, WRES_GUID) select WSEC_GRP_GUID, @res_guid from MSP_WEB_SECURITY_GROUPS where WSEC_GRP_ID=4

   RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_AddNewTAResourceAsManager TO MSProjectServerRole
GO



/* Query #65058 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_AddNewTAResourceAsMember
   @res_guid uniqueidentifier
AS
   insert into MSP_WEB_SECURITY_GROUP_MEMBERS (WSEC_GRP_GUID, WRES_GUID) values (@res_guid, @res_guid)
   insert into MSP_WEB_SECURITY_GROUP_MEMBERS (WSEC_GRP_GUID, WRES_GUID) select WSEC_GRP_GUID, @res_guid from MSP_WEB_SECURITY_GROUPS where WSEC_GRP_ID=7

   RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_AddNewTAResourceAsMember TO MSProjectServerRole
GO



/* Query #65059 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_CopyInsertNewTemplatePermissions
   @newTmplID     INT,
   @copyTmplID    INT
AS
   insert into MSP_WEB_SECURITY_TEMPLATE_PERMISSIONS (WSEC_TMPL_ID, WSEC_ACT_ID, WSEC_ALLOW, WSEC_DENY, WSEC_ACCESS) 
      select @newTmplID, WSEC_ACT_ID, WSEC_ALLOW, WSEC_DENY, WSEC_ACCESS
        from MSP_WEB_SECURITY_TEMPLATE_PERMISSIONS
       where WSEC_TMPL_ID=@copyTmplID

   RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_CopyInsertNewTemplatePermissions TO MSProjectServerRole
GO


/* Query #65060 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_AddResToProjectManagers
  @res_guid uniqueidentifier
AS
BEGIN
  -- Check if @res_guid is already in Project Managers (WSEC_GRP_ID=4) group
  select GM.* from MSP_WEB_SECURITY_GROUP_MEMBERS GM, MSP_WEB_SECURITY_GROUPS G where GM.WRES_GUID=@res_guid and GM.WSEC_GRP_GUID=G.WSEC_GRP_GUID and G.WSEC_GRP_ID=4
  if (@@ROWCOUNT <> 0) RETURN

  -- Add @res_guid into Project Managers group
  insert into MSP_WEB_SECURITY_GROUP_MEMBERS (WSEC_GRP_GUID, WRES_GUID) select WSEC_GRP_GUID, @res_guid from MSP_WEB_SECURITY_GROUPS where WSEC_GRP_ID=4
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_AddResToProjectManagers TO MSProjectServerRole
GO


/* Query #65061 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_AddResToTeamMembers
  @res_guid uniqueidentifier
AS
BEGIN
  -- Check if @res_guid is already in Team Members (WSEC_GRP_ID=7) group
  select GM.* from MSP_WEB_SECURITY_GROUP_MEMBERS GM, MSP_WEB_SECURITY_GROUPS G where GM.WRES_GUID=@res_guid and GM.WSEC_GRP_GUID=G.WSEC_GRP_GUID and G.WSEC_GRP_ID=7
  if (@@ROWCOUNT <> 0) RETURN

  -- Add @res_guid into Team Members group
  insert into MSP_WEB_SECURITY_GROUP_MEMBERS (WSEC_GRP_GUID, WRES_GUID) select WSEC_GRP_GUID, @res_guid from MSP_WEB_SECURITY_GROUPS where WSEC_GRP_ID=7
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_AddResToTeamMembers TO MSProjectServerRole
GO


/* Query #65070 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetSPsForCategoryID
  @p0 INT
AS
  select V.WSEC_SP_ID, V.WSEC_SP_NAME
    from MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR,
         MSP_WEB_VW_SEC_ALLSP V
   where WSEC_CAT_ID = @p0
     and SCR.WSEC_SP_GUID = V.WSEC_SP_GUID
   order by V.WSEC_SP_NAME
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetSPsForCategoryID TO MSProjectServerRole
GO


/* Query #65071 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetResAssignmentsForCategoryID
  @p0 INT
AS
  select WRES_ID, RES_NAME
    from MSP_WEB_SECURITY_CATEGORY_OBJECTS,
         MSP_WEB_RESOURCES
   where WSEC_CAT_ID = @p0
     and WSEC_OBJ_TYPE = 2
     and WSEC_OBJ_ID = WRES_ID
     and NOT (WRES_IS_ENABLED=0 and WRES_CAN_LOGIN=0 and WRES_COUNT_LICENSE=0 and RES_EUID IS NULL)
   Order By RES_NAME
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetResAssignmentsForCategoryID TO MSProjectServerRole
GO


/* Query #65072 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetSPListedGlobalPermissionSettings
  @sp_guid     uniqueidentifier,
  @act_list    ntext,
  @fInclCustom tinyint
AS
BEGIN
  If (@fInclCustom = 0)
   Begin
      Select FA.WSEC_FEA_ACT_ID, dbo.MSP_WEB_FN_SEC_CheckSPGlobalPermission(@sp_guid, FA.WSEC_FEA_ACT_ID) as WSEC_ALLOW
        From MSP_WEB_SECURITY_FEATURES_ACTIONS  FA
       Where FA.WSEC_IS_ACTION = 1 and FA.WSEC_ON_OBJECT = 0
         and FA.WSEC_FEA_ACT_ID in ( select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@act_list) )
   End
  Else
   Begin
      Select FA.WSEC_FEA_ACT_ID, dbo.MSP_WEB_FN_SEC_CheckSPGlobalPermission(@sp_guid, FA.WSEC_FEA_ACT_ID) as WSEC_ALLOW
        From MSP_WEB_SECURITY_FEATURES_ACTIONS  FA
       Where FA.WSEC_IS_ACTION = 1 and FA.WSEC_ON_OBJECT = 0
         and (   FA.WSEC_FEA_ACT_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@act_list))
              or (FA.WSEC_FEA_ACT_ID >= 150 and FA.WSEC_FEA_ACT_ID <= 199)
             )
   End
RETURN
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetSPListedGlobalPermissionSettings TO MSProjectServerRole
GO


/* Query #35300 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetReportNameFromResponseID
   @p0 INT
AS
SELECT WREPORT_NAME FROM MSP_WEB_STATUS_REPORTS INNER JOIN MSP_WEB_STATUS_RESPONSES ON MSP_WEB_STATUS_REPORTS.WSR_ID=MSP_WEB_STATUS_RESPONSES.WSR_ID WHERE WRESP_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetReportNameFromResponseID TO MSProjectServerRole
GO



/* Query #40031 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetResAndMgrForProjId
   @p0 INT
AS
(SELECT DISTINCT WRES_ID FROM MSP_WEB_ASSIGNMENTS WHERE WPROJ_ID=@p0 and WRES_ID IN (SELECT WRES_ID FROM MSP_WEB_RESOURCES) UNION SELECT DISTINCT WRES_ID_MGR AS 'WRES_ID' FROM MSP_WEB_ASSIGNMENTS WHERE WPROJ_ID=@p0 and WRES_ID_MGR IN (SELECT WRES_ID FROM MSP_WEB_RESOURCES)) ORDER BY WRES_ID RETURN
GO




GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetResAndMgrForProjId TO MSProjectServerRole
GO



/* Query #40032 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetResNameFromId
   @p0 INT
AS
SELECT WRES_NT_ACCOUNT FROM MSP_WEB_RESOURCES WHERE WRES_ID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetResNameFromId TO MSProjectServerRole
GO

/* Query #40036 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteStsServer
   @p0 INT
AS
DELETE FROM MSP_WEB_OBJECT_LINKS WHERE WOBJLINK_OBJECT1 IN (SELECT o.WOBJ_ID FROM MSP_WEB_OBJECTS o INNER JOIN MSP_WEB_PROJECTS p ON o.WOBJ_PROJ_ID = p.WPROJ_ID WHERE p.WSTS_SERVER_ID=@p0) OR WOBJLINK_OBJECT2 IN (SELECT o.WOBJ_ID FROM MSP_WEB_OBJECTS o INNER JOIN MSP_WEB_PROJECTS p ON o.WOBJ_PROJ_ID = p.WPROJ_ID WHERE p.WSTS_SERVER_ID=@p0)
DELETE FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID IN (SELECT WPROJ_ID FROM MSP_WEB_PROJECTS WHERE WSTS_SERVER_ID=@p0)
UPDATE MSP_WEB_PROJECTS SET WPROJ_STS_SUBWEB_NAME='NONE',WSTS_SERVER_ID=0,WPROJ_ISSUE_LIST_NAME=null, WPROJ_RISK_LIST_NAME=null WHERE WSTS_SERVER_ID=@p0
DELETE MSP_WEB_STS_SERVERS WHERE WSTS_SERVER_ID=@p0
RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteStsServer TO MSProjectServerRole
GO



/* Query #65047 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetEntProjIDFromProjDBID
   @p0 INT
AS
select PROJ_ID from MSP_WEB_PROJECTS where WPROJ_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetEntProjIDFromProjDBID TO MSProjectServerRole
GO



/* Query #330000 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllProjsSubwebNamesSTSServerNames
AS
SELECT WP.WPROJ_ID, WP.PROJ_NAME, WP.WPROJ_STS_SUBWEB_NAME, WP.WSTS_SERVER_ID, WS.WSTS_SERVER_NAME, WS.WSTS_SERVER_WEB_PORT, WS.WSTS_WEB_PORT_IS_SSL, WSTS_SERVER_ADMIN_PORT, WSTS_ADMIN_PORT_IS_SSL, WS.WSTS_MANAGED_PATH, WS.WSTS_EXTRANET_SERVER_NAME FROM (MSP_WEB_PROJECTS WP LEFT JOIN MSP_WEB_STS_SERVERS WS ON WP.WSTS_SERVER_ID=WS.WSTS_SERVER_ID) WHERE WP.WPROJ_TYPE<>3 and WP.WPROJ_DEFAULT_WPROJ_ID=WP.WPROJ_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllProjsSubwebNamesSTSServerNames TO MSProjectServerRole
GO



/* Query #54012 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetFileIdFromPathOwnerAndEntProjID
   @p0 NVARCHAR(32),
   @p1 NVARCHAR(255),
   @p2 INT
AS
Select * From MSP_WEB_PROJECTS Where PROJ_TIMESTAMP=@p0 and lower(PROJ_NAME)=lower(@p1) and PROJ_ID=@p2 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetFileIdFromPathOwnerAndEntProjID TO MSProjectServerRole
GO



/* Query #30040 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetDocLibDocObjIDs
   @p0 INT,
   @p1 INT,
   @p2 UNIQUEIDENTIFIER
AS
SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_TYPE=(@p0) and WOBJ_PROJ_ID=(@p1) and WOBJ_LIST_NAME=(@p2) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetDocLibDocObjIDs TO MSProjectServerRole
GO



/* Query #30041 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_RemoveAllProjectLinks
   @p0 INT
AS
DELETE FROM MSP_WEB_OBJECT_LINKS WHERE WOBJLINK_OBJECT1 IN (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID=(@p0)) OR WOBJLINK_OBJECT2 IN (SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID=(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_RemoveAllProjectLinks TO MSProjectServerRole
GO



/* Query #30042 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_RemoveAllProjectObjects
   @p0 INT
AS
DELETE FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID=(@p0) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_RemoveAllProjectObjects TO MSProjectServerRole
GO


/* Query #35400 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetOutlineCodeMasksForViewID
   @p3 INT
AS

select WVF.WFIELD_ID,WVF.WFIELD_NAME_OLEDB as TFieldName, MAS.AS_VALUE as TMask, 0 as TRequiredField
from MSP_ATTRIBUTE_STRINGS MAS INNER JOIN MSP_FIELD_ATTRIBUTES MFA ON (MAS.AS_ID=MFA.AS_ID and MAS.PROJ_ID=MFA.PROJ_ID)
INNER JOIN MSP_WEB_VIEW_REPORTS_FIELDS WVRF ON ATTRIB_FIELD_ID=dbo.MSP_WEB_FN_ConvertERMVToEROC(WVRF.WFIELD_ID)
INNER JOIN MSP_WEB_VIEW_FIELDS WVF ON WVRF.WFIELD_ID=WVF.WFIELD_ID
INNER JOIN MSP_PROJECTS MP ON MAS.PROJ_ID=MP.PROJ_ID 
where WVIEW_ID=@p3 and MP.PROJ_TYPE=2 and MFA.ATTRIB_ID=200
union
select WVF.WFIELD_ID,WVF.WFIELD_NAME_OLEDB as TFieldName, MAS.AS_VALUE as TMask, 0 as TRequiredField
from MSP_FIELD_ATTRIBUTES MFA inner join MSP_FIELD_ATTRIBUTES MFA2 on MFA2.ATTRIB_VALUE=MFA.ATTRIB_FIELD_ID
INNER JOIN MSP_ATTRIBUTE_STRINGS MAS ON (MAS.AS_ID=MFA.AS_ID and MAS.PROJ_ID=MFA.PROJ_ID)
INNER JOIN MSP_WEB_VIEW_REPORTS_FIELDS WVRF ON MFA2.ATTRIB_FIELD_ID=dbo.MSP_WEB_FN_ConvertERMVToEROC(WVRF.WFIELD_ID)
INNER JOIN MSP_WEB_VIEW_FIELDS WVF ON WVRF.WFIELD_ID=WVF.WFIELD_ID
INNER JOIN MSP_PROJECTS MP ON MAS.PROJ_ID=MP.PROJ_ID 
where WVIEW_ID=@p3 and MP.PROJ_TYPE=2 and MFA.ATTRIB_ID=200 and MFA2.ATTRIB_ID=212
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetOutlineCodeMasksForViewID TO MSProjectServerRole
GO



/* Query #35401 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetOutlineCodeValuesForViewID
   @p3 INT
AS
select WVF.WFIELD_NAME_OLEDB as TFieldName, OC_CACHED_FULL_NAME, OC_DESCRIPTION, CODE_UID
from MSP_WEB_VIEW_REPORTS_FIELDS WVRF
INNER JOIN MSP_FIELD_ATTRIBUTES MFA ON dbo.MSP_WEB_FN_ConvertERMVToEROC(WVRF.WFIELD_ID)=MFA.ATTRIB_FIELD_ID
INNER JOIN MSP_OUTLINE_CODES MOC ON (MFA.ATTRIB_FIELD_ID=MOC.OC_FIELD_ID or (MFA.ATTRIB_VALUE=MOC.OC_FIELD_ID and ATTRIB_ID=212))
INNER JOIN MSP_PROJECTS MP ON (MOC.PROJ_ID=MP.PROJ_ID and MFA.PROJ_ID=MP.PROJ_ID)
INNER JOIN MSP_WEB_VIEW_FIELDS WVF ON WVRF.WFIELD_ID=WVF.WFIELD_ID 
where WVIEW_ID=@p3 and MP.PROJ_TYPE=2 and OC_CACHED_FULL_NAME is not null 
and (ATTRIB_ID=200 or ATTRIB_ID=212) 
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetOutlineCodeValuesForViewID TO MSProjectServerRole
GO



/* Query #40027 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetMyProjectsForIssuesMainPage
   @p0 INT
AS

SELECT
  DISTINCT P.WPROJ_ID, 
  P.PROJ_NAME, 
  P.WPROJ_STS_SUBWEB_NAME, 
  P.WPROJ_ISSUE_LIST_NAME,
  P.WPROJ_RISK_LIST_NAME,
  S.* 
FROM 
(SELECT WPROJ_ID FROM MSP_WEB_ASSIGNMENTS WHERE (WRES_ID = @p0 or WRES_ID_MGR = @p0) AND WASSN_DELETED_IN_PROJ=0
 union
 SELECT WPROJ_ID FROM MSP_WEB_PROJECTS WHERE WRES_ID = @p0 ) as P2
INNER JOIN MSP_WEB_PROJECTS P ON P.WPROJ_ID = P2.WPROJ_ID
LEFT JOIN MSP_WEB_STS_SERVERS S ON S.WSTS_SERVER_ID = P.WSTS_SERVER_ID 
WHERE
	WPROJ_TYPE < 3
	and WPROJ_IS_NONWORKING = 0
	and P.WPROJ_ID = P.WPROJ_DEFAULT_WPROJ_ID 
ORDER BY P.WPROJ_ID 

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetMyProjectsForIssuesMainPage TO MSProjectServerRole
GO



/* Query #85015 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjectNamesForIDs
   @p0 NTEXT
AS
SELECT PROJ_ID, PROJ_NAME, PROJ_PROP_AUTHOR FROM MSP_PROJECTS WHERE PROJ_ID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjectNamesForIDs TO MSProjectServerRole
GO



/* Query #90015 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetViewTimeStamp
   @p0 INT
AS
select WVIEW_TIMESTAMP from MSP_WEB_VIEW_REPORTS where WVIEW_ID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetViewTimeStamp TO MSProjectServerRole
GO



/* Query #90016 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_CompareGUIDs
   @p0 INT,
   @p1 INT
AS
select case when WVR.WVIEW_TIMESTAMP=WVF.WVIEW_TIMESTAMP then 1 else 0 end as RESULT from MSP_WEB_VIEW_REPORTS WVR, MSP_WEB_VIEW_FAVORITES WVF where WVR.WVIEW_ID = @p0 and WVF.WVIEW_FAV_ID = @p1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_CompareGUIDs TO MSProjectServerRole
GO

/* Query #90019 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetEntCustomField
   @p0 NTEXT
AS
	SELECT * FROM MSP_WEB_FN_QRY_GetEntCustomField(@p0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetEntCustomField TO MSProjectServerRole
GO

/* Query #90022 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_UpdateTimePeriod_Start
AS
	DELETE FROM MSP_WEB_TIME_PERIODS WHERE WPRD_ID>=100
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_UpdateTimePeriod_Start TO MSProjectServerRole
GO

/* Query #90024 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_UpdateTimePeriod_Finish
AS
	IF EXISTS (SELECT * FROM MSP_WEB_TIME_PERIODS WHERE WPRD_ID>=100)
		BEGIN
			UPDATE MSP_WEB_TIME_PERIODS SET WPRD_FINISH_DATE = T1.MinDate FROM (SELECT DATEADD(second, -1,MIN (WPRD_START_DATE)) AS MinDate FROM MSP_WEB_TIME_PERIODS WHERE WPRD_ID>=100) T1 WHERE WPRD_ID=1
			UPDATE MSP_WEB_TIME_PERIODS SET WPRD_START_DATE  = T1.MaxDate FROM (SELECT DATEADD(second,  1,MAX (WPRD_FINISH_DATE)) AS MaxDate FROM MSP_WEB_TIME_PERIODS WHERE WPRD_ID>=100) T1 WHERE WPRD_ID=2
		END
	ELSE
		BEGIN
			UPDATE MSP_WEB_TIME_PERIODS SET WPRD_FINISH_DATE = {d'2000-01-01'} WHERE WPRD_ID=1
			UPDATE MSP_WEB_TIME_PERIODS SET WPRD_START_DATE  = T1.MaxDate FROM (SELECT DATEADD(second,  1,MAX (WPRD_FINISH_DATE)) AS MaxDate FROM MSP_WEB_TIME_PERIODS WHERE WPRD_ID=1) T1 WHERE WPRD_ID=2
		END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_UpdateTimePeriod_Finish TO MSProjectServerRole
GO


/* Query #30013 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllProjectsWithSubwebConfigured
AS
SELECT WP.WPROJ_ID, WP.PROJ_NAME, WP.WPROJ_STS_SUBWEB_NAME, WS.* from (MSP_WEB_PROJECTS WP INNER JOIN MSP_WEB_STS_SERVERS WS ON WP.WSTS_SERVER_ID=WS.WSTS_SERVER_ID) WHERE WP.WSTS_SERVER_ID<>0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllProjectsWithSubwebConfigured TO MSProjectServerRole
GO



/* Query #30043 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetPublicDocsServerAllInfo
AS
SELECT WS.*, WA.WADMIN_PUBDOCS_STS_SUBWEB_NAME, WA.WADMIN_EXTRANET_SERVER_URL FROM (MSP_WEB_ADMIN WA INNER JOIN MSP_WEB_STS_SERVERS WS ON WA.WADMIN_CURRENT_STS_SERVER_ID=WS.WSTS_SERVER_ID) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetPublicDocsServerAllInfo TO MSProjectServerRole
GO



/* Query #30044 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_UpdatePortalSettings
   @p0 NVARCHAR(1024),
   @p1 NVARCHAR(255)
AS
UPDATE MSP_WEB_ADMIN SET WADMIN_STS_PORTAL_URL=NullIf(@p0,''), WADMIN_STS_PORTAL_NAME=NullIf(@p1,'') RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_UpdatePortalSettings TO MSProjectServerRole
GO



/* Query #30046 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_UpdateLastSTSAdminSynchTime
   @p0 DATETIME
AS
UPDATE MSP_WEB_ADMIN SET WADMIN_LAST_STS_ADMIN_SYNCH_TIME=(@p0) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_UpdateLastSTSAdminSynchTime TO MSProjectServerRole
GO



/* Query #30047 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetLastSTSAdminSynchTime
AS
SELECT WADMIN_LAST_STS_ADMIN_SYNCH_TIME from MSP_WEB_ADMIN RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetLastSTSAdminSynchTime TO MSProjectServerRole
GO



/* Query #30048 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetResourceNamesFromIds
   @p0 NTEXT
AS
SELECT WRES_ID, WRES_GUID, WRES_USE_NT_LOGON, WRES_NT_ACCOUNT, RES_NAME, WRES_EMAIL from MSP_WEB_RESOURCES where WRES_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and WRES_USE_NT_LOGON=1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetResourceNamesFromIds TO MSProjectServerRole
GO



/* Query #30049 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAddUserListForSTSManagerRole
   @p0 INT,
   @p1 NTEXT
AS
SELECT WRES_ID, WRES_NT_ACCOUNT, RES_NAME, WRES_EMAIL from MSP_WEB_RESOURCES where WRES_USE_NT_LOGON=1 and (WRES_ID in (SELECT WRES_ID from MSP_WEB_PROJECTS where WPROJ_ID=(@p0)) or WRES_ID in (SELECT DISTINCT WRES_ID_MGR from MSP_WEB_ASSIGNMENTS where WPROJ_ID=(@p0))) and WRES_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAddUserListForSTSManagerRole TO MSProjectServerRole
GO



/* Query #30050 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAddUserListForSTSTeamMemberRole
   @p0 NTEXT,
   @p1 NTEXT
AS
SELECT WRES_ID, WRES_NT_ACCOUNT, RES_NAME, WRES_EMAIL from MSP_WEB_RESOURCES where WRES_USE_NT_LOGON=1 and WRES_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and WRES_ID not in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAddUserListForSTSTeamMemberRole TO MSProjectServerRole
GO



/* Query #30051 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetRemoveUserListFromSTSRoles
   @p0 NTEXT,
   @p1 INT
AS
SELECT WRES_ID, WRES_NT_ACCOUNT, RES_NAME, WRES_EMAIL from MSP_WEB_RESOURCES r where r.WRES_USE_NT_LOGON=1 and r.WRES_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) and not exists (SELECT a.WASSN_ID from MSP_WEB_ASSIGNMENTS a where (a.WRES_ID=r.WRES_ID or a.WRES_ID_MGR=r.WRES_ID) and a.WPROJ_ID=(@p1)) and not exists (SELECT WPROJ_ID from MSP_WEB_PROJECTS p where WPROJ_ID=(@p1) and r.WRES_ID=p.WRES_ID) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetRemoveUserListFromSTSRoles TO MSProjectServerRole
GO



/* Query #30052 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetProjectsAllResIsManager
   @p0 INT
AS
SELECT DISTINCT WP.WPROJ_STS_SUBWEB_NAME, WS.* FROM ((MSP_WEB_ASSIGNMENTS WA INNER JOIN MSP_WEB_PROJECTS WP ON WA.WPROJ_ID=WP.WPROJ_ID) INNER JOIN MSP_WEB_STS_SERVERS WS ON WP.WSTS_SERVER_ID=WS.WSTS_SERVER_ID) WHERE WA.WRES_ID_MGR=(@p0) or WP.WRES_ID=(@p0) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetProjectsAllResIsManager TO MSProjectServerRole
GO



/* Query #30053 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetProjectsAllResIsTeamMember
   @p0 INT
AS
SELECT DISTINCT WP.WPROJ_STS_SUBWEB_NAME, WS.* FROM ((MSP_WEB_ASSIGNMENTS WA INNER JOIN MSP_WEB_PROJECTS WP ON WA.WPROJ_ID=WP.WPROJ_ID) INNER JOIN MSP_WEB_STS_SERVERS WS ON WP.WSTS_SERVER_ID=WS.WSTS_SERVER_ID) WHERE WA.WRES_ID=(@p0) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetProjectsAllResIsTeamMember TO MSProjectServerRole
GO



/* Query #30054 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetProjectStsSiteCount
   @p0 NVARCHAR(128)
AS
SELECT COUNT(*) FROM MSP_WEB_PROJECTS WHERE WPROJ_STS_SUBWEB_NAME=(@p0) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetProjectStsSiteCount TO MSProjectServerRole
GO



/* Query #30055 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetResEmailFromResNTAccountName
   @p0 NVARCHAR(255)
AS
SELECT WRES_EMAIL FROM MSP_WEB_RESOURCES WHERE WRES_NT_ACCOUNT=(@p0) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetResEmailFromResNTAccountName TO MSProjectServerRole
GO



/* Query #30056 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetObjIDListGUIDForProjId
   @p0 INT,
   @p1 INT
AS
SELECT WOBJ_ID, WOBJ_TP_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_PROJ_ID=(@p0) and WOBJ_TYPE=(@p1) ORDER BY WOBJ_TP_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetObjIDListGUIDForProjId TO MSProjectServerRole
GO



/* Query #30057 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllProjsWithSubwebs
AS
SELECT WP.WPROJ_STS_SUBWEB_NAME, WS.* FROM (MSP_WEB_PROJECTS WP INNER JOIN MSP_WEB_STS_SERVERS WS ON WP.WSTS_SERVER_ID=WS.WSTS_SERVER_ID), MSP_WEB_ADMIN WA RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllProjsWithSubwebs TO MSProjectServerRole
GO



/* Query #30058 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetResIDsForAssnIDs
   @p0 INT,
   @p1 NTEXT
AS
SELECT WASSN_ID, WRES_ID FROM MSP_WEB_ASSIGNMENTS WHERE WPROJ_ID=(@p0) and WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) ORDER BY WRES_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetResIDsForAssnIDs TO MSProjectServerRole
GO



/* Query #30059 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllActiveNTUsers
AS
SELECT WRES_NT_ACCOUNT, RES_NAME, WRES_EMAIL FROM MSP_WEB_RESOURCES WHERE WRES_IS_ENABLED=1 and WRES_CAN_LOGIN=1 and WRES_COUNT_LICENSE=1 and WRES_USE_NT_LOGON=1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllActiveNTUsers TO MSProjectServerRole
GO



/* Query #30061 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetPublishedProjCountForProjId
   @p0 INT
AS
SELECT WPROJ_ID, PROJ_NAME FROM MSP_WEB_PROJECTS WHERE WPROJ_ID=(@p0) and WPROJ_TYPE<>3 and WPROJ_DEFAULT_WPROJ_ID=WPROJ_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetPublishedProjCountForProjId TO MSProjectServerRole
GO



/* Query #30062 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetTDLDefaultStartNFinishTimes
AS
SELECT PROJ_OPT_DEF_START_TIME, PROJ_OPT_DEF_FINISH_TIME FROM MSP_PROJECTS WHERE PROJ_TYPE=2 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetTDLDefaultStartNFinishTimes TO MSProjectServerRole
GO



/* Query #30063 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_AddTDLStartNFinishRollupInfo
   @p0 INT
AS
UPDATE MSP_WEB_ASSIGNMENTS SET ASSN_START_DATE=(SELECT MIN(ASSN_START_DATE) FROM MSP_WEB_ASSIGNMENTS WHERE WPROJ_ID=(@p0) and TASK_ID<>0), ASSN_FINISH_DATE=(SELECT MAX(ASSN_FINISH_DATE) FROM MSP_WEB_ASSIGNMENTS WHERE WPROJ_ID=(@p0) and TASK_ID<>0) WHERE WPROJ_ID=(@p0) and TASK_ID=0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_AddTDLStartNFinishRollupInfo TO MSProjectServerRole
GO



/* Query #30064 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetEmptyWebStsServers
AS
SELECT * FROM MSP_WEB_STS_SERVERS WITH (READPAST) WHERE WSTS_SERVER_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetEmptyWebStsServers TO MSProjectServerRole
GO


/* Query #30065 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetSTSGeneralSettings
AS
SELECT WADMIN_PUBDOCS_STS_SUBWEB_NAME, WADMIN_EXTRANET_SERVER_URL, 
(CASE WHEN WSTS_NETBIOS_SERVER_NAME IS NULL THEN N'' ELSE WSTS_NETBIOS_SERVER_NAME END) AS WSTS_NETBIOS_SERVER_NAME
FROM (MSP_WEB_ADMIN LEFT JOIN MSP_WEB_STS_SERVERS ON WADMIN_CURRENT_STS_SERVER_ID=WSTS_SERVER_ID)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetSTSGeneralSettings TO MSProjectServerRole
GO


/* Query #30067 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetResWSSOperationValidatorGUID
   @p1 UNIQUEIDENTIFIER
AS
SELECT WRES_WSS_VALIDATOR_GUID FROM MSP_WEB_RESOURCES WHERE WRES_GUID=(@p1) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetResWSSOperationValidatorGUID TO MSProjectServerRole
GO


/* Query #30068 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_UpdateServerIdForMigratedProjects
   @p0 INT
AS
UPDATE MSP_WEB_PROJECTS SET WSTS_SERVER_ID=(@p0) WHERE WPROJ_STS_SUBWEB_NAME<>N'NONE' RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_UpdateServerIdForMigratedProjects TO MSProjectServerRole
GO


/* Query #30069 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllProjectCountWithSites
AS

SELECT COUNT(*) FROM (MSP_WEB_PROJECTS WP INNER JOIN MSP_WEB_STS_SERVERS WS ON WP.WSTS_SERVER_ID=WS.WSTS_SERVER_ID) WHERE WP.WSTS_SERVER_ID<>0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllProjectCountWithSites TO MSProjectServerRole
GO


/* Query #30070 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetWSSSiteVariableValues
AS

SELECT WADMIN_INTRANET_SERVER_URL, WADMIN_EXTRANET_SERVER_URL, WADMIN_STS_PORTAL_URL, WADMIN_STS_PORTAL_NAME FROM MSP_WEB_ADMIN RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetWSSSiteVariableValues TO MSProjectServerRole
GO

/* Query #30072 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetExistingFavByName
	@p0 INT,
	@p1 INT,
	@p2 NVARCHAR(50)
AS
Select * 
  From MSP_WEB_VIEW_FAVORITES
 Where WRES_ID = @p0 AND WVIEW_TYPE = @p1 AND WVIEW_FAV_NAME = @p2
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetExistingFavByName TO MSProjectServerRole
GO


/* Query #30073 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetLastWSSListsSyncTimes
  @p0 INT,
  @p1 UNIQUEIDENTIFIER
AS

SELECT WPROJ_WSS_LAST_LIST_SYNC_TIME FROM MSP_WEB_WSS_LIST_SYNCHRONIZE_TIMES WHERE WPROJ_ID=@p0 AND WOBJ_LIST_NAME=@p1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetLastWSSListsSyncTimes TO MSProjectServerRole
GO


/* Query #30074 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_SetLastWSSListsSyncTimes
  @p0 INT,
  @p1 UNIQUEIDENTIFIER,
  @p2 NVARCHAR(50)
AS

IF EXISTS (SELECT WPROJ_WSS_LAST_LIST_SYNC_TIME FROM MSP_WEB_WSS_LIST_SYNCHRONIZE_TIMES WHERE WPROJ_ID=@p0 AND WOBJ_LIST_NAME=@p1)
BEGIN
  UPDATE MSP_WEB_WSS_LIST_SYNCHRONIZE_TIMES SET WPROJ_WSS_LAST_LIST_SYNC_TIME=(@p2)	WHERE WPROJ_ID=@p0 AND WOBJ_LIST_NAME=@p1
END
ELSE
BEGIN
  INSERT INTO MSP_WEB_WSS_LIST_SYNCHRONIZE_TIMES (WPROJ_ID, WOBJ_LIST_NAME, WPROJ_WSS_LAST_LIST_SYNC_TIME) VALUES (@p0,@p1,@p2) 
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_SetLastWSSListsSyncTimes TO MSProjectServerRole
GO


/* Query #30075 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetIsHostedOrg
AS

SELECT WADMIN_IS_HOSTED_ORG FROM MSP_WEB_ADMIN RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetIsHostedOrg TO MSProjectServerRole
GO


/* Query #30076 */
-------------------------------------------------------------------------------
--
-- PROCEDURE: MSP_WEB_SP_QRY_GetPSWSSObjectLinkPermissionsForProject
--
-- DESCRIPTION:
--   Perfoms a series of queries to determine if a given user has admin,
--   Project Manager, Team Member or Reader permission on WSS.
--
--   We need this info to secure svr_dbdoblib.asp file when updating links.
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetPSWSSObjectLinkPermissionsForProject
   @nProjId   int,
   @nUserId   int
AS
BEGIN

  declare @bAllowRetVal tinyint
  set @bAllowRetVal=0

  IF EXISTS
  (
    SELECT WPROJ_ID FROM MSP_WEB_PROJECTS WP WHERE WP.WRES_ID=@nUserId AND WP.WPROJ_ID=@nProjId
    UNION
    SELECT DISTINCT WPROJ_ID
      FROM MSP_WEB_ASSIGNMENTS WA 
      WHERE WA.WASSN_DELETED_IN_PROJ=0 AND
      WA.WPROJ_ID=@nProjId AND
      (WA.WRES_ID=@nUserId OR WA.WRES_ID_MGR=@nUserId OR WRES_ID_TEAM_LEAD=@nUserId)
    UNION
    SELECT WPROJ_ID 
      FROM MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID(@nUserId,1012,-1,1)
      WHERE WPROJ_ID=@nProjId
    UNION
    SELECT WPROJ_ID
      FROM MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID(@nUserId,790,-1,1)
      WHERE WPROJ_ID=@nProjId
  )
  BEGIN
    SET @bAllowRetVal=1
    GOTO ExitProc
  END

  ExitProc:
    SELECT 'WSEC_WSSLINK_ALLOWED'=@bAllowRetVal

END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetPSWSSObjectLinkPermissionsForProject TO MSProjectServerRole
GO


/* Query #35301 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_UpdateSRRequestDueDate
   @p0 INT,
   @p1 INT,
   @p2 DATETIME
AS
update MSP_WEB_STATUS_REQUESTS set WDUE_ON=@p2 WHERE WSR_ID=@p1 and WRES_ID_RECEIVER=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_UpdateSRRequestDueDate TO MSProjectServerRole
GO



/* Query #40033 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetStatusResponsesForSRID
   @p0 INT
AS
SELECT WRESP_ID FROM MSP_WEB_STATUS_RESPONSES WHERE WSR_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetStatusResponsesForSRID TO MSProjectServerRole
GO



/* Query #40035 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_UpdateStsServer
   @p0 NVARCHAR(255),
   @p1 INT,
   @p2 TINYINT,
   @p3 INT,
   @p4 TINYINT,
   @p5 NVARCHAR(60),
   @p6 NVARCHAR(255),
   @p7 NVARCHAR(255),
   @p8 INT
AS
UPDATE MSP_WEB_STS_SERVERS SET WSTS_SERVER_NAME=@p0,WSTS_SERVER_WEB_PORT=@p1,WSTS_WEB_PORT_IS_SSL=@p2,WSTS_SERVER_ADMIN_PORT=@p3,WSTS_ADMIN_PORT_IS_SSL=@p4,WSTS_MANAGED_PATH=@p5,WSTS_EXTRANET_SERVER_NAME=NullIf(@p6,''),WSTS_ADMIN_SERVER_NAME=@p7 WHERE WSTS_SERVER_ID=@p8 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_UpdateStsServer TO MSProjectServerRole
GO



/* Query #40037 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ResetCurrentAndPubDocsStsServers
   @p0 INT
AS
UPDATE MSP_WEB_ADMIN SET WADMIN_CURRENT_STS_SERVER_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ResetCurrentAndPubDocsStsServers TO MSProjectServerRole
GO



/* Query #40038 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetStsObjectIdFromTpId
   @p0 INT,
   @p1 UNIQUEIDENTIFIER
AS
SELECT WOBJ_ID FROM MSP_WEB_OBJECTS WHERE WOBJ_TP_ID=@p0 AND WOBJ_LIST_NAME=@p1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetStsObjectIdFromTpId TO MSProjectServerRole
GO



/* Query #40042 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetPublicDocsSubwebName
AS
SELECT WADMIN_PUBDOCS_STS_SUBWEB_NAME FROM MSP_WEB_ADMIN RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetPublicDocsSubwebName TO MSProjectServerRole
GO



/* Query #40049 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetSrResponceFromRespId
   @p0 INT
AS
SELECT SR.*, R.RES_NAME FROM MSP_WEB_STATUS_RESPONSES SR INNER JOIN MSP_WEB_RESOURCES R ON SR.WRES_ID = R.WRES_ID WHERE SR.WRESP_ID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetSrResponceFromRespId TO MSProjectServerRole
GO



/* Query #40050 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllSrResponcesFromUpdateStatus
   @p0 INT
AS
SELECT SR.*, R.RES_NAME FROM MSP_WEB_STATUS_RESPONSES SR INNER JOIN MSP_WEB_RESOURCES R ON SR.WRES_ID = R.WRES_ID WHERE SR.WUPDATE_STATUS = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllSrResponcesFromUpdateStatus TO MSProjectServerRole
GO



/* Query #40051 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetUpdateStatusFromRespId
   @p0 INT
AS
SELECT WUPDATE_STATUS FROM MSP_WEB_STATUS_RESPONSES WHERE WRESP_ID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetUpdateStatusFromRespId TO MSProjectServerRole
GO



/* Query #40052 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetSRespForSRID
   @p0 INT
AS
SELECT WRESP_ID FROM MSP_WEB_STATUS_RESPONSES WHERE WSR_ID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetSRespForSRID TO MSProjectServerRole
GO



/* Query #40053 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteAllSRRespForSRID
   @p0 INT
AS
DELETE FROM MSP_WEB_STATUS_RESPONSES WHERE WSR_ID = @p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteAllSRRespForSRID TO MSProjectServerRole
GO



/* Query #40054 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_DeleteSDistForSRespForSRID
   @p0 INT
AS
DELETE FROM MSP_WEB_STATUS_DISTRIBUTION WHERE WRESP_ID in (SELECT WRESP_ID FROM MSP_WEB_STATUS_RESPONSES WHERE WSR_ID = @p0) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_DeleteSDistForSRespForSRID TO MSProjectServerRole
GO



/* Query #40055 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_StsGetObjectIdsForDeletedTasks
AS
SELECT O.WOBJ_ID FROM MSP_WEB_OBJECTS O LEFT OUTER JOIN MSP_WEB_ASSIGNMENTS A ON O.WOBJ_TASK_ID = A.TASK_UID AND O.WOBJ_PROJ_ID = A.WPROJ_ID WHERE (O.WOBJ_TYPE = 2) AND (A.TASK_UID IS NULL) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_StsGetObjectIdsForDeletedTasks TO MSProjectServerRole
GO



/* Query #40057 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_StsDeleteObject
   @p0 INT
AS
DELETE FROM MSP_WEB_OBJECTS WHERE WOBJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_StsDeleteObject TO MSProjectServerRole
GO



/* Query #40058 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_StsUpdateOtherRefCnt
   @p0 INT,
   @p1 INT
AS
UPDATE MSP_WEB_OBJECTS SET WOBJ_OTHER_REF_CNT=@p1 WHERE WOBJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_StsUpdateOtherRefCnt TO MSProjectServerRole
GO



/* Query #40059 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_StsDeleteAllLinksForMultipleObjects
   @p0 NTEXT
AS
DELETE FROM MSP_WEB_OBJECT_LINKS WHERE (WOBJLINK_OBJECT1 IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) OR (WOBJLINK_OBJECT2 IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_StsDeleteAllLinksForMultipleObjects TO MSProjectServerRole
GO



/* Query #40060 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_StsDeleteObjectsForMultipleObjects
   @p0 NTEXT
AS
DELETE FROM MSP_WEB_OBJECTS WHERE WOBJ_ID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_StsDeleteObjectsForMultipleObjects TO MSProjectServerRole
GO



/* Query #40100 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetEROCDefaultNames
   @p0 INT
AS
select VF.WFIELD_ID, CV.CONV_STRING from MSP_WEB_CONVERSIONS CV, MSP_WEB_VIEW_FIELDS VF where CV.CONV_VALUE=VF.WFIELD_NAME_CONV_VALUE and CV.LANG_ID=@p0 and VF.WFIELD_ID in (205521482,205521484,205521486,205521488,205521490,205521492,205521494,205521496,205521498,205521500,205521502,205521504,205521506,205521508,205521510,205521512,205521514,205521516,205521518,205521520,205521522,205521524,205521526,205521528,205521530,205521532,205521534,205521536,205521538,205521540) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetEROCDefaultNames TO MSProjectServerRole
GO



/* Query #50810 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewTaskTimephasedByDay_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_PROJ_TASK_TP_BY_DAY where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewTaskTimephasedByDay_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #50820 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewTaskTimephasedByDay_SelectEmptyRst0
AS
select * from MSP_VIEW_PROJ_TASK_TP_BY_DAY WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewTaskTimephasedByDay_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #50850 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewCalendars_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_PROJ_CAL where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewCalendars_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #50860 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewCalendars_SelectEmptyRst0
AS
select * from MSP_VIEW_PROJ_CAL WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewCalendars_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #50890 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewCalendarData_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_PROJ_CAL_DATA where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewCalendarData_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #50900 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewCalendarData_SelectEmptyRst0
AS
select * from MSP_VIEW_PROJ_CAL_DATA WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewCalendarData_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #50930 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewCalendarExceptions_DeleteViewTable0
   @p0 INT
AS
delete from MSP_VIEW_PROJ_CAL_EXCEPTIONS where WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewCalendarExceptions_DeleteViewTable0 TO MSProjectServerRole
GO



/* Query #50940 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_ViewCalendarExceptions_SelectEmptyRst0
AS
select * from MSP_VIEW_PROJ_CAL_EXCEPTIONS WITH (READPAST) where WPROJ_ID=-1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_ViewCalendarExceptions_SelectEmptyRst0 TO MSProjectServerRole
GO



/* Query #54013 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetProjIDForToDoListID
   @p0 INT,
   @p1 INT
AS
select WPROJ_TYPE from MSP_WEB_PROJECTS where WPROJ_ID=@p0 and WRES_ID=@p1 and WPROJ_TYPE=3 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetProjIDForToDoListID TO MSProjectServerRole
GO



/* Query #54015 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAssnIDForResIDAndForProjID
   @p0 INT,
   @p1 INT
AS
Select count(*) From MSP_WEB_ASSIGNMENTS Where WASSN_DELETED_IN_PROJ=0 and WPROJ_ID=@p0 and WRES_ID=@p1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAssnIDForResIDAndForProjID TO MSProjectServerRole
GO



/* Query #54016 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetIsConsProjPubAllowed
AS
select WADMIN_CAN_PUBLISH_CONSOLIDATED_PROJECTS from MSP_WEB_ADMIN RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetIsConsProjPubAllowed TO MSProjectServerRole
GO



/* Query #54017 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetIsProjectConsolidatedProj
   @p0 INT
AS
select WPROJ_IS_CONSOLIDATED_PROJECT from MSP_WEB_PROJECTS where WPROJ_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetIsProjectConsolidatedProj TO MSProjectServerRole
GO



/* Query #54018 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_UpdateProjectPublishedDate
   @p0 INT,
   @p1 DATETIME
AS
update MSP_WEB_PROJECTS set WPROJ_LAST_PUB=@p1 WHERE WPROJ_ID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_UpdateProjectPublishedDate TO MSProjectServerRole
GO



/* Query #54019 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_UpdateResourcePublishedDate
   @p0 INT,
   @p1 DATETIME
AS
update MSP_VIEW_RES_STD set ResourceLastPublished=@p1 WHERE ResourceUniqueID=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_UpdateResourcePublishedDate TO MSProjectServerRole
GO



/* Query #67019 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllModelsOrderByName
AS
select WMOD_MODEL_UID, WMOD_MODEL_NAME from MSP_WEB_MODELS order by WMOD_MODEL_NAME RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllModelsOrderByName TO MSProjectServerRole
GO



/* Query #67020 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetOrgApproveTimesheetPermSettings
AS
Select COUNT(*) AS WSEC_ALLOW From MSP_WEB_SECURITY_ORG_PERMISSIONS Where WSEC_FEA_ACT_ID in (211, 212) and WSEC_ACCESS=1 and WSEC_PAID=1 and WSEC_DENY=0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetOrgApproveTimesheetPermSettings TO MSProjectServerRole
GO



/* Query #67137 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_InsertGroupMemberByGrpID
   @p0 INT,
   @p1 uniqueidentifier
AS
insert into MSP_WEB_SECURITY_GROUP_MEMBERS select WSEC_GRP_GUID, @p1 from MSP_WEB_SECURITY_GROUPS where WSEC_GRP_ID=@p0
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_InsertGroupMemberByGrpID TO MSProjectServerRole
GO


/* Query #67138 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetCategoryByCatName
   @p0 NVARCHAR(255)
AS
select WSEC_CAT_ID from MSP_WEB_SECURITY_CATEGORIES where lower(WSEC_CAT_NAME)=lower(@p0) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetCategoryByCatName TO MSProjectServerRole
GO



/* Query #67139 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_UpdateCustomPage
   @p0 INT,
   @p1 INT
AS
update MSP_WEB_SECURITY_PAGES set WSEC_PAGE_MENU_ID=@p0, WSEC_PAGE_MASTER_PAGE_ID=@p1 where WSEC_PAGE_ID=@p1 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_UpdateCustomPage TO MSProjectServerRole
GO



/* Query #67140 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_CustPageURLForPageID
   @p0 INT
AS
select WSEC_PAGE_CUSTOM_URL from MSP_WEB_SECURITY_PAGES where WSEC_PAGE_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_CustPageURLForPageID TO MSProjectServerRole
GO



/* Query #67200 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_CheckRBSDefinedInEnterpriseGlobal
AS
select TOP 1 OC.* from MSP_PROJECTS P, MSP_OUTLINE_CODES OC where P.PROJ_TYPE=2 and P.PROJ_ID=OC.PROJ_ID and OC.OC_FIELD_ID=dbo.MSP_WEB_FN_GetRBSFieldID() and OC_CACHED_IS_VALID=1 and CODE_UID > 0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_CheckRBSDefinedInEnterpriseGlobal TO MSProjectServerRole
GO



/* Query #75005 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CBE_RES1
AS
select WRES_GUID, RES_NAME from MSP_WEB_RESOURCES where WRES_ID=1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_CBE_RES1 TO MSProjectServerRole
GO



/* Query #75006 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAdminADSettings
AS
select * from MSP_WEB_ADMIN_AD RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAdminADSettings TO MSProjectServerRole
GO



/* Query #75007 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_SyncResPoolQuery1
AS
select * from MSP_RESOURCES where (RES_UID > 0) and (PROJ_ID = (select PROJ_ID from MSP_PROJECTS where PROJ_TYPE=3)) order by RES_UID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_SyncResPoolQuery1 TO MSProjectServerRole
GO



/* Query #75008 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_SyncGroupsQuery2
AS
select * from MSP_WEB_SECURITY_GROUPS RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_SyncGroupsQuery2 TO MSProjectServerRole
GO



/* Query #75009 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_SyncResPoolQuery2
AS
select TEXT_FIELD_ID, TEXT_REF_UID, TEXT_VALUE from MSP_TEXT_FIELDS where (TEXT_CATEGORY=1) and (TEXT_FIELD_ID=205520899 or TEXT_FIELD_ID=205521207 or TEXT_FIELD_ID=205520931) and (PROJ_ID = (select PROJ_ID from MSP_PROJECTS where PROJ_TYPE=3)) order by TEXT_REF_UID,TEXT_FIELD_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_SyncResPoolQuery2 TO MSProjectServerRole
GO



/* Query #75010 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_SyncGroupsQuery1
AS
select * from MSP_WEB_RESOURCES RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_SyncGroupsQuery1 TO MSProjectServerRole
GO



/* Query #85021 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetWARPableAttib
   @p0 INT
AS
SELECT ATTRIB_FIELD_ID, ATTRIB_ID, ATTRIB_VALUE FROM MSP_FIELD_ATTRIBUTES WHERE (PROJ_ID = @p0) AND ((ATTRIB_ID = 209) OR (ATTRIB_ID = 212)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetWARPableAttib TO MSProjectServerRole
GO



/* Query #85022 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetPoolResourceSkills
   @p0 NTEXT
AS
SELECT ENT_ResourceUniqueID, ResourceEnterpriseOutlineCode1ID, ResourceEnterpriseOutlineCode2ID, ResourceEnterpriseOutlineCode3ID, ResourceEnterpriseOutlineCode4ID, ResourceEnterpriseOutlineCode5ID, ResourceEnterpriseOutlineCode6ID, ResourceEnterpriseOutlineCode7ID, ResourceEnterpriseOutlineCode8ID, ResourceEnterpriseOutlineCode9ID, ResourceEnterpriseOutlineCode10ID, ResourceEnterpriseOutlineCode11ID, ResourceEnterpriseOutlineCode12ID, ResourceEnterpriseOutlineCode13ID, ResourceEnterpriseOutlineCode14ID, ResourceEnterpriseOutlineCode15ID, ResourceEnterpriseOutlineCode16ID, ResourceEnterpriseOutlineCode17ID, ResourceEnterpriseOutlineCode18ID, ResourceEnterpriseOutlineCode19ID, ResourceEnterpriseOutlineCode20ID, ResourceEnterpriseOutlineCode21ID, ResourceEnterpriseOutlineCode22ID, ResourceEnterpriseOutlineCode23ID, ResourceEnterpriseOutlineCode24ID, ResourceEnterpriseOutlineCode25ID, ResourceEnterpriseOutlineCode26ID, ResourceEnterpriseOutlineCode27ID, ResourceEnterpriseOutlineCode28ID, ResourceEnterpriseOutlineCode29ID, ResourceEnterpriseOutlineCode30ID, ResourceEnterpriseRMV20ID, ResourceEnterpriseRMV21ID, ResourceEnterpriseRMV22ID, ResourceEnterpriseRMV23ID, ResourceEnterpriseRMV24ID, ResourceEnterpriseRMV25ID, ResourceEnterpriseRMV26ID, ResourceEnterpriseRMV27ID, ResourceEnterpriseRMV28ID, ResourceEnterpriseRMV29ID FROM MSP_VIEW_RES_ENT WHERE ENT_ResourceUniqueID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) ORDER BY ENT_ResourceUniqueID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetPoolResourceSkills TO MSProjectServerRole
GO



/* Query #85023 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetSkillDescs
   @p0 INT,
   @p1 NTEXT
AS
SELECT CODE_UID, OC_PARENT, OC_NAME, OC_CACHED_FULL_NAME FROM MSP_OUTLINE_CODES WHERE (PROJ_ID = @p0 ) AND (CODE_UID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1))) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetSkillDescs TO MSProjectServerRole
GO



/* Query #85024 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetPredecessorTaskInfo
   @p0 INT,
   @p1 INT
AS
SELECT TEXT_VALUE FROM MSP_PROJECTS P INNER JOIN MSP_TEXT_FIELDS T ON (P.PROJ_ID= T.PROJ_ID) WHERE T.TEXT_CATEGORY = 4 AND TEXT_FIELD_ID = 239075346 AND P.PROJ_ID = @p0 AND T.TEXT_REF_UID = @p1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetPredecessorTaskInfo TO MSProjectServerRole
GO



/* Query #85025 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetTaskUID
   @p0 NVARCHAR(255),
   @p1 INT
AS
SELECT TASK_UID FROM MSP_PROJECTS P INNER JOIN MSP_TASKS T ON (P.PROJ_ID = T.PROJ_ID) WHERE P.PROJ_NAME = @p0 AND T.TASK_ID = @p1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetTaskUID TO MSProjectServerRole
GO



/* Query #85026 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjUID
   @p0 NVARCHAR(255)
AS
SELECT PROJ_ID FROM MSP_WEB_PROJECTS WHERE lower(PROJ_NAME) = lower(@p0) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjUID TO MSProjectServerRole
GO



/* Query #85027 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetUserID
   @p0 NVARCHAR(255)
AS
SELECT WRES_ID, WRES_GUID FROM MSP_WEB_RESOURCES WHERE lower(RES_NAME) = lower(@p0) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetUserID TO MSProjectServerRole
GO



/* Query #85028 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetUserName
   @p0 INT
AS
SELECT WRES_ID, WRES_GUID, RES_NAME, RES_EUID FROM MSP_WEB_RESOURCES WHERE (WRES_ID = @p0) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetUserName TO MSProjectServerRole
GO



/* Query #85029 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetEntResourcesForIDs
   @p0 NTEXT
AS
SELECT ResourceUniqueID, ResourceName FROM MSP_VIEW_RES_STD INNER JOIN MSP_VIEW_RES_ENT ON ResourceUniqueID = ENT_ResourceUniqueID INNER JOIN MSP_WEB_RESOURCES ON (ResourceUniqueID = RES_EUID) WHERE ResourceType=0 AND ResourceEnterpriseGeneric=0 AND WRES_IS_ENABLED<>0 AND ResourceUniqueID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) ORDER BY ResourceName RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetEntResourcesForIDs TO MSProjectServerRole
GO



/* Query #85030 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjectsForIDs
   @p0 NTEXT
AS
SELECT ProjectUniqueID, MSP_PROJECTS.PROJ_NAME FROM (MSP_VIEW_PROJ_PROJECTS_STD INNER JOIN MSP_PROJECTS ON MSP_VIEW_PROJ_PROJECTS_STD.ProjectUniqueID = MSP_PROJECTS.PROJ_ID) INNER JOIN MSP_WEB_PROJECTS ON MSP_VIEW_PROJ_PROJECTS_STD.WPROJ_ID = MSP_WEB_PROJECTS.WPROJ_ID  WHERE WPROJ_IS_CONSOLIDATED_PROJECT = 0 AND ProjectUniqueID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) ORDER BY MSP_PROJECTS.PROJ_NAME RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjectsForIDs TO MSProjectServerRole
GO



/* Query #85031 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetPoolResNames
   @p0 NTEXT
AS
SELECT ResourceUniqueID, ResourceName, ResourceStandardRate, ResourceOvertimeRate FROM MSP_VIEW_RES_STD WHERE ResourceUniqueID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetPoolResNames TO MSProjectServerRole
GO



/* Query #85032 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjResourceSkills
   @p0 INT,
   @p1 NTEXT
AS
SELECT ENT_ResourceUniqueID, ResourceEnterpriseOutlineCode1ID, ResourceEnterpriseOutlineCode2ID, ResourceEnterpriseOutlineCode3ID, ResourceEnterpriseOutlineCode4ID, ResourceEnterpriseOutlineCode5ID, ResourceEnterpriseOutlineCode6ID, ResourceEnterpriseOutlineCode7ID, ResourceEnterpriseOutlineCode8ID, ResourceEnterpriseOutlineCode9ID, ResourceEnterpriseOutlineCode10ID, ResourceEnterpriseOutlineCode11ID, ResourceEnterpriseOutlineCode12ID, ResourceEnterpriseOutlineCode13ID, ResourceEnterpriseOutlineCode14ID, ResourceEnterpriseOutlineCode15ID, ResourceEnterpriseOutlineCode16ID, ResourceEnterpriseOutlineCode17ID, ResourceEnterpriseOutlineCode18ID, ResourceEnterpriseOutlineCode19ID, ResourceEnterpriseOutlineCode20ID, ResourceEnterpriseOutlineCode21ID, ResourceEnterpriseOutlineCode22ID, ResourceEnterpriseOutlineCode23ID, ResourceEnterpriseOutlineCode24ID, ResourceEnterpriseOutlineCode25ID, ResourceEnterpriseOutlineCode26ID, ResourceEnterpriseOutlineCode27ID, ResourceEnterpriseOutlineCode28ID, ResourceEnterpriseOutlineCode29ID, ResourceEnterpriseOutlineCode30ID, ResourceEnterpriseRMV20ID, ResourceEnterpriseRMV21ID, ResourceEnterpriseRMV22ID, ResourceEnterpriseRMV23ID, ResourceEnterpriseRMV24ID, ResourceEnterpriseRMV25ID, ResourceEnterpriseRMV26ID, ResourceEnterpriseRMV27ID, ResourceEnterpriseRMV28ID, ResourceEnterpriseRMV29ID FROM MSP_VIEW_PROJ_RES_ENT WHERE ENT_ProjectUniqueID = (@p0) AND ENT_ResourceUniqueID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p1)) ORDER BY ENT_ResourceUniqueID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjResourceSkills TO MSProjectServerRole
GO



/* Query #85033 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetLastPubTimestamp
   @p0 INT
AS
SELECT WPROJ_LAST_PUB FROM MSP_WEB_PROJECTS WHERE WPROJ_ID = (@p0) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetLastPubTimestamp TO MSProjectServerRole
GO



/* Query #85034 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjResListFromViews
AS
SELECT ProjectUniqueID, ResourceEnterpriseUniqueID FROM MSP_VIEW_PROJ_RES_STD INNER JOIN MSP_VIEW_PROJ_RES_ENT ON MSP_VIEW_PROJ_RES_STD.WPROJ_ID = MSP_VIEW_PROJ_RES_ENT.WPROJ_ID AND MSP_VIEW_PROJ_RES_STD.ResourceUniqueID = MSP_VIEW_PROJ_RES_ENT.ENT_ResourceUniqueID WHERE ResourceType = 0 AND ResourceEnterpriseGeneric = 0 AND ResourceEnterpriseUniqueID > 0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjResListFromViews TO MSProjectServerRole
GO



/* Query #85035 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjResListFromViewsByVersion
   @p0 NTEXT
AS
SELECT ProjectUniqueID, ResourceEnterpriseUniqueID FROM (MSP_VIEW_PROJ_RES_STD INNER JOIN MSP_VIEW_PROJ_RES_ENT ON MSP_VIEW_PROJ_RES_STD.WPROJ_ID = MSP_VIEW_PROJ_RES_ENT.WPROJ_ID AND MSP_VIEW_PROJ_RES_STD.ResourceUniqueID = MSP_VIEW_PROJ_RES_ENT.ENT_ResourceUniqueID) INNER JOIN MSP_VIEW_PROJ_PROJECTS_ENT ON MSP_VIEW_PROJ_PROJECTS_ENT.WPROJ_ID = MSP_VIEW_PROJ_RES_STD.WPROJ_ID WHERE ResourceType = 0 AND ResourceEnterpriseGeneric = 0 AND ResourceEnterpriseUniqueID > 0 AND ProjectEnterpriseVersion IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjResListFromViewsByVersion TO MSProjectServerRole
GO



/* Query #85036 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_PredecessorsFromViews
AS
SELECT ProjectUniqueID, PredecessorPath from MSP_VIEW_PROJ_PRED WHERE LTRIM(PredecessorPath) + SPACE(1) <> SPACE(1) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_PredecessorsFromViews TO MSProjectServerRole
GO



/* Query #85037 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_SuccessorsFromViews
AS
SELECT ProjectUniqueID, SuccessorPath from MSP_VIEW_PROJ_SUCC WHERE LTRIM(SuccessorPath) + SPACE(1) <> SPACE(1) RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_SuccessorsFromViews TO MSProjectServerRole
GO



/* Query #85038 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetDefaultVersion
AS
SELECT VERS_ID, VERS_VERSION FROM MSP_VERSIONS WHERE VERS_DEFAULT = 1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetDefaultVersion TO MSProjectServerRole
GO



/* Query #85039 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProjectsFromMSP
   @p0 NTEXT
AS
SELECT PROJ_ID, PROJ_NAME, PROJ_VERSION, PROJ_ADMINPROJECT 
FROM MSP_PROJECTS 
WHERE PROJ_ID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0)) 
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProjectsFromMSP TO MSProjectServerRole
GO



/* Query #85050 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetProject
   @p0 INT
AS
SELECT WPROJ_ID, ProjectStartDate, ProjectFinishDate, ProjectStatusDate, ProjectCalendarName from MSP_VIEW_PROJ_PROJECTS_STD WHERE ProjectUniqueID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetProject TO MSProjectServerRole
GO



/* Query #85051 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetTasks
   @p0 INT
AS
SELECT TaskFinish, TaskStart, TaskActualStart, TaskActualFinish, TaskConstraintDate FROM MSP_VIEW_PROJ_TASKS_STD WHERE ProjectUniqueID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetTasks TO MSProjectServerRole
GO



/* Query #85052 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetAssns
   @p0 INT
AS
SELECT AssignmentStart, AssignmentFinish, AssignmentActualStart, AssignmentActualFinish FROM MSP_VIEW_PROJ_ASSN_STD WHERE ProjectUniqueID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetAssns TO MSProjectServerRole
GO



/* Query #85054 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetTaskDetails
   @p0 INT
AS
SELECT TaskID, TaskActualWork, TaskUniqueID, TaskConstraintDate, TaskConstraintType, TaskDuration, TaskDurationElapsed, TaskEffortDriven, TaskEstimated, TaskFinish, TaskIgnoreResourceCalendar, TaskIsNull, TaskLevelAssignments, TaskLevelingCanSplit, TaskLevelingDelay, TaskMilestone, TaskOutlineLevel, TaskPriority, TaskStart, TaskSummary, TaskWork, TaskExternalTask, TaskCalendar, TaskPercentComplete, TaskLevelAssignments, TaskLevelingCanSplit, TaskType, TaskActualStart, TaskActualFinish, TaskActualCost, TaskUniqueIDPredecessors, TaskUniqueIDSuccessors FROM MSP_VIEW_PROJ_TASKS_STD WHERE TaskIsNull = 0 AND TaskUniqueID <> 0 AND ProjectUniqueID = @p0 ORDER BY TaskID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetTaskDetails TO MSProjectServerRole
GO



/* Query #85055 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetPred
   @p0 INT
AS
SELECT TaskUniqueID, PredecessorLag, PredecessorPath, PredecessorTaskUniqueID, PredecessorType, PredecessorLagType FROM MSP_VIEW_PROJ_PRED WHERE ProjectUniqueID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetPred TO MSProjectServerRole
GO



/* Query #85057 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetCalendars
   @p0 INT
AS
SELECT CalendarUniqueID, ResourceUniqueID, CalendarName, CalendarIsBaseCalendar, CalendarBaseCalendarUniqueID FROM MSP_VIEW_PROJ_CAL WHERE ProjectUniqueID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetCalendars TO MSProjectServerRole
GO



/* Query #85059 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetSucc
   @p0 INT
AS
SELECT TaskUniqueID, SuccessorTaskUniqueID, SuccessorPath FROM MSP_VIEW_PROJ_SUCC WHERE ProjectUniqueID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetSucc TO MSProjectServerRole
GO



/* Query #85060 */
CREATE PROCEDURE dbo.MSP_WEB_SP_MDL_GetAssnWorkContour
   @p0 INT,
   @p1 INT
AS
SELECT AssignmentRemainingWorkContour FROM MSP_VIEW_PROJ_ASSN_STD WHERE ProjectUniqueID = @p0 AND AssignmentUniqueID = @p1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_MDL_GetAssnWorkContour TO MSProjectServerRole
GO



/* Query #90017 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetFavoriteViewFromID
   @p0 INT
AS
SELECT * from MSP_WEB_VIEW_FAVORITES WHERE WVIEW_FAV_ID = @p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetFavoriteViewFromID TO MSProjectServerRole
GO



/* Query #90018 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_AddNewViewReports
   @p0 NVARCHAR(255),
   @p1 NVARCHAR(255),
   @p2 INT,
   @p3 INT,
   @p4 NVARCHAR(1024)
AS
INSERT INTO MSP_WEB_VIEW_REPORTS (WVIEW_NAME,WVIEW_DESCRIPTION,WVIEW_TYPE,WVIEW_REPORT_KIND,WVIEW_PATH,WVIEW_TIMESTAMP) VALUES (@p0,@p1,@p2,@p3,@p4,NEWID()) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_AddNewViewReports TO MSProjectServerRole
GO



/* Query #90020 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetClosedPeriodInfo
AS
SELECT WPRD_START_DATE, WPRD_FINISH_DATE,WPRD_STATE FROM MSP_WEB_TIME_PERIODS WHERE WPRD_STATE = 1 AND EXISTS (SELECT * FROM MSP_WEB_ADMIN WHERE WADMIN_TIMESHEET_SPAN = 2 AND WADMIN_PROTECT_ACTUALS =1 ) ORDER BY WPRD_START_DATE RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetClosedPeriodInfo TO MSProjectServerRole
GO



/* Query #90021 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetAllTimePeriodInfo
AS
SELECT WPRD_ID,WPRD_START_DATE, WPRD_FINISH_DATE, WPRD_STATE FROM MSP_WEB_TIME_PERIODS WHERE WPRD_ID >=100 ORDER BY WPRD_START_DATE RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetAllTimePeriodInfo TO MSProjectServerRole
GO



/* Query #90025 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_InsertWorkAdjustInfo
   @p0 INT,
   @p1 DATETIME,
   @p2 INT,
   @p3 DECIMAL(25,6),
   @p4 DECIMAL(25,6),
   @p5 DATETIME,
   @p6 INT
AS
INSERT INTO MSP_WEB_WORK_ADJUSTED (WASSN_ID,WWORK_DATE,WWORK_TYPE,WWORK_VALUE,WWORK_VALUE_ADJUSTED,WWORK_ADJUST_DATE,WRES_ID) VALUES (@p0,@p1,@p2,@p3,@p4,@p5,@p6) RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_InsertWorkAdjustInfo TO MSProjectServerRole
GO

/* Query #90026 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_CreateApprovalRecord
   @p0 INT
AS
DELETE FROM MSP_WEB_WORK_APPROVAL WHERE WAPPROVAL_ID IN (
SELECT DISTINCT WAPPROVAL_ID FROM MSP_WEB_WORK WW INNER JOIN MSP_WEB_WORK_APPROVAL WWA ON (WW.WWORK_START<= WWA.WPRD_FINISH_DATE AND WW.WWORK_FINISH>=WWA.WPRD_START_DATE) 
WHERE WWA.WASSN_ID = @p0 
)

INSERT INTO MSP_WEB_WORK_APPROVAL 
	SELECT DISTINCT WW.WASSN_ID,WW.WRES_ID, WTP.WPRD_START_DATE,WTP.WPRD_FINISH_DATE,-1,0,0 FROM MSP_WEB_WORK WW INNER JOIN MSP_WEB_TIME_PERIODS WTP ON (WW.WWORK_START<= WTP.WPRD_FINISH_DATE AND WW.WWORK_FINISH>=WTP.WPRD_START_DATE AND WTP.WPRD_ID>=100)
	WHERE WW.WASSN_ID = @p0 AND WWORK_VALUE <>0 AND WWORK_TYPE<>0
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_CreateApprovalRecord TO MSProjectServerRole
GO


/* Query #90028 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetTimePeriodInfo
AS
SELECT WPRD_START_DATE, WPRD_FINISH_DATE,WPRD_STATE FROM MSP_WEB_TIME_PERIODS WHERE EXISTS (SELECT * FROM MSP_WEB_ADMIN WHERE WADMIN_TIMESHEET_SPAN = 2 AND WADMIN_PROTECT_ACTUALS =1 ) ORDER BY WPRD_START_DATE RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetTimePeriodInfo TO MSProjectServerRole
GO




/* Query #390003 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetClosedPeriodInfoFromClient
AS
SELECT WPRD_START_DATE, WPRD_FINISH_DATE FROM MSP_WEB_TIME_PERIODS WHERE WPRD_STATE = 1 AND EXISTS (SELECT * FROM MSP_WEB_ADMIN WHERE WADMIN_TIMESHEET_SPAN = 2 AND WADMIN_PROTECT_ACTUALS =1 ) ORDER BY WPRD_START_DATE RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetClosedPeriodInfoFromClient TO MSProjectServerRole
GO



/* Query #190001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetERMVSeparator
AS
SELECT PROJ_ENT_LIST_SEPARATOR FROM MSP_PROJECTS WHERE PROJ_TYPE = 2 
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetERMVSeparator TO MSProjectServerRole
GO


/* Query #390012 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetLastActualPeriodForApproval
   @p0 INT
AS
SELECT TOP 1 WWA.WPRD_START_DATE , WWA.WPRD_FINISH_DATE
FROM MSP_WEB_WORK_APPROVAL WWA
WHERE (WWA.WAPPROVAL_STATUS = 0)
	AND WWA.WRES_ID in (
	-- Permission 212: Approve timesheet permission
        select WRES_ID from MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(@p0, 212, -1)
     )
ORDER BY WWA.WPRD_START_DATE DESC
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetLastActualPeriodForApproval TO MSProjectServerRole
GO


/* Query #390013 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetOneActualPeriodForApproval
   @p0 INT,
   @p1 DATETIME
AS

SELECT TOP 1 WWA.WPRD_START_DATE , WWA.WPRD_FINISH_DATE
FROM MSP_WEB_WORK_APPROVAL WWA
WHERE (WWA.WAPPROVAL_STATUS = 0)
	AND WWA.WRES_ID in (
	-- Permission 212: Approve timesheet permission
		select WRES_ID from MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(@p0, 212, -1)
	 )
	 AND WWA.WPRD_START_DATE<=@p1
ORDER BY WWA.WPRD_START_DATE DESC

GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetOneActualPeriodForApproval TO MSProjectServerRole
GO

/* Query #390014 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetOneActualPeriodForSummary
   @p0 DATETIME
AS

SELECT TOP 1 WTP.WPRD_START_DATE , WTP.WPRD_FINISH_DATE
FROM MSP_WEB_TIME_PERIODS WTP
WHERE (WTP.WPRD_START_DATE<= @p0 AND WTP.WPRD_ID>=100) OR WTP.WPRD_START_DATE = ( SELECT MIN (WPRD_START_DATE) FROM MSP_WEB_TIME_PERIODS WHERE WPRD_ID>=100)
ORDER BY WTP.WPRD_START_DATE DESC

GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_GetOneActualPeriodForSummary TO MSProjectServerRole
GO



/* Query #210237 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_UpdatePublishMasterProject
   @p0 TINYINT
AS
update MSP_WEB_ADMIN set WADMIN_CAN_PUBLISH_CONSOLIDATED_PROJECTS=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_UpdatePublishMasterProject TO MSProjectServerRole
GO



/* Query #210238 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_UpdateIntranetURL
   @p0 NVARCHAR(255)
AS
update MSP_WEB_ADMIN set WADMIN_INTRANET_SERVER_URL=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_UpdateIntranetURL TO MSProjectServerRole
GO



/* Query #210239 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_UpdateExtranetURL
   @p0 NVARCHAR(255)
AS
update MSP_WEB_ADMIN set WADMIN_EXTRANET_SERVER_URL=@p0 RETURN(0)
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_UpdateExtranetURL TO MSProjectServerRole
GO



/* Query #240001 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_GetAllSTSServerForServerId
AS
SELECT WS.*, WA.WADMIN_PUBDOCS_STS_SUBWEB_NAME FROM MSP_WEB_STS_SERVERS WS INNER JOIN MSP_WEB_ADMIN WA ON WS.WSTS_SERVER_ID=WA.WADMIN_CURRENT_STS_SERVER_ID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_GetAllSTSServerForServerId TO MSProjectServerRole
GO



/* Query #265018 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_SecGetModelsForCategoryID
   @p0 INT
AS
select M.WMOD_MODEL_UID, M.WMOD_MODEL_NAME from MSP_WEB_MODELS M INNER JOIN MSP_WEB_SECURITY_CATEGORY_OBJECTS O ON O.WSEC_OBJ_ID = M.WMOD_MODEL_UID Where O.WSEC_OBJ_TYPE = 4 and O.WSEC_CAT_ID = @p0 Order By M.WMOD_MODEL_NAME RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_SecGetModelsForCategoryID TO MSProjectServerRole
GO



/* Query #275007 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_EntResCheckin
AS
select A.* from MSP_RESOURCES AS A INNER JOIN MSP_PROJECTS AS B ON A.PROJ_ID = B.PROJ_ID WHERE B.PROJ_TYPE=3 and A.RES_CHECKEDOUT=1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_EntResCheckin TO MSProjectServerRole
GO



/* Query #275008 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_EntResCheckin2
   @p0 NTEXT,
   @p1 INT,
   @p2 varchar(255)
AS
BEGIN
   SET XACT_ABORT ON

   Update MSP_RESOURCES Set RES_CHECKEDOUT=0, RES_CHECKOUTBY=@p2, RES_CHECKOUTDATE=GETDATE() 
          Where PROJ_ID=@p1 and RES_CHECKEDOUT=1 and RES_UID IN (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))

   SET XACT_ABORT OFF
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_EntResCheckin2 TO MSProjectServerRole
GO



/* Query #275100 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_GetEntpriseProjectDetailByWProjID
   @p0 INT
AS
SELECT TaskID,TaskName,TaskDuration,TaskStart,TaskFinish,TaskPercentComplete,TaskWork,TaskResourceNames,TaskSummary,TaskOutlineLevel FROM ((MSP_VIEW_PROJ_TASKS_STD PTS INNER JOIN MSP_VIEW_PROJ_TASKS_CF PTCF ON PTS.TaskUniqueID=PTCF.CF_TaskUniqueID) INNER JOIN MSP_VIEW_PROJ_TASKS_ENT PTE ON PTS.TaskUniqueID=PTE.ENT_TaskUniqueID) INNER JOIN MSP_WEB_PROJECTS WP ON PTS.WPROJ_ID=WP.WPROJ_ID WHERE PTS.WPROJ_ID=@p0 AND PTCF.WPROJ_ID=@p0 AND PTE.WPROJ_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_GetEntpriseProjectDetailByWProjID TO MSProjectServerRole
GO


/* Query #275101 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_GetEntResourcesManagedByWResID
   @p0 INT
AS
Select distinct R.RES_EUID from MSP_WEB_RESOURCES R, dbo.MSP_WEB_FN_SEC_GetResourcesManagedByResID(@p0, 0, -1) T where R.WRES_ID = T.WRES_ID and R.RES_EUID > 0 order by RES_EUID RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_GetEntResourcesManagedByWResID TO MSProjectServerRole
GO


/* Query #290000 */
CREATE PROCEDURE dbo.MSP_WEB_SP_ADM_GetTimePeriods
AS
SELECT  WPRD_ID, WPRD_START_DATE ,WPRD_FINISH_DATE, WPRD_STATE, RESERVED_DATA1, CASE WHEN EXISTS (SELECT * FROM MSP_WEB_WORK MWW WHERE MWW.WWORK_START<=WPRD_FINISH_DATE AND MWW.WWORK_FINISH>=WPRD_START_DATE AND MWW.WWORK_TYPE !=0) THEN 1 ELSE 0 END AS TREADONLY FROM MSP_WEB_TIME_PERIODS WHERE WPRD_ID >=100 ORDER BY WPRD_START_DATE RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_ADM_GetTimePeriods TO MSProjectServerRole
GO

/*-------------------------------------------------------------------------
 * Given a fea/act id, return if allowed in Organization                   
 * RETURN: 0 -- Denied
 *         1 -- Allowed
 *         2 -- Undefined
 *------------------------------------------------------------------------*/
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_CheckOrgPermission
   @fea_act_id INT,
   @fAllow     tinyint OUTPUT
AS

BEGIN
   set @fAllow = dbo.MSP_WEB_FN_SEC_CheckOrgPermission(@fea_act_id)

   -- return result in a recordset
   select @fAllow
END

GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_CheckOrgPermission TO MSProjectServerRole
GO

/*-------------------------------------------------------------------------*/
/* Check SP's permission on a given category                               */
/*-------------------------------------------------------------------------*/
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_CheckSPCatPermission
   @sp_guid uniqueidentifier,
   @cat_id  int,
   @act_id  int,
   @fAllow  tinyint OUTPUT
AS
BEGIN
  declare @bAllow  tinyint
  declare @bDeny   tinyint
  declare @bAccess tinyint

  -- initialize as denied
  set @fAllow = 0

  -- check for Organization permission
  set @fAllow = dbo.MSP_WEB_FN_SEC_CheckOrgPermission(@act_id)
  if (@fAllow = 0)   goto ExitProc
  set @fAllow = 0
    
  select @bAllow = max(cast(WSEC_ALLOW  as tinyint)), 
         @bDeny  = max(cast(WSEC_DENY   as tinyint)),
         @bAccess= max(cast(WSEC_ACCESS as tinyint))
    from MSP_WEB_SECURITY_SP_CAT_RELATIONS   SCR, 
         MSP_WEB_SECURITY_SP_CAT_PERMISSIONS SCP
   where SCR.WSEC_CAT_ID=@cat_id and SCR.WSEC_REL_ID=SCP.WSEC_REL_ID
     and SCP.WSEC_FEA_ACT_ID=@act_id
     and (SCR.WSEC_SP_GUID=@sp_guid or 
          SCR.WSEC_SP_GUID in
            (select WSEC_GRP_GUID 
               from MSP_WEB_SECURITY_GROUP_MEMBERS
              where WRES_GUID=@sp_guid))
           
  if (@@rowcount = 1) AND (@bAccess = 1) AND (@bDeny = 0) AND (@bAllow = 1)
    set @fAllow = 1

ExitProc:
  --select @fAllow del jh 5/9/01
  select 'WSEC_ALLOW' = @fAllow -- add jh 5/9/01 
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_CheckSPCatPermission TO MSProjectServerRole
GO


/*-------------------------------------------------------------------------*
 * Given a global fea/act id, return if allowed to the SP                  *
 * RETURN: 0 -- Denied (undefined is same as denied)                       *
 *         1 -- Allowed                                                    *
 *-------------------------------------------------------------------------*/
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_CheckSPGlobalPermission
   @sp_guid uniqueidentifier,
   @act_id  int,
   @fAllow  tinyint OUTPUT
AS
  set @fAllow = dbo.MSP_WEB_FN_SEC_CheckSPGlobalPermission(@sp_guid, @act_id)

  -- return the value in recordset to caller.
  select 'WSEC_ALLOW'=@fAllow
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_CheckSPGlobalPermission TO MSProjectServerRole
GO

/* Query #66017 */
/*-------------------------------------------------------------------------*/
/* return all the portfolio/Project/Assignment views that a resource has   */
/*-------------------------------------------------------------------------*/
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetAllResViewsByType
   @res_guid    uniqueidentifier,
   @view_type   int
AS
BEGIN
  -- Check for inputs
  if (@res_guid is null) or (@view_type is null)
    return

  -- return all the given type of views available for the given resource
  select distinct 
        WVIEW_ID, 
        WVIEW_NAME, 
        WVIEW_TYPE, 
        WVIEW_DISPLAY_TYPE, 
        WVIEW_WORK_TYPE, 
        WGANTT_SCHEME_ID, 
        WVIEW_REPORT_KIND, 
        WVIEW_PATH, 
        WVIEW_GROUPING_SORTING_PARAMS,
        WVIEW_FILTER_BY_RBS,
        WGROUP_SCHEME_ID,
        WTABLE_ID,
        WVIEW_SPLITTER_POS,
        WVIEW_OUTLINE_LEVEL,
        WVIEW_TIMESTAMP
    from MSP_WEB_SECURITY_GROUP_MEMBERS GM,
         MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR,
         MSP_WEB_SECURITY_CATEGORY_OBJECTS CO,
         MSP_WEB_VIEW_REPORTS VR
   where GM.WRES_GUID = @res_guid
     and GM.WSEC_GRP_GUID = SCR.WSEC_SP_GUID
     and SCR.WSEC_CAT_ID = CO.WSEC_CAT_ID
     and CO.WSEC_OBJ_TYPE = 3
     and CO.WSEC_OBJ_ID = VR.WVIEW_ID 
     and VR.WVIEW_TYPE = @view_type

RETURN
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetAllResViewsByType TO MSProjectServerRole
GO

/* Query #66035 */
/*-------------------------------------------------------------------------*/
/* return all the Project views that a resource has for a certain project  */
/*-------------------------------------------------------------------------*/
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetAllResProjectViewsByProject
   @res_guid    uniqueidentifier,
   @project_id int
AS
BEGIN
  -- Check for inputs
  if (@res_guid is null) or (@project_id is null)
    return

  -- return all the given type of views available for the given resource
   select distinct WVIEW_ID, WVIEW_NAME, WVIEW_TYPE, WVIEW_DISPLAY_TYPE, WVIEW_WORK_TYPE, 
          WGANTT_SCHEME_ID, WVIEW_REPORT_KIND, WVIEW_PATH, WGROUP_SCHEME_ID, WTABLE_ID,
          WVIEW_GROUPING_SORTING_PARAMS, WVIEW_FILTER_BY_RBS, WVIEW_SPLITTER_POS,
          WVIEW_OUTLINE_LEVEL, WVIEW_TIMESTAMP
    from MSP_WEB_SECURITY_GROUP_MEMBERS GM,
         MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR,
         MSP_WEB_SECURITY_CATEGORY_OBJECTS CO,
         MSP_WEB_VIEW_REPORTS VR
   where GM.WRES_GUID = @res_guid
     and GM.WSEC_GRP_GUID = SCR.WSEC_SP_GUID
     and SCR.WSEC_CAT_ID = CO.WSEC_CAT_ID
     and CO.WSEC_OBJ_TYPE = 3
     and CO.WSEC_OBJ_ID = VR.WVIEW_ID 
     and VR.WVIEW_TYPE = 0

RETURN
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetAllResProjectViewsByProject TO MSProjectServerRole
GO

CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetCatIncludeAllProjForView
   @view_id    int,
   @res_guid   uniqueidentifier
AS
BEGIN
   select CO.WSEC_CAT_ID
     from MSP_WEB_SECURITY_CATEGORY_OBJECTS CO,
          MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR,
          MSP_WEB_SECURITY_CATEGORY_RULES CR,
          MSP_WEB_SECURITY_GROUP_MEMBERS GM
    where CO.WSEC_OBJ_TYPE=3 and CO.WSEC_OBJ_ID=@view_id
      and CO.WSEC_CAT_ID=SCR.WSEC_CAT_ID
      and SCR.WSEC_SP_GUID=GM.WSEC_GRP_GUID and GM.WRES_GUID=@res_guid
      and CO.WSEC_CAT_ID=CR.WSEC_CAT_ID
      and CR.WSEC_OBJ_TYPE=1 and CR.WSEC_OBJ_RULE_TYPE=1 -- All Projects
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetCatIncludeAllProjForView TO MSProjectServerRole
GO

CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetCatIncludeTAProjForView
   @view_id    int,
   @res_guid   uniqueidentifier
AS
BEGIN
   select CO.WSEC_CAT_ID
     from MSP_WEB_SECURITY_CATEGORY_OBJECTS CO,
          MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR,
          MSP_WEB_SECURITY_CATEGORY_RULES CR,
          MSP_WEB_SECURITY_GROUP_MEMBERS GM
    where CO.WSEC_OBJ_TYPE=3 and CO.WSEC_OBJ_ID=@view_id
      and CO.WSEC_CAT_ID=SCR.WSEC_CAT_ID
      and SCR.WSEC_SP_GUID=GM.WSEC_GRP_GUID and GM.WRES_GUID=@res_guid
      and CO.WSEC_CAT_ID=CR.WSEC_CAT_ID
      and CR.WSEC_OBJ_TYPE=1 and CR.WSEC_OBJ_RULE_TYPE=3 -- All TeamAssign Projects
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetCatIncludeTAProjForView TO MSProjectServerRole
GO


/* Query #16005 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetPortfolioViewRSBasedOnFieldList
   @view_id			int,
   @res_id			int,
   @field_list		nvarchar(2000), -- 2000 : MAX_PORTFOLIO_FIELDS
   @filter_string	nvarchar(1500)	-- MAX_FILTERLIST_SIZE
AS
BEGIN
  declare @sql_query as nvarchar(4000)

  if (LEN(@field_list) = 0)
    set @field_list = N'0'

  set @sql_query = N'
  SELECT WP.PROJ_ID,WOBJ_DOC_REF_CNT as WOBJ_DOC_REF_CNT_PORTFOLIO,
         WOBJ_ISSUE_REF_CNT as WOBJ_ISSUE_REF_CNT_PORTFOLIO,
         WOBJ_RISK_REF_CNT as WOBJ_RISK_REF_CNT_PORTFOLIO,
         (case when VERS_WGANTT_STYLE_ID is null then 6 else VERS_WGANTT_STYLE_ID end) as WGANTT_STYLE_TYPE,
         (case when WDSN_ID>0 or WPATH is not null then 1 else 0 end) as TOpenProjectExe, 
         (case when WDSN_ID>0 or WPATH is not null or WPROJ_TYPE>0 then 1 else 0 end) as TOpenProjectView,
         WPROJ_TYPE,WLOCAL_PATH,WA.WASSN_ID,WA.WPROJ_ID,ASSN_START_DATE,ASSN_FINISH_DATE,
         WASSN_SUMMARY_PROGRESS, ^2
    FROM MSP_WEB_ASSIGNMENTS WA INNER JOIN MSP_WEB_PROJECTS WP ON (WA.WPROJ_ID=WP.WPROJ_ID)
         INNER JOIN dbo.MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID(^0, 508, ^1, 3) LP ON (WP.WPROJ_DEFAULT_WPROJ_ID=LP.WPROJ_ID)
         LEFT JOIN MSP_WEB_RESOURCES WR ON (WR.WRES_ID=WP.WRES_ID)
         LEFT JOIN MSP_PROJECTS MP ON (WP.PROJ_ID=MP.PROJ_ID)
         LEFT JOIN MSP_VERSIONS MV ON (MP.PROJ_VERSION=MV.VERS_VERSION)
         LEFT JOIN MSP_WEB_OBJECTS WO ON (WP.WPROJ_ID=WO.WOBJ_PROJ_ID and WO.WOBJ_TYPE=1 and WO.WOBJ_TASK_ID is null)
   WHERE TASK_ID=0 ^3'
  
  set @sql_query = REPLACE(@sql_query, N'^0', @res_id)
  set @sql_query = REPLACE(@sql_query, N'^1', @view_id)
  set @sql_query = REPLACE(@sql_query, N'^2', @field_list)
  set @sql_query = REPLACE(@sql_query, N'^3', @filter_string)

  exec sp_executesql @sql_query

RETURN
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetPortfolioViewRSBasedOnFieldList TO MSProjectServerRole
GO



/* Query #16006 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_PortfolioViewAllFieldList
   @view_id      int,
   @res_id       int,
   @lang_id      int
AS
BEGIN
SELECT 
VF.WFIELD_ID,
WC.CONV_STRING,
WFIELD_NAME_SQL,
WFIELD_TEXTCONV_TYPE,
WFIELD_IS_CUSTOM_FIELD,
WFI.CUSTFIELD_INFO_ID,
VRF.WVIEW_FIELD_WIDTH,
VRF.WVIEW_FIELD_AUTOSIZE,
((CASE WHEN CUSTFIELD_NAME is null OR CUSTFIELD_NAME=N'' THEN WC2.CONV_STRING ELSE CUSTFIELD_NAME END)) as CUSTFIELD_NAME 
FROM 
MSP_WEB_VIEW_REPORTS VR 
INNER JOIN MSP_WEB_VIEW_REPORTS_FIELDS VRF ON VR.WVIEW_ID=VRF.WVIEW_ID
INNER JOIN MSP_WEB_VIEW_FIELDS VF ON VRF.WFIELD_ID=VF.WFIELD_ID 
INNER JOIN MSP_WEB_CONVERSIONS WC ON VF.WFIELD_NAME_CONV_VALUE=WC.CONV_VALUE 
LEFT JOIN MSP_WEB_WORKGROUP_FIELDS_INFO WFI ON VF.WFIELD_ID=WFI.FIELD_ID 
LEFT JOIN MSP_WEB_CONVERSIONS WC2 ON (WFI.CONV_VALUE=WC2.CONV_VALUE and WC2.LANG_ID=@lang_id) 
WHERE VR.WVIEW_ID=@view_id and WC.LANG_ID=@lang_id and 
(WFI.CUSTFIELD_INFO_ID Is Null or WFI.CUSTFIELD_INFO_ID in (
      SELECT DISTINCT PWI.CUSTFIELD_INFO_ID 
      FROM MSP_WEB_PROJECT_WORKGROUP_INFO PWI 
      WHERE PWI.WPROJ_ID in (
        select WPROJ_ID 
        from dbo.MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID(@res_id, 508, @view_id, 3) -- 3: all projects and todolists
        ))
      ) 
Order By WVIEW_FIELD_ORDER

RETURN
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_PortfolioViewAllFieldList TO MSProjectServerRole
GO



CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetProjectViewInfoForViewResProjID
   @view_id   int,
   @res_id    int
AS
BEGIN
   declare @res_guid uniqueidentifier

   -- get the resource's GUID
   select @res_guid=WRES_GUID from MSP_WEB_RESOURCES where WRES_ID=@res_id
   if (@res_guid is null)
      return

   Select MSP_WEB_VIEW_TABLES.*, VR.* 
     From MSP_WEB_VIEW_TABLES,
          MSP_WEB_VIEW_REPORTS VR
    Where MSP_WEB_VIEW_TABLES.WTABLE_ID=VR.WTABLE_ID 
      and VR.WVIEW_ID=@view_id and VR.WVIEW_TYPE=0 -- Project view
      and VR.WVIEW_ID in
          ( -- Resource has access to the view
            Select CO.WSEC_OBJ_ID as WVIEW_ID
              From MSP_WEB_SECURITY_GROUP_MEMBERS GM,
                   MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR,
                   MSP_WEB_SECURITY_CATEGORY_OBJECTS CO
             Where GM.WRES_GUID=@res_guid and GM.WSEC_GRP_GUID=SCR.WSEC_SP_GUID
               and SCR.WSEC_CAT_ID=CO.WSEC_CAT_ID
               and CO.WSEC_OBJ_TYPE=3 -- view
          )

END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetProjectViewInfoForViewResProjID TO MSProjectServerRole
GO

CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetProjectViewReportsForResProjID
   @res_id    int,
   @proj_id   int
AS
BEGIN
   declare @res_guid   uniqueidentifier

   -- check for the correct resource id, and get the resource GUID
   select @res_guid=WRES_GUID from MSP_WEB_RESOURCES where WRES_ID=@res_id
   if (@res_guid is null)
    return null

  -- The views from categories which include ALL projects
  -- UNION
  -- the views from categories which include TA projects, and @proj_id is a TA project
  -- UNION
  -- the views from categories which include @proj_id in its project list.
  --(Select V1.* 
  (Select WVIEW_ID, 
		  WVIEW_NAME, 
		  WVIEW_TYPE, 
		  WVIEW_DISPLAY_TYPE, 
		  WVIEW_WORK_TYPE, 
		  WGANTT_SCHEME_ID, 
		  WVIEW_REPORT_KIND, 
		  WVIEW_PATH, 
		  WGROUP_SCHEME_ID
     From MSP_WEB_VIEW_REPORTS V1,
          MSP_WEB_SECURITY_CATEGORY_OBJECTS CO1,
          MSP_WEB_SECURITY_CATEGORY_RULES CR1,
          MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR1,
          MSP_WEB_SECURITY_GROUP_MEMBERS GM1
    Where V1.WVIEW_TYPE=0   -- project views
      and V1.WVIEW_ID=CO1.WSEC_OBJ_ID and CO1.WSEC_OBJ_TYPE=3   -- view
      and CO1.WSEC_CAT_ID=SCR1.WSEC_CAT_ID
      and SCR1.WSEC_SP_GUID=GM1.WSEC_GRP_GUID and GM1.WRES_GUID=@res_guid
      and CR1.WSEC_CAT_ID=SCR1.WSEC_CAT_ID
      and CR1.WSEC_OBJ_TYPE=3 -- view
      and CR1.WSEC_OBJ_RULE_TYPE=0 -- all projects
  )
  UNION
  (Select WVIEW_ID, 
		  WVIEW_NAME, 
		  WVIEW_TYPE, 
		  WVIEW_DISPLAY_TYPE, 
		  WVIEW_WORK_TYPE, 
		  WGANTT_SCHEME_ID, 
		  WVIEW_REPORT_KIND, 
		  WVIEW_PATH, 
		  WGROUP_SCHEME_ID
     From MSP_WEB_VIEW_REPORTS V2,
          MSP_WEB_SECURITY_CATEGORY_OBJECTS CO2,
          MSP_WEB_SECURITY_CATEGORY_RULES CR2,
          MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR2,
          MSP_WEB_SECURITY_GROUP_MEMBERS GM2
    Where V2.WVIEW_TYPE=0   -- project views
      and V2.WVIEW_ID=CO2.WSEC_OBJ_ID and CO2.WSEC_OBJ_TYPE=3   -- view
      and CO2.WSEC_CAT_ID=SCR2.WSEC_CAT_ID
      and SCR2.WSEC_SP_GUID=GM2.WSEC_GRP_GUID and GM2.WRES_GUID=@res_guid
      and CR2.WSEC_CAT_ID=SCR2.WSEC_CAT_ID
      and CR2.WSEC_OBJ_TYPE=3          -- view
      and CR2.WSEC_OBJ_RULE_TYPE=2     -- all TA projects
      and (exists (Select A.WASSN_ID 
                    From MSP_WEB_ASSIGNMENTS A
                   Where A.WPROJ_ID=@proj_id 
                     and (A.WRES_ID=@res_id or A.WRES_ID_MGR=@res_id)
                  )
          )
  )
  UNION
  (Select WVIEW_ID, 
          WVIEW_NAME, 
          WVIEW_TYPE, 
          WVIEW_DISPLAY_TYPE, 
          WVIEW_WORK_TYPE, 
          WGANTT_SCHEME_ID, 
          WVIEW_REPORT_KIND, 
          WVIEW_PATH, 
          WGROUP_SCHEME_ID
     From MSP_WEB_VIEW_REPORTS V3,
          MSP_WEB_SECURITY_CATEGORY_OBJECTS CO3
    Where V3.WVIEW_TYPE=0   -- project views
      and V3.WVIEW_ID=CO3.WSEC_OBJ_ID and CO3.WSEC_OBJ_TYPE=3   -- view
      and CO3.WSEC_CAT_ID in (
            Select CO4.WSEC_CAT_ID 
              From MSP_WEB_SECURITY_GROUP_MEMBERS GM4,
                   MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR4,
                   MSP_WEB_SECURITY_CATEGORY_OBJECTS CO4
             Where GM4.WRES_GUID=@res_guid and GM4.WSEC_GRP_GUID=SCR4.WSEC_SP_GUID
               and SCR4.WSEC_CAT_ID=CO4.WSEC_CAT_ID
               and CO4.WSEC_OBJ_TYPE=1       -- project
               and CO4.WSEC_OBJ_ID=@proj_id  -- same project id
            )
  )
  Order by WVIEW_NAME
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetProjectViewReportsForResProjID TO MSProjectServerRole
GO


CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetResIDsForAssignmentView
   @res_id   int,
   @view_id  int
AS
BEGIN
  declare @cat_id    int
  declare @rule_type int
  declare @cat_tbl   table (WSEC_CAT_ID int)
  declare @res_guid  uniqueidentifier

  declare @rule_0_visited tinyint
  declare @rule_1_visited tinyint
  declare @rule_2_visited tinyint

  set @rule_0_visited = 0
  set @rule_1_visited = 0
  set @rule_2_visited = 0

  -- get the resource's GUID
  select @res_guid=WRES_GUID from MSP_WEB_RESOURCES where WRES_ID=@res_id
  if (@res_guid is null)
    return

  -- Cursor: get all the categories with assignments defined
  DECLARE sql_cursor CURSOR FOR
  select distinct CR.WSEC_CAT_ID, CR.WSEC_OBJ_RULE_TYPE
    from MSP_WEB_SECURITY_GROUP_MEMBERS GM,
         MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR,
         MSP_WEB_SECURITY_CATEGORY_RULES CR,
         MSP_WEB_SECURITY_CATEGORY_OBJECTS CO
   where GM.WRES_GUID=@res_guid
     and GM.WSEC_GRP_GUID=SCR.WSEC_SP_GUID
     and SCR.WSEC_CAT_ID=CO.WSEC_CAT_ID
     and CO.WSEC_OBJ_TYPE=3 and CO.WSEC_OBJ_ID=@view_id
     and SCR.WSEC_CAT_ID=CR.WSEC_CAT_ID
     and CR.WSEC_OBJ_TYPE=2 -- assignment

  OPEN sql_cursor
  FETCH NEXT FROM sql_cursor INTO @cat_id, @rule_type
  WHILE (@@FETCH_STATUS = 0)
  BEGIN
    -- assignment view rules:
    -- 0 : All current and future resources
    if (@rule_type = 0)
    begin
       set @rule_0_visited = 1
       break
    end

    -- 1 : All resources in the list
    else if (@rule_type = 1)
    begin
      set @rule_1_visited = 1
      insert into @cat_tbl (WSEC_CAT_ID) values (@cat_id)
    end

    -- 2 : All resources I assigned tasks to
    else if (@rule_type = 2)
    begin
      set @rule_2_visited = 1
    end

    FETCH NEXT FROM sql_cursor INTO @cat_id, @rule_type
  END
  CLOSE sql_cursor
  DEALLOCATE sql_cursor

  -- all current and future resources
  if (@rule_0_visited = 1)
  begin
    -- return 'All'
    select 'All'
    -- select WRES_ID from MSP_WEB_RESOURCES
    return
  end

  -- only resources in category_objects table
  if (@rule_1_visited = 1) AND (@rule_2_visited = 0)
  begin
    select distinct WSEC_OBJ_ID as WRES_ID from MSP_WEB_SECURITY_CATEGORY_OBJECTS where WSEC_OBJ_TYPE=2 and WSEC_CAT_ID in (select WSEC_CAT_ID from @cat_tbl)
    return
  end

  -- only resources I assign to PLUS myself
  if (@rule_2_visited = 1) AND (@rule_1_visited = 0)
  begin
    select distinct WRES_ID from MSP_WEB_ASSIGMENTS where WRES_ID_MGR=@res_id or WRES_ID=@res_id
    return
  end

  -- All resources in the list and I assign to PLUS myself
  if (@rule_1_visited = 1) AND (@rule_2_visited = 1)
  begin
    select distinct WSEC_OBJ_ID as WRES_ID from MSP_WEB_SECURITY_CATEGORY_OBJECTS 
     where WSEC_OBJ_TYPE=2 and WSEC_CAT_ID in (select WSEC_CAT_ID from @cat_tbl)
    UNION
    select distinct A.WRES_ID from MSP_WEB_ASSIGNEMNTS A
     where WRES_ID_MGR=@res_id or WRES_ID=@res_id

    return
  end

  -- Otherwise, return the resource only.
  select @res_id as WRES_ID
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetResIDsForAssignmentView TO MSProjectServerRole
GO


CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetUserMenu
   @res_guid  uniqueidentifier,
   @langid    int
AS
BEGIN
   Select WSEC_MENU_PAGE_ID, WSEC_MENU_ID, CV.CONV_STRING as WSEC_MENU_NAME, WSEC_MENU_CUSTOM_NAME, WSEC_MENU_PARENT_ID, WSEC_MENU_SEQ, 
          dbo.MSP_WEB_FN_SEC_CheckSPGlobalPermission(@res_guid, PG.WSEC_PAGE_ACT_ID) as WSEC_ALLOW,
          PG.WSEC_PAGE_ACT_ID, PG.WSEC_PAGE_URL, PG.WSEC_PAGE_CAN_OFFLINE, WSEC_MENU_IS_CUSTOM,
          CV1.CONV_STRING as WSEC_MENU_DESC, WSEC_MENU_CUSTOM_DESC,CV2.CONV_STRING as WSEC_MENU_LINKGROUP_NAME
     From ( MSP_WEB_SECURITY_MENUS MN LEFT OUTER JOIN MSP_WEB_CONVERSIONS CV On MN.WSEC_MENU_NAME_ID=CV.CONV_VALUE and CV.LANG_ID=@langid and CV.STRING_TYPE_ID=5 ) 
     LEFT OUTER JOIN MSP_WEB_CONVERSIONS CV1 ON ( MN.WSEC_MENU_DESC_ID=CV1.CONV_VALUE and CV.LANG_ID=@langid and CV.STRING_TYPE_ID=5 )
     LEFT OUTER JOIN MSP_WEB_SECURITY_PAGES PG ON (MN.WSEC_MENU_PAGE_ID = PG.WSEC_PAGE_ID) 
	 LEFT OUTER JOIN MSP_WEB_CONVERSIONS CV2 ON (MN.WSEC_MENU_LINKGROUP_NAME_ID = CV2.CONV_VALUE and CV2.LANG_ID=@langid and CV2.STRING_TYPE_ID = 8)
 Order By WSEC_MENU_PARENT_ID, WSEC_MENU_SEQ
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetUserMenu TO MSProjectServerRole
GO

/* Query #16079 */
CREATE     PROCEDURE dbo.MSP_WEB_SP_SEC_GetWebClientViewRSBasedOnFieldListInternal
   @view_id      int,
   @res_id       int,
   @field_list   nvarchar(2000), -- 2000 : MAX_PORTFOLIO_FIELDS
   @includeNWT   int,
   @dCurDate     nvarchar(100),
   @bAllAssn     int,
   @sResIDList   nvarchar (1500),
   @permission_id int
AS
BEGIN
  declare @sql_query as nvarchar (4000)

  if (LEN(@field_list) = 0)
    set @field_list = N'0'

  if (LEN(@sResIDList) = 0)
    set @sResIDList = N'-1'


  set @sql_query = N'
  Select WOBJ_DOC_REF_CNT,WOBJ_ISSUE_REF_CNT,WOBJ_RISK_REF_CNT,ASSN_ACT_WORK,
         abs(WDELEG_REJECT)+abs(WASSN_DELEG_PENDING-1)+(CASE WHEN WR1.WRES_ID is null THEN 0 ELSE 1 END)+(case when WA.WRES_ID_TEAM_LEAD is null then -1 else 2 end) as TDelegIndicator,
         WDELEG_DATE,WASSN_REQUEST_UPDATE,WASSN_RESOURCE_UPDATE,WASSN_ACTUALS_PENDING, WASSN_UPDATE_STATUS,WR0.RES_NAME as TManagerName,
         WASSN_CREATED_BY_RES+WASSN_ASSIGNED_TO_EXISTING as TNewTaskIndic,WR1.RES_NAME AS TDelegatorName,WR2.RES_NAME AS TDelegeeName,WR3.RES_NAME AS TLeadName,
         WASSN_IS_NEW_ASSN,WASSN_DELETED_IN_PROJ,WA.WRES_ID,WR.RES_NAME,WA.WPROJ_ID,PROJ_NAME,WPROJ_TYPE,WPROJ_ADMINPROJECT as TProjNWT,WPROJ_ADMINPROJECT,
         OPT_DEF_START_TIME,OPT_DEF_FINISH_TIME,WA.WASSN_ID,TASK_UID_SUMMARY,TASK_ID,TASK_UID,TASK_IS_SUMMARY,TASK_IS_MILESTONE,
         ASSN_START_DATE,ASSN_FINISH_DATE,ASSN_WORK,ASSN_REM_WORK,WASSN_PCT_COMP, ^2, WA.WASSN_SEND_UPDATE_DATE, WA.TASK_NAME,WA.WASSN_CURRENT_TRACKING_MODE,WA.WASSN_SEND_UPDATE_NEEDED
    From ((((((MSP_WEB_ASSIGNMENTS WA INNER JOIN MSP_WEB_PROJECTS ON WA.WPROJ_ID=MSP_WEB_PROJECTS.WPROJ_ID) 
         INNER JOIN MSP_WEB_RESOURCES WR ON WA.WRES_ID=WR.WRES_ID) 
         LEFT JOIN MSP_WEB_RESOURCES WR0 ON WA.WRES_ID_MGR=WR0.WRES_ID) 
         LEFT JOIN MSP_WEB_DELEGATIONS WD ON WA.WASSN_LAST_DELEG_ID=WD.WDELEG_ID) 
         LEFT JOIN MSP_WEB_RESOURCES WR1 ON WD.WRES_ID_DELEGATOR=WR1.WRES_ID) 
         LEFT JOIN MSP_WEB_RESOURCES WR2 ON WD.WRES_ID_DELEGATEE=WR2.WRES_ID) 
         LEFT JOIN MSP_WEB_RESOURCES WR3 ON WA.WRES_ID_TEAM_LEAD=WR3.WRES_ID 
         LEFT JOIN MSP_WEB_OBJECTS WO ON (WA.WPROJ_ID=WO.WOBJ_PROJ_ID AND WA.TASK_UID=WO.WOBJ_TASK_ID)
   Where (WA.WASSN_IS_CONFIRMED<>0 OR MSP_WEB_PROJECTS.WPROJ_ADMINPROJECT<>0)
     and (CASE WHEN ^3 =0 AND MSP_WEB_PROJECTS.WPROJ_ADMINPROJECT<>0 THEN 0 ELSE 1 END) = 1
     and WA.WASSN_REMOVED_BY_RESOURCE=0
     and WA.WRES_ID in (
            select WRES_ID from MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(^0, ^7, ^1)
         )
     and WA.WRES_ID in (^6)
     and (((WA.ASSN_START_DATE < N''^4'') AND (WA.WASSN_PCT_COMP< 100)) 
	        OR ((WA.ASSN_START_DATE IS NULL AND (WA.ASSN_FINISH_DATE IS NULL OR WA.ASSN_FINISH_DATE< N''^4'')) AND WA.WASSN_PCT_COMP< 100) 
          OR (WA.WASSN_SEND_UPDATE_NEEDED <> 0) 
          OR (WA.WASSN_PCT_COMP< 100 AND WASSN_PCT_COMP>0) 
          OR (WA.WASSN_IS_NEW_ASSN <> 0)
          OR (WA.TASK_IS_SUMMARY<>0) 
          OR (^5<>0))'


  set @sql_query = REPLACE(@sql_query, N'^0', @res_id)
  set @sql_query = REPLACE(@sql_query, N'^1', @view_id)
  set @sql_query = REPLACE(@sql_query, N'^2', @field_list)
  set @sql_query = REPLACE(@sql_query, N'^3', @includeNWT)
  set @sql_query = REPLACE(@sql_query, N'^4', @dCurDate)
  set @sql_query = REPLACE(@sql_query, N'^5', @bAllAssn)
  set @sql_query = REPLACE(@sql_query, N'^6', @sResIDList)
  set @sql_query = REPLACE(@sql_query, N'^7', @permission_id)

exec sp_executesql @sql_query

RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetWebClientViewRSBasedOnFieldListInternal TO MSProjectServerRole
GO

/* Query #16034 */
CREATE     PROCEDURE dbo.MSP_WEB_SP_SEC_GetWebClientViewRSBasedOnFieldList
   @view_id      int,
   @res_id       int,
   @field_list   nvarchar(2000), -- 2000 : MAX_PORTFOLIO_FIELDS
   @includeNWT   int,
   @dCurDate     nvarchar(100),
   @bAllAssn     int,
   @sResIDList   nvarchar (1500)
AS
BEGIN
EXEC MSP_WEB_SP_SEC_GetWebClientViewRSBasedOnFieldListInternal @view_id,@res_id,@field_list,@includeNWT,@dCurDate,@bAllAssn,@sResIDList,510
RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetWebClientViewRSBasedOnFieldList TO MSProjectServerRole
GO

/* Query #16078 */
CREATE     PROCEDURE dbo.MSP_WEB_SP_SEC_GetAdjustActualsViewRSBasedOnFieldList
   @view_id      int,
   @res_id       int,
   @field_list   nvarchar(2000), -- 2000 : MAX_PORTFOLIO_FIELDS
   @includeNWT   int,
   @dCurDate     nvarchar(100),
   @bAllAssn     int,
   @sResIDList   nvarchar (1500)
AS
BEGIN
	EXEC MSP_WEB_SP_SEC_GetWebClientViewRSBasedOnFieldListInternal @view_id,@res_id,@field_list,@includeNWT,@dCurDate,@bAllAssn,@sResIDList,513
RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetAdjustActualsViewRSBasedOnFieldList TO MSProjectServerRole
GO




/* Query #16034 */
CREATE     PROCEDURE dbo.MSP_WEB_SP_SEC_GetWebClientViewRSBasedOnFieldList2
   @view_id      int,
   @res_id       int,
   @field_list   nvarchar(2000), -- 2000 : MAX_PORTFOLIO_FIELDS
   @includeNWT   int,
   @dCurDate     nvarchar(100),
   @bAllAssn     int,
   @sResIDList   nvarchar (1500)
AS
BEGIN
  declare @sql_query as nvarchar (4000)

  if (LEN(@field_list) = 0)
    set @field_list = N'0'

  if (LEN(@sResIDList) = 0)
    set @sResIDList = N'-1'


  set @sql_query = N'
  Select WOBJ_DOC_REF_CNT,WOBJ_ISSUE_REF_CNT,WOBJ_RISK_REF_CNT,
         abs(WDELEG_REJECT)+abs(WASSN_DELEG_PENDING-1)+(CASE WHEN WR1.WRES_ID is null THEN 0 ELSE 1 END)+(case when WA.WRES_ID_TEAM_LEAD is null then -1 else 2 end) as TDelegIndicator,
         WDELEG_DATE,WASSN_REQUEST_UPDATE,WASSN_RESOURCE_UPDATE,WASSN_ACTUALS_PENDING, WASSN_UPDATE_STATUS,WR0.RES_NAME as TManagerName,
         WASSN_CREATED_BY_RES+WASSN_ASSIGNED_TO_EXISTING as TNewTaskIndic,WR1.RES_NAME AS TDelegatorName,WR2.RES_NAME AS TDelegeeName,WR3.RES_NAME AS TLeadName,
         WASSN_IS_NEW_ASSN,WASSN_DELETED_IN_PROJ,WA.WRES_ID,WR.RES_NAME,WA.WPROJ_ID,PROJ_NAME,WPROJ_TYPE,WPROJ_ADMINPROJECT as TProjNWT,
         OPT_DEF_START_TIME,OPT_DEF_FINISH_TIME,WA.WASSN_ID,TASK_UID_SUMMARY,TASK_ID,TASK_UID,TASK_IS_SUMMARY,TASK_IS_MILESTONE,
         ASSN_START_DATE,ASSN_FINISH_DATE,ASSN_WORK,ASSN_REM_WORK,WASSN_PCT_COMP, ^2, WA.WASSN_SEND_UPDATE_DATE 
    From ((((((MSP_WEB_ASSIGNMENTS WA INNER JOIN MSP_WEB_PROJECTS ON WA.WPROJ_ID=MSP_WEB_PROJECTS.WPROJ_ID) 
         INNER JOIN MSP_WEB_RESOURCES WR ON WA.WRES_ID=WR.WRES_ID) 
         LEFT JOIN MSP_WEB_RESOURCES WR0 ON WA.WRES_ID_MGR=WR0.WRES_ID) 
         LEFT JOIN MSP_WEB_DELEGATIONS WD ON WA.WASSN_LAST_DELEG_ID=WD.WDELEG_ID) 
         LEFT JOIN MSP_WEB_RESOURCES WR1 ON WD.WRES_ID_DELEGATOR=WR1.WRES_ID) 
         LEFT JOIN MSP_WEB_RESOURCES WR2 ON WD.WRES_ID_DELEGATEE=WR2.WRES_ID) 
         LEFT JOIN MSP_WEB_RESOURCES WR3 ON WA.WRES_ID_TEAM_LEAD=WR3.WRES_ID 
         LEFT JOIN MSP_WEB_OBJECTS WO ON (WA.WPROJ_ID=WO.WOBJ_PROJ_ID AND WA.TASK_UID=WO.WOBJ_TASK_ID)
   Where (WA.WASSN_IS_CONFIRMED<>0 OR MSP_WEB_PROJECTS.WPROJ_ADMINPROJECT<>0)
     and (CASE WHEN ^3 =0 AND MSP_WEB_PROJECTS.WPROJ_ADMINPROJECT<>0 THEN 0 ELSE 1 END) = 1
     and WA.WASSN_REMOVED_BY_RESOURCE=0
     and WA.WRES_ID in (
            -- Permission 510: See Resource Assignments in Assignment Views
            select WRES_ID from MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(^0, 510, ^1)
         )
     and WA.WRES_ID in (^6)
     and (((WA.ASSN_START_DATE < N''^4'') AND (WA.WASSN_PCT_COMP< 100 OR WA.TASK_IS_SUMMARY<>0)) 
	  OR ((WA.ASSN_START_DATE IS NULL AND (WA.ASSN_FINISH_DATE IS NULL OR WA.ASSN_FINISH_DATE< N''^4'')) AND WA.WASSN_PCT_COMP< 100) 
          OR (WA.WASSN_SEND_UPDATE_NEEDED <> 0) 
          OR (WA.WASSN_PCT_COMP< 100 AND WASSN_PCT_COMP>0) 
          OR (WA.WASSN_IS_NEW_ASSN <> 0) 
          OR (^5<>0))'


  set @sql_query = REPLACE(@sql_query, N'^0', @res_id)
  set @sql_query = REPLACE(@sql_query, N'^1', @view_id)
  set @sql_query = REPLACE(@sql_query, N'^2', @field_list)
  set @sql_query = REPLACE(@sql_query, N'^3', @includeNWT)
  set @sql_query = REPLACE(@sql_query, N'^4', @dCurDate)
  set @sql_query = REPLACE(@sql_query, N'^5', @bAllAssn)
  set @sql_query = REPLACE(@sql_query, N'^6', @sResIDList)

exec sp_executesql @sql_query

RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetWebClientViewRSBasedOnFieldList2 TO MSProjectServerRole
GO

/*-------------------------------------------------------------------------
 * Given a fea/act id, return if allowed in Organization                   
 * RETURN: 0 -- Denied
 *         1 -- Allowed
 *         2 -- Undefined
 *------------------------------------------------------------------------*/
CREATE FUNCTION dbo.MSP_WEB_FN_SEC_CheckOrgPermission(
   @fea_act_id INT
)
RETURNS tinyint
AS
BEGIN
   declare @bAllow  tinyint
   declare @bDeny   tinyint
   declare @bAccess tinyint
   declare @bPaid   tinyint
   declare @fAllow  tinyint

   -- init output to be 'undefined'
   set @fAllow = 2

   select @bAllow=WSEC_ALLOW, @bDeny=WSEC_DENY, @bAccess=WSEC_ACCESS, @bPaid=WSEC_PAID
     from MSP_WEB_SECURITY_ORG_PERMISSIONS
    where WSEC_FEA_ACT_ID=@fea_act_id

   if (@@rowcount = 1) 
    begin
      if (@bPaid = 1) AND (@bAccess = 1) AND (@bDeny = 0) AND (@bAllow = 1)
         set @fAllow = 1
      else
         if (@bPaid = 0) OR (@bAccess = 0) OR (@bDeny = 1)
            set @fAllow = 0
         else
            set @fAllow = 2
    end
   else
      set @fAllow = 0

   return @fAllow
END

GO

GRANT EXECUTE ON dbo.MSP_WEB_FN_SEC_CheckOrgPermission TO MSProjectServerRole
GO

CREATE FUNCTION dbo.MSP_WEB_FN_SEC_CheckSPGlobalPermission(
   @sp_guid uniqueidentifier,
   @act_id  int
)
RETURNS tinyint
AS
BEGIN
   declare @fReturn as tinyint
   declare @bAllow  as tinyint
   declare @bDeny   as tinyint
   declare @bAccess as tinyint

   -- initialize the return as not allowed
   set @fReturn = 0

   -- null or 0 action id means no security checking.
   if (@act_id is null) OR (@act_id = 0)
   Begin
     set @fReturn = 1
     goto ExitFunc
   End

   -- check for Organization permission
   set @fReturn = dbo.MSP_WEB_FN_SEC_CheckOrgPermission(@act_id)
   if (@fReturn = 0)    goto ExitFunc
   set @fReturn = 0

   -- check for user/group specific permission    
   select @bAllow = max(cast(WSEC_ALLOW  as tinyint)), 
          @bDeny  = max(cast(WSEC_DENY   as tinyint)),
          @bAccess= max(cast(WSEC_ACCESS as tinyint))
     from MSP_WEB_SECURITY_SP_CAT_RELATIONS   SCR, 
          MSP_WEB_SECURITY_SP_CAT_PERMISSIONS SCP
    where SCR.WSEC_REL_ID=SCP.WSEC_REL_ID and SCR.WSEC_CAT_ID=0
      and SCP.WSEC_FEA_ACT_ID=@act_id
      and SCR.WSEC_SP_GUID in
          ( select WSEC_GRP_GUID 
              from MSP_WEB_SECURITY_GROUP_MEMBERS
             where WRES_GUID=@sp_guid )
           
   if (@@rowcount = 1) AND (@bAccess = 1) AND (@bDeny = 0) AND (@bAllow = 1)
     set @fReturn = 1

ExitFunc:
   RETURN @fReturn

END
GO

GRANT EXECUTE ON dbo.MSP_WEB_FN_SEC_CheckSPGlobalPermission TO MSProjectServerRole
GO

/*----------------------------------------------------------*/
/* Check if a resource is the manager of a given Project    */
/*----------------------------------------------------------*/
CREATE FUNCTION dbo.MSP_WEB_FN_SEC_CheckResIsManagerOfProject(
   @res_id   int,
   @proj_id  int
)
RETURNS tinyint
AS
BEGIN
  -- Check for MSP_WEB_PROJECTS table, excluding Non-working Time and Task List --
  if (EXISTS(select * from MSP_WEB_PROJECTS where WRES_ID=@res_id and WPROJ_ID=@proj_id and WPROJ_IS_NONWORKING=0 and WPROJ_TYPE<>3))
  begin
    return 1
  end

  -- Otherwise check for MSP_WEB_ASSIGNMENTS table --
  if (EXISTS(select * from MSP_WEB_ASSIGNMENTS WA, MSP_WEB_PROJECTS WP 
			  where WA.WRES_ID_MGR=@res_id and WA.WPROJ_ID=@proj_id 
			    and WA.WPROJ_ID=WP.WPROJ_ID and WP.WPROJ_IS_NONWORKING=0 and WP.WPROJ_TYPE<>3))
  begin
    return 1
  end

  -- Otherwise, the res is not a manager of the project given --
  return 0    
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_FN_SEC_CheckResIsManagerOfProject TO MSProjectServerRole
GO

/*----------------------------------------------------------*/
/* Check if a resource is assigned to a given Project       */
/*----------------------------------------------------------*/
CREATE FUNCTION dbo.MSP_WEB_FN_SEC_CheckResIsMemberOfProject(
   @res_id   int,
   @proj_id  int
)
RETURNS tinyint
AS
BEGIN
  declare @fIsMember as tinyint

  select @fIsMember = count(*)
    from MSP_WEB_ASSIGNMENTS A, 
         MSP_WEB_PROJECTS P
   where A.WRES_ID=@res_id
     and A.WPROJ_ID=@proj_id and A.WPROJ_ID=P.WPROJ_ID
     and P.WPROJ_IS_NONWORKING=0 and P.WPROJ_TYPE<>3

  return @fIsMember
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_FN_SEC_CheckResIsMemberOfProject TO MSProjectServerRole
GO

/*----------------------------------------------------------*/
/* Check if a given Project is included in a given Category */
/*----------------------------------------------------------*/
CREATE FUNCTION dbo.MSP_WEB_FN_SEC_CheckProjectInCategory(
   @cat_id   int,
   @proj_id  int,
   @sp_guid  uniqueidentifier
)
RETURNS tinyint
AS
BEGIN
  declare @res_id  int
  declare @ruleid  int
  declare @fResult tinyint
  declare @fRet    tinyint

  /*-- initialize return value as false --*/
  set @fRet = 0

  /*-- Check MSP_WEB_SECURITY_CATEGORY_OBJECTS first --*/
  select @fRet = count(*) from MSP_WEB_SECURITY_CATEGORY_OBJECTS
   where WSEC_CAT_ID=@cat_id and WSEC_OBJ_TYPE=1 
     and WSEC_OBJ_ID=@proj_id

  if (@fRet<>0)
  begin
    set @fRet = 1
    goto ExitProc
  end

  -- Get the Resource's ID
  set @res_id = 0
  select @res_id=WRES_ID from MSP_WEB_RESOURCES where WRES_GUID=@sp_guid

  --
  -- if not found in MSP_WEB_SECURITY_CATEGORY_OBJECTS, 
  -- then check MSP_WEB_CATEGORY_RULES
  --
  DECLARE sql_cursor CURSOR FOR
  select WSEC_OBJ_RULE_TYPE
    from MSP_WEB_SECURITY_CATEGORY_RULES
   where WSEC_CAT_ID=@cat_id and WSEC_OBJ_TYPE=1
   order by WSEC_OBJ_RULE_TYPE

  OPEN sql_cursor
  FETCH NEXT FROM sql_cursor INTO @ruleid
  WHILE (@@FETCH_STATUS = 0)
  BEGIN
    -- 0: all current and future projects
    if (@ruleid = 0)
    begin 
      set @fRet = 1
      break
    end

    -- 1: only projects in the list
    -- if (@ruleid = 1) do nothing. Continue to check other rules.

    -- 2: all current and future projects I manage
    if (@ruleid = 2) AND (@res_id <> 0)
    begin
      -- check if sp_guid is the manager of this project
      set @fResult = dbo.MSP_WEB_FN_SEC_CheckResIsManagerOfProject(@res_id, @proj_id)
      if (@fResult<>0)
      begin
        set @fRet = 1
        break
      end
    end

    -- 3 all current and future projects I am assigned to
    if (@ruleid = 3) AND (@res_id <> 0)
    begin
      -- check if sp_guid is assigned in this project
      set @fResult = dbo.MSP_WEB_FN_SEC_CheckResIsMemberOfProject(@res_id, @proj_id)
      if (@fResult <>0)
      begin
        set @fRet = 1
        break
      end         
    end

    FETCH NEXT FROM sql_cursor INTO @ruleid
  END
  CLOSE sql_cursor
  DEALLOCATE sql_cursor

ExitProc:
  return @fRet
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_FN_SEC_CheckProjectInCategory TO MSProjectServerRole
GO


/*
 * VIEW: all Security Priciples (SP): users and groups
 */
CREATE VIEW dbo.MSP_WEB_VW_SEC_ALLSP
AS
  ( select WRES_ID          as WSEC_SP_ID,
           WRES_GUID        as WSEC_SP_GUID, 
           RES_NAME         as WSEC_SP_NAME, 
           WRES_IS_ENABLED  as WSEC_SP_ENABLED 
      from MSP_WEB_RESOURCES 
     where WRES_CAN_LOGIN = 1 
       and WRES_COUNT_LICENSE = 1
  )
  UNION 
  ( select - WSEC_GRP_ID    as WSEC_SP_ID,
           WSEC_GRP_GUID    as WSEC_SP_GUID, 
           WSEC_GRP_NAME    as WSEC_SP_NAME, 
           1                as WSEC_SP_ENABLED
      from MSP_WEB_SECURITY_GROUPS
  )
GO

GRANT SELECT ON dbo.MSP_WEB_VW_SEC_ALLSP  TO MSProjectServerRole
GO


/* Query #66038 */
/*----------------------------------------------------*/
/* Delete all the security infomation for a resource. */
/* This is called when merge account.                 */
/*----------------------------------------------------*/
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_DeleteResSecurityInfo
  @p0 INT
AS
BEGIN
  declare @resGUID as uniqueidentifier

  select @resGUID=WRES_GUID from MSP_WEB_RESOURCES where WRES_ID=@p0
  if (@@rowcount=0)  RETURN

  delete from MSP_WEB_SECURITY_GROUP_MEMBERS where WRES_GUID=@resGUID
  delete from MSP_WEB_SECURITY_SP_CAT_PERMISSIONS where WSEC_REL_ID in (select WSEC_REL_ID from MSP_WEB_SECURITY_SP_CAT_RELATIONS where WSEC_SP_GUID=@resGUID)
  delete from MSP_WEB_SECURITY_SP_CAT_RELATIONS where WSEC_SP_GUID=@resGUID
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_DeleteResSecurityInfo TO MSProjectServerRole
GO


/* Query #66040 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_CheckResInSecGroupByGrpID
  @p0  uniqueidentifier,
  @p1  INT
AS
BEGIN
  select GM.WSEC_GRP_GUID
    from MSP_WEB_SECURITY_GROUP_MEMBERS GM, MSP_WEB_SECURITY_GROUPS G
   where G.WSEC_GRP_ID = @p1 
    and G.WSEC_GRP_GUID=GM.WSEC_GRP_GUID
    and GM.WRES_GUID = @p0

  RETURN
END
GO

GRANT EXEC on dbo.MSP_WEB_SP_SEC_CheckResInSecGroupByGrpID to MSProjectServerRole
GO


/* Query #66042 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetEnterpriseResIDsFromWResIDs
  @p0  NTEXT
AS
BEGIN
  select RES_EUID 
    from MSP_WEB_RESOURCES 
   where WRES_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))
     and RES_EUID is not NULL
  RETURN
END
GO

GRANT EXEC on dbo.MSP_WEB_SP_QRY_GetEnterpriseResIDsFromWResIDs to MSProjectServerRole
GO


/* Query #66043 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_GetEnterpriseProjIDsFromWProjIDs
  @p0  NTEXT
AS
BEGIN
  select PROJ_ID 
    from MSP_WEB_PROJECTS 
   where WPROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p0))
     and PROJ_ID is not NULL
  RETURN
END
GO

GRANT EXEC on dbo.MSP_WEB_SP_QRY_GetEnterpriseProjIDsFromWProjIDs to MSProjectServerRole
GO


/* Query #66044 */
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_MergeResourcesInfoForEOrDResID
   @p0 INT,
   @p1 INT
AS
  ------- Delete Records for the Src Resource -------
  -- Delete Non-working work for the src resource --
  DELETE From MSP_WEB_WORK Where WRES_ID=@p0 and WASSN_ID in (Select WASSN_ID From MSP_WEB_ASSIGNMENTS Where WRES_ID = @p0 and WNWRK_ID>0)

  -- Delete Non-working assignments for the src resource --
  DELETE From MSP_WEB_ASSIGNMENTS Where WRES_ID=@p0 and WNWRK_ID>0

  -- Delete disabled/deleted status request for the src resource --
  DELETE From MSP_WEB_STATUS_REQUESTS Where WRES_ID_RECEIVER=@p0 and WREQ_IS_ENABLED=0

  ------- Merger Src Resource's data to Dest Resource  -------
  -- Merge Assignments --
  UPDATE MSP_WEB_ASSIGNMENTS SET WRES_ID = @p1          where WRES_ID = @p0
  UPDATE MSP_WEB_ASSIGNMENTS SET WRES_ID_MGR = @p1      where WRES_ID_MGR = @p0
  UPDATE MSP_WEB_ASSIGNMENTS SET WRES_ID_TEAM_LEAD=@p1  where WRES_ID_TEAM_LEAD=@p0

  -- Merge Messages --
  UPDATE MSP_WEB_MESSAGES SET WRES_ID_RECEIVER = @p1  where WRES_ID_RECEIVER = @p0
  UPDATE MSP_WEB_MESSAGES SET WRES_ID_SENDER = @p1    where WRES_ID_SENDER = @p0

  -- Merge Transactions --
  UPDATE MSP_WEB_TRANSACTIONS SET WRES_ID_TRANS_SENDER = @p1 where WRES_ID_TRANS_SENDER = @p0

  -- Merge Work --   
  UPDATE MSP_WEB_WORK SET WRES_ID = @p1 where WRES_ID = @p0

  -- Merge Projects --
  UPDATE MSP_WEB_PROJECTS SET WRES_ID = @p1 where WRES_ID = @p0

  -- Merge Status Reports -- 
  UPDATE MSP_WEB_STATUS_REQUESTS      SET WRES_ID_RECEIVER = @p1  where WRES_ID_RECEIVER = @p0
  UPDATE MSP_WEB_STATUS_REPORTS       SET WRES_ID_MGR = @p1       where WRES_ID_MGR = @p0 and WREPORT_IS_ENABLED <> 0
  UPDATE MSP_WEB_STATUS_RESPONSES     SET WRES_ID = @p1           where WRES_ID = @p0
  UPDATE MSP_WEB_STATUS_DISTRIBUTION  SET WRES_ID_DISTR_RECIP=@p1 where  WRES_ID_DISTR_RECIP=@p0

  -- Merge Delegations --
  UPDATE MSP_WEB_DELEGATIONS SET WRES_ID_DELEGATEE=@p1  where WRES_ID_DELEGATEE=@p0
  UPDATE MSP_WEB_DELEGATIONS SET WRES_ID_DELEGATOR =@p1 where WRES_ID_DELEGATOR =@p0

  -- Merge Mgr Rules --
  UPDATE MSP_WEB_MGR_RULES        SET WRES_ID_MGR=@p1 where WRES_ID_MGR=@p0
  UPDATE MSP_WEB_MGR_RULES_LISTS  SET ITEM_ID=@p1     where (ITEM_TYPE=1 or ITEM_TYPE=2) and ITEM_ID=@p0

  -------------------------------------------------------------
  -- Finally, Delete the src resource from MSP_WEB_RESOURCES --
  -------------------------------------------------------------
  DELETE From MSP_WEB_RESOURCES Where WRES_ID = @p0

RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_MergeResourcesInfoForEOrDResID TO MSProjectServerRole
GO

/* Query #66045 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetGroupsForResByResID
   @p0 INT
AS
  select GP.WSEC_GRP_GUID,
         GP.WSEC_GRP_NAME
    from MSP_WEB_RESOURCES R,
         MSP_WEB_SECURITY_GROUP_MEMBERS GM,
         MSP_WEB_SECURITY_GROUPS GP
   where R.WRES_ID=@p0
     and R.WRES_GUID=GM.WRES_GUID
     and GM.WSEC_GRP_GUID=GP.WSEC_GRP_GUID
   order by GP.WSEC_GRP_NAME
RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetGroupsForResByResID TO MSProjectServerRole
GO



/* Query #66049 */
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetAllEntUsersOBName
AS
Select WRES_ID, RES_EUID, WRES_GUID, RES_NAME, WRES_NT_ACCOUNT from MSP_WEB_RESOURCES where (NOT (WRES_IS_ENABLED=0 and WRES_CAN_LOGIN=0 and WRES_COUNT_LICENSE=0 and RES_EUID IS NULL)) AND WRES_ID <> 1 order by RES_NAME RETURN
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetAllEntUsersOBName TO MSProjectServerRole
GO



/* Query #66050 */
CREATE PROCEDURE dbo.MSP_WEB_SP_CheckUserInGroupByGUID
  @p0  uniqueidentifier,
  @p1  uniqueidentifier
AS
SELECT * FROM MSP_WEB_SECURITY_GROUP_MEMBERS WHERE WSEC_GRP_GUID=@p0 and WRES_GUID=@p1 RETURN
GO

GRANT EXEC on dbo.MSP_WEB_SP_CheckUserInGroupByGUID to MSProjectServerRole
GO


/*-- Used by NPE --*/
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_SetNPELastRunTime
  @p0  DATETIME
AS
BEGIN
  Update MSP_WEB_ADMIN set WADMIN_NPE_LAST_RUN=@p0
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_SetNPELastRunTime TO MSProjectServerRole
GO


/*-- Used by NPE --*/
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_SetNPENextRunTime
  @p0	DATETIME
AS
BEGIN
  Update MSP_WEB_ADMIN set WADMIN_NPE_NEXT_RUN=@p0
END
GO

GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_SetNPENextRunTime TO MSProjectServerRole
GO


/*****************************************************************************/
/*--                                                                       --*/
/*-- Project Server admin/security object permission related SP/Functions  --*/
/*--                                                                       --*/
/*****************************************************************************/

-------------------------------------------------------------------------------
--
-- FUNCTION: MSP_WEB_FN_SEC_GetAllObjectsResCanViewByViewIDInfo
-- INPUTS:
-- @obj_type: Currently we have the following objects: 
--            (Check table MSP_WEB_SECURITY_OBJECT_TYPES)
--            1: Project; 2: Resource; 3: Views; 4:Models
-- @view_id: this now only applies to Project and Resource.
--            For other object type, caller should use -1.
--
-- This function supports up to 10 different rules (0-9), and assuming that :
-- . Rule 0 is All currrent and future objects
-- . Rule 1 is list of objects within the category
-- Caller is responsible to translate the returned rule/cat info, according to the object type.
--
-- RETURNS:
-- WSEC_RULE_INFO : bit 0 --> Rule 0, Bit 1 --> Rule 1; ...
-- WSEC_CAT_ID: list of category that has list of projects defined within it.
--
-------------------------------------------------------------------------------
CREATE FUNCTION dbo.MSP_WEB_FN_SEC_GetAllObjectsResCanViewByViewIDInfo (
   @res_guid   uniqueidentifier,
   @fea_act_id int,
   @fAllow     int,
   @obj_type   int,
   @view_id    int
)
RETURNS @ret_obj_rule_info_tbl table (WSEC_RULE_INFO int, WSEC_CAT_ID int)
AS
BEGIN
  -- Due to the nature of Views, this function does not apply to Views.
  if (@obj_type = 3)  RETURN

  declare @cat_tbl table (WSEC_CAT_ID int)

  -- Get either all the allowed or denied categories for the user
  DECLARE sql_cursor_with_view CURSOR FOR
    select WSEC_CAT_ID, WSEC_OBJ_RULE_TYPE
      from MSP_WEB_SECURITY_CATEGORY_RULES
     where WSEC_OBJ_TYPE = @obj_type
       and WSEC_CAT_ID in (
             select SCR.WSEC_CAT_ID
               from ((MSP_WEB_SECURITY_CATEGORY_OBJECTS CO INNER JOIN MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR ON CO.WSEC_CAT_ID=SCR.WSEC_CAT_ID)
                    INNER JOIN MSP_WEB_SECURITY_SP_CAT_PERMISSIONS SCP ON SCR.WSEC_REL_ID=SCP.WSEC_REL_ID)
                    INNER JOIN MSP_WEB_SECURITY_GROUP_MEMBERS GM ON SCR.WSEC_SP_GUID = GM.WSEC_GRP_GUID
               where CO.WSEC_OBJ_TYPE=3  -- 3: View Type
                 and CO.WSEC_OBJ_ID=@view_id
                 and SCP.WSEC_FEA_ACT_ID=@fea_act_id 
                 and SCP.WSEC_ALLOW=@fAllow and SCP.WSEC_DENY<>@fAllow
                 and GM.WRES_GUID = @res_guid
           )

  DECLARE sql_cursor_no_view CURSOR FOR
    select WSEC_CAT_ID, WSEC_OBJ_RULE_TYPE
      from MSP_WEB_SECURITY_CATEGORY_RULES
     where WSEC_OBJ_TYPE = @obj_type
       and WSEC_CAT_ID in (
             select SCR.WSEC_CAT_ID
              from (MSP_WEB_SECURITY_SP_CAT_RELATIONS SCR INNER JOIN MSP_WEB_SECURITY_SP_CAT_PERMISSIONS SCP ON SCR.WSEC_REL_ID=SCP.WSEC_REL_ID)
                   INNER JOIN MSP_WEB_SECURITY_GROUP_MEMBERS GM ON SCR.WSEC_SP_GUID = GM.WSEC_GRP_GUID
             where SCP.WSEC_FEA_ACT_ID=@fea_act_id 
               and SCP.WSEC_ALLOW=@fAllow and WSEC_DENY<>@fAllow
               and GM.WRES_GUID = @res_guid
       )

  -- Set the right query depends on @view_id
  declare @sql_cursor cursor
  if (@view_id = -1)
    set @sql_cursor = sql_cursor_no_view
  else
    set @sql_cursor = sql_cursor_with_view

  declare @catid        int
  declare @ruleid       int
  declare @rule_info    int
  set @rule_info = 0

  OPEN @sql_cursor
  FETCH NEXT FROM @sql_cursor INTO @catid, @ruleid
  WHILE (@@FETCH_STATUS = 0)
  BEGIN
    -- Rule 0: all current and furture objects. break immediately.
    if (@ruleid = 0) 
    begin
      set @rule_info = @rule_info | 1
      BREAK
    end
    -- Rule 1: all objects in the list
    else if (@ruleid = 1)  
    begin
      set @rule_info = @rule_info | 2
      insert into @cat_tbl (WSEC_CAT_ID) values (@catid)
    end
    -- Rule 2:
    else if (@ruleid = 2)  
    begin
      set @rule_info = @rule_info | 4
    end
    -- Rule 3:
    else if (@ruleid = 3)  
    begin
      set @rule_info = @rule_info | 8
    end
    -- Rule 4:
    else if (@ruleid = 4)  
    begin
      set @rule_info = @rule_info | 16
    end
    -- Rule 5:
    else if (@ruleid = 5)  
    begin
      set @rule_info = @rule_info | 32
    end
    -- Rule 6:
    else if (@ruleid = 6)
    begin
      set @rule_info = @rule_info | 64
    end
    -- Rule 7:
    else if (@ruleid = 7)
    begin
      set @rule_info = @rule_info | 128
    end
    -- Rule 8 -- 31: We can support up to 32 rules for one object type. 
    -- We reserver the rule 0 -- 15 for ProjectServer
    -- Third party can creat custom rules 16 -- 31
    else if (@ruleid >= 8 AND @ruleid < 32)
    begin
      set @rule_info = @rule_info | POWER(2, @ruleid)
    end

    -- get next row
    FETCH NEXT FROM @sql_cursor INTO @catid, @ruleid
  END
  CLOSE @sql_cursor
  DEALLOCATE @sql_cursor

  -------------------------
  -- Check Project Rules --
  -------------------------
  if (@rule_info & 1 != 0) -- Rule 0: All
  begin
    insert into @ret_obj_rule_info_tbl (WSEC_RULE_INFO, WSEC_CAT_ID) values (1, 0)
    RETURN -- no need to get other info. return directly
  end

  --
  -- return the table result
  --
  if (@rule_info & 2 != 0) -- Rule 1: List
    insert into @ret_obj_rule_info_tbl (WSEC_RULE_INFO, WSEC_CAT_ID) (select @rule_info, WSEC_CAT_ID from @cat_tbl)
  else
    insert into @ret_obj_rule_info_tbl (WSEC_RULE_INFO, WSEC_CAT_ID) values (@rule_info, 0)

RETURN
END
GO
GRANT SELECT ON dbo.MSP_WEB_FN_SEC_GetAllObjectsResCanViewByViewIDInfo TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
-- 
-- FUNCTION: MSP_WEB_FN_SEC_GetResourcesManagedByResID
--
-- DESCRIPTION:
--   Get all the resources that are managed by a given resource.
--
-- INPUT:
--   @res_id       -- manager resource id
--   @fIncludeSelf -- flag.
--
-- NOTE:
--   This function is assuming that the Project Enterprise feature is on
--
-------------------------------------------------------------------------------
CREATE FUNCTION dbo.MSP_WEB_FN_SEC_GetResourcesManagedByResID (
  @res_id        int,
  @fIncludeSelf  int,
  @nMaxLevel     int
)
RETURNS @ret_res_tbl table (WRES_ID int)
AS
BEGIN
  declare @res_euid int
  declare @ent_res_global_proj_id int
  declare @ent_global_proj_id  int
  declare @ent_res_oc_uid int
  declare @ent_res_uid int

  set @res_euid = 0
  set @ent_res_global_proj_id = 0
  set @ent_global_proj_id = 0
  set @ent_res_oc_uid = 0
  set @ent_res_uid = 0

  -- Get RES_EUID and WRES_RBS_UID for the res_id
  select @res_euid=RES_EUID, @ent_res_oc_uid=WRES_RBS_UID from MSP_WEB_RESOURCES where WRES_ID=@res_id
  if (@res_euid = 0 or @ent_res_oc_uid = 0)  RETURN

  -- Get the Enterprise Resource Global Project ID
  select @ent_res_global_proj_id=PROJ_ID from MSP_PROJECTS where PROJ_TYPE=3  -- Enterprise Resource Global
  if (@ent_res_global_proj_id = 0)  RETURN

  -- Get the RES_UID for the resource (the RES_UID = the RES_EUID for resglobal always, so we basically
  -- are checking for its existence in the table)
  select @ent_res_uid=RES_UID from MSP_RESOURCES where RES_EUID = @res_euid and PROJ_ID = @ent_res_global_proj_id
  if (@ent_res_uid = 0)  return

  -- Get the Enterprise Global Project ID
  select @ent_global_proj_id=PROJ_ID from MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE) where PROJ_TYPE=2  -- Enterprise Global
  if (@ent_global_proj_id = 0)  RETURN
     
  --
  -- Get all the CODEs that are decendent of @res_oc_uid
  -- Only get those OC_CACHE_IS_VALID=1 (valid OC)
  -- 
  declare @all_oc_tbl   table (CODE_UID int)
  declare @temp1_oc_tbl table (CODE_UID int)
  declare @temp2_oc_tbl table (CODE_UID int)
  declare @cnt int, @numlevel int
  declare @fUseTemp1 tinyint

  if (@fIncludeSelf = 1)
    insert into @all_oc_tbl (CODE_UID) select @ent_res_oc_uid

  insert @temp1_oc_tbl (CODE_UID) select @ent_res_oc_uid

  set @cnt = 0
  set @numlevel = 0
  set @fUseTemp1 = 1
  if (@nMaxLevel < 0)  set @nMaxLevel = 5000 -- avoid infinite loop. Max: 5000 level RBS
  WHILE (@numlevel < @nMaxLevel)
  BEGIN
    IF (@fUseTemp1 = 1)
     begin
      insert into @temp2_oc_tbl (CODE_UID)
      (
        select CODE_UID
          from MSP_OUTLINE_CODES
         where PROJ_ID = @ent_global_proj_id
           and OC_PARENT in (
                 select CODE_UID from @temp1_oc_tbl
               )
      )
      
      select @cnt=COUNT(*) from @temp2_oc_tbl
      if (@cnt = 0) break

      insert into @all_oc_tbl (CODE_UID) select CODE_UID from @temp2_oc_tbl
      delete from @temp1_oc_tbl
      set @fUseTemp1 = 0
     end
    ELSE
     begin
      insert into @temp1_oc_tbl (CODE_UID)
      (
        select CODE_UID
          from MSP_OUTLINE_CODES
         where PROJ_ID = @ent_global_proj_id
           and OC_PARENT in (
                 select CODE_UID from @temp2_oc_tbl
               )
      )
      
      select @cnt=COUNT(*) from @temp1_oc_tbl
      if (@cnt = 0) break

      insert into @all_oc_tbl (CODE_UID) select CODE_UID from @temp1_oc_tbl
      delete from @temp2_oc_tbl
      set @fUseTemp1 = 1
     end

     -- go to next level
     set @numlevel = @numlevel + 1

  END -- end of WHILE()
      
  --
  -- Get all those enterprise resources whose OC are in the set.
  -- And then map to MSP_WEB_RESOURCES
  --
  INSERT INTO @ret_res_tbl (WRES_ID)
  (
    select WR.WRES_ID
      from MSP_RESOURCES ER,
           MSP_WEB_RESOURCES WR 
     where WR.WRES_RBS_UID in (select CODE_UID from @all_oc_tbl)
       and ER.PROJ_ID = @ent_res_global_proj_id
       and ER.RES_EUID = WR.RES_EUID
  )

RETURN
END
GO
GRANT SELECT ON dbo.MSP_WEB_FN_SEC_GetResourcesManagedByResID TO MSProjectServerRole
GO

-------------------------------------------------------------------------------
-- 
-- FUNCTION: MSP_WEB_FN_QRY_GetEntCustomField
--
-- DESCRIPTION:
--   Get the enterprise custom field information
--
-- INPUT:
--   @p0       -- a list of assignment ids
--
-------------------------------------------------------------------------------
CREATE FUNCTION dbo.MSP_WEB_FN_QRY_GetEntCustomField (
  @p0        ntext
)
RETURNS @EntCustField_tbl table (FIELD_ID int, FIELD_VALUE nvarchar(255), TRequired int)
AS
BEGIN
	declare @t1 table (FIELD_ID int)
	declare @t2 table (FIELD_ID int)
	declare @ProjID int

	select @ProjID = PROJ_ID from MSP_PROJECTS where PROJ_TYPE =2
	insert into @t1 
		Select distinct WWF.FIELD_ID 
		From dbo.MSP_WEB_FN_ConvertListToTable(@p0) LT INNER JOIN MSP_WEB_ASSIGNMENTS WA ON LT.TokenVal=WA.WASSN_ID 
		INNER JOIN MSP_WEB_WORKGROUP_FIELDS WWF ON WA.WASSN_ID=WWF.WASSN_ID 
		INNER JOIN MSP_FIELD_ATTRIBUTES FA ON (FA.ATTRIB_FIELD_ID = WWF.FIELD_ID AND FA.PROJ_ID=@ProjID AND FA.ATTRIB_ID = 217 AND FA.ATTRIB_VALUE =1 ) 
		WHERE (( WWF.FIELD_ID BETWEEN 188744279 AND 188744518) AND WWF.FIELD_ID NOT BETWEEN 188744419 AND 188744477)

	insert into @t2 
		select FIELD_ID 
		from @t1 T1 INNER JOIN MSP_FIELD_ATTRIBUTES FA ON (T1.FIELD_ID = FA.ATTRIB_FIELD_ID) 
		where (ATTRIB_ID=213 AND ATTRIB_VALUE= 1 AND PROJ_ID=@ProjID)
	insert into @EntCustField_tbl 
		select FA.ATTRIB_FIELD_ID as FIELD_ID, MAS.AS_VALUE as FIELD_VALUE, CASE WHEN (FA.ATTRIB_FIELD_ID in (select FIELD_ID from @t2) OR FA2.ATTRIB_ID IS NOT NULL) THEN 1 ELSE 0 END AS TRequired 
		from MSP_FIELD_ATTRIBUTES FA INNER JOIN @t1 T1 ON FA.ATTRIB_FIELD_ID = T1.FIELD_ID AND FA.PROJ_ID = @ProjID AND FA.ATTRIB_ID =210
		INNER JOIN MSP_ATTRIBUTE_STRINGS MAS ON (FA.AS_ID = MAS.AS_ID AND MAS.PROJ_ID =@ProjID) 
		LEFT  JOIN MSP_FIELD_ATTRIBUTES FA2 ON FA2.ATTRIB_FIELD_ID = T1.FIELD_ID AND FA2.PROJ_ID = @ProjID AND FA2.ATTRIB_ID =220		
		ORDER BY FA.ATTRIB_FIELD_ID 
RETURN
END
GO
GRANT SELECT ON dbo.MSP_WEB_FN_QRY_GetEntCustomField TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
-- 
-- FUNCTION: MSP_WEB_FN_QRY_GetEnterpriseOutlineCodesForFilter
--
-------------------------------------------------------------------------------
CREATE FUNCTION dbo.MSP_WEB_FN_QRY_GetEnterpriseOutlineCodesForFilter (
	@code_name	nvarchar(255),
	@filter     nvarchar(255)
)  
RETURNS @ret_code_tbl table (CODE_UID int)
AS
BEGIN 
	INSERT INTO @ret_code_tbl (CODE_UID)
	(
		SELECT MOC.CODE_UID
		FROM         
			dbo.MSP_WEB_VIEW_FIELDS WVF INNER JOIN
			dbo.MSP_FIELD_ATTRIBUTES MFA ON dbo.MSP_WEB_FN_ConvertERMVToEROC(WVF.WFIELD_ID) = MFA.ATTRIB_FIELD_ID INNER JOIN
			dbo.MSP_OUTLINE_CODES MOC ON MFA.ATTRIB_FIELD_ID = MOC.OC_FIELD_ID OR MFA.ATTRIB_VALUE = MOC.OC_FIELD_ID AND MFA.ATTRIB_ID = 212 INNER JOIN
			dbo.MSP_PROJECTS MP ON MOC.PROJ_ID = MP.PROJ_ID AND MFA.PROJ_ID = MP.PROJ_ID
		WHERE
			(MP.PROJ_TYPE = 2) AND 
			(MOC.OC_CACHED_FULL_NAME IS NOT NULL) AND 
			(MFA.ATTRIB_ID = 200 OR MFA.ATTRIB_ID = 212) AND
			(WVF.WFIELD_NAME_OLEDB = @code_name) AND 
			(MOC.OC_CACHED_FULL_NAME LIKE @filter)
	)
	RETURN
END
GO
GRANT SELECT ON dbo.MSP_WEB_FN_QRY_GetEnterpriseOutlineCodesForFilter TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
-- 
-- FUNCTION: MSP_WEB_FN_QRY_GetProjectIDsForEntProjectOutlineCodeFilter
--
-------------------------------------------------------------------------------
CREATE FUNCTION dbo.MSP_WEB_FN_QRY_GetProjectIDsForEntProjectOutlineCodeFilter (
	@field_id	int,
	@filter     nvarchar(255)
)  
RETURNS @ret_code_tbl table (WASSN_ID int)
AS
BEGIN 
	INSERT INTO @ret_code_tbl (WASSN_ID)
	(
		SELECT
		  MWF.WASSN_ID
		FROM
		  MSP_WEB_WORKGROUP_FIELDS MWF 
		  LEFT OUTER JOIN MSP_OUTLINE_CODES MOC ON MWF.INT_VAL = MOC.CODE_UID
		WHERE
		  MWF.FIELD_ID = @field_id
		AND
		  MOC.OC_CACHED_FULL_NAME LIKE @filter
	)
	RETURN
END
GO
GRANT SELECT ON dbo.MSP_WEB_FN_QRY_GetProjectIDsForEntProjectOutlineCodeFilter TO MSProjectServerRole
GO



-------------------------------------------------------------------------------
-- 
-- PROCEDURE: MSP_WEB_SP_SEC_GetResourcesManagedByResID
--
-- DESCRIPTION:
--   Wrapper SP of MSP_WEB_SP_SEC_GetResourcesManagedByResID, so that it can 
--   be exposed out to ADO.
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetResourcesManagedByResID
  @res_id        int,
  @fIncludeSelf  int
AS
BEGIN
  select distinct WRES_ID 
    from dbo.MSP_WEB_FN_SEC_GetResourcesManagedByResID (@res_id, @fIncludeSelf, -1)
   order by WRES_ID
RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetResourcesManagedByResID TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
--
-- FUNTION: MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID
--
-- DESCRIPTION:
--   eg. Get all the projects that the given resource have "SEE IN PROJECT CENTER"
--       permission, and can view in the given Portfolio view (@view_id)
--
--   if @view_id is -1, then get all the projects that a user has the given permission.
--
-------------------------------------------------------------------------------
CREATE FUNCTION dbo.MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID (
   @res_id     int,
   @fea_act_id int,
   @view_id    int,
   @proj_option int  -- bit 0: projects, bit 1: todolist
)
RETURNS @ret_proj_tbl table (WPROJ_ID int)
AS
BEGIN
  declare @deny_proj_tbl table  (WPROJ_ID int)
  declare @allow_proj_tbl table (WPROJ_ID int)

  -- Get the WRES_GUID for the resource
  declare @res_guid uniqueidentifier
  select @res_guid=WRES_GUID from MSP_WEB_RESOURCES where WRES_ID=@res_id
  if (@res_guid is null)  RETURN

  If (@proj_option & 1 != 0)
  Begin
    declare @proj_allow_info_tbl table (WSEC_RULE_INFO int, WSEC_CAT_ID int)
    declare @proj_deny_info_tbl  table (WSEC_RULE_INFO int, WSEC_CAT_ID int)

    -- Get the ALLOW rule/cat_list info cache table
    insert into @proj_allow_info_tbl (WSEC_RULE_INFO, WSEC_CAT_ID) (
      select WSEC_RULE_INFO, WSEC_CAT_ID
       from dbo.MSP_WEB_FN_SEC_GetAllObjectsResCanViewByViewIDInfo(@res_guid, @fea_act_id, 1, 1, @view_id)
    )

    -- Get the DENY rule/cat_list info into local cache table
    insert into @proj_deny_info_tbl (WSEC_RULE_INFO, WSEC_CAT_ID) (
      select WSEC_RULE_INFO, WSEC_CAT_ID
       from dbo.MSP_WEB_FN_SEC_GetAllObjectsResCanViewByViewIDInfo(@res_guid, @fea_act_id, 0, 1, @view_id)
    )

    --
    -- Get the ALLOW/DENY rule info
    --
    declare @allow_rule_info  int
    declare @deny_rule_info   int
    set @allow_rule_info = 0
    set @deny_rule_info = 0

    select TOP 1 @allow_rule_info=WSEC_RULE_INFO from @proj_allow_info_tbl
    select TOP 1 @deny_rule_info=WSEC_RULE_INFO from @proj_deny_info_tbl

    -------------------------------------------------
    -- Check the returned info, optimize the query
    -------------------------------------------------
    --
    -- Handling rule 0: all current and future projects
    --
    if (@deny_rule_info & 1 != 0) -- Deny ALL: no need for further operation
      goto ExitFunc

    if (@allow_rule_info = 0)  -- No records in @proj_allow_rule_info
      goto ExitFunc

    if (@allow_rule_info & 1 != 0) -- All ALL
    begin
      insert into @allow_proj_tbl (WPROJ_ID)
      (
        select WPROJ_ID from MSP_WEB_PROJECTS where WPROJ_IS_NONWORKING=0 and WPROJ_TYPE<>3
      )
    end

    --
    -- Handling rule 1: all projects in the list
    --
    if (@allow_rule_info & 2 != 0) AND (@allow_rule_info & 1 = 0)
    begin
      insert into @allow_proj_tbl (WPROJ_ID)
      (
        select WSEC_OBJ_ID as WPROJ_ID
          from MSP_WEB_SECURITY_CATEGORY_OBJECTS
          where WSEC_OBJ_TYPE=1
            and WSEC_CAT_ID in (select WSEC_CAT_ID from @proj_allow_info_tbl)
      )
    end

    if (@deny_rule_info & 2 != 0)
    begin
      insert into @deny_proj_tbl (WPROJ_ID)
      (
        select WSEC_OBJ_ID as WPROJ_ID
          from MSP_WEB_SECURITY_CATEGORY_OBJECTS
          where WSEC_OBJ_TYPE=1
            and WSEC_CAT_ID in (select WSEC_CAT_ID from @proj_deny_info_tbl)
      )
    end

    --
    -- Handling rule 2: all current and future projects I manage
    --
    IF (@deny_rule_info & 4 != 0)
     begin
      insert into @deny_proj_tbl (WPROJ_ID)
      (
        ( select WPROJ_ID
            from MSP_WEB_PROJECTS
           where WRES_ID=@res_id
             and WPROJ_IS_NONWORKING=0
             and WPROJ_TYPE<>3
        )
        UNION
        (
          select WA.WPROJ_ID
            from MSP_WEB_ASSIGNMENTS WA,
                 MSP_WEB_PROJECTS WP
           where WA.WRES_ID_MGR=@res_id
             and WA.WPROJ_ID=WP.WPROJ_ID
             and WP.WPROJ_IS_NONWORKING=0
             and WP.WPROJ_TYPE<>3
        )
      )
     end
    ELSE IF (@allow_rule_info & 4 != 0) AND (@allow_rule_info & 1 = 0)
     begin
      insert into @allow_proj_tbl (WPROJ_ID)
      (
        ( select WPROJ_ID
            from MSP_WEB_PROJECTS
           where WRES_ID=@res_id
             and WPROJ_IS_NONWORKING=0
             and WPROJ_TYPE<>3
        )
        UNION
        (
          select WA.WPROJ_ID
            from MSP_WEB_ASSIGNMENTS WA,
                 MSP_WEB_PROJECTS WP
           where WA.WRES_ID_MGR=@res_id
             and WA.WPROJ_ID=WP.WPROJ_ID
             and WP.WPROJ_IS_NONWORKING=0
             and WP.WPROJ_TYPE<>3
        )
      )
     end

    --
    -- Handling rule 3: all current and future projects I am assigned to
    --
    IF (@deny_rule_info & 8 != 0)
     begin
      insert into @deny_proj_tbl (WPROJ_ID)
      (
        (
          select A.WPROJ_ID
            from MSP_WEB_ASSIGNMENTS A,
                 MSP_WEB_PROJECTS P
           where A.WRES_ID=@res_id
             and A.WPROJ_ID=P.WPROJ_ID
             and P.WPROJ_IS_NONWORKING=0
             and P.WPROJ_TYPE<>3
        )
        UNION
        (
          select WP.WPROJ_ID
            from MSP_RESOURCES ER INNER JOIN MSP_WEB_RESOURCES WR ON (WR.WRES_ID=@res_id and WR.RES_EUID=ER.RES_EUID)
                 INNER JOIN MSP_WEB_PROJECTS WP ON (ER.PROJ_ID=WP.PROJ_ID)
        )
      )
     end
    ELSE IF (@allow_rule_info & 8 != 0) AND (@allow_rule_info & 1 = 0)
     begin
      insert into @allow_proj_tbl (WPROJ_ID)
      (
        (
          select A.WPROJ_ID
            from MSP_WEB_ASSIGNMENTS A,
                 MSP_WEB_PROJECTS P
           where A.WRES_ID=@res_id
             and A.WPROJ_ID=P.WPROJ_ID
             and P.WPROJ_IS_NONWORKING=0
             and P.WPROJ_TYPE<>3
        )
        UNION
        (
          select WP.WPROJ_ID
            from MSP_RESOURCES ER INNER JOIN MSP_WEB_RESOURCES WR ON (WR.WRES_ID=@res_id and WR.RES_EUID=ER.RES_EUID)
                 INNER JOIN MSP_WEB_PROJECTS WP ON (ER.PROJ_ID=WP.PROJ_ID)
        )
      )
     end

    -- Get the enterprise info
    declare @fEnt int
    set @fEnt = 0
    select @fEnt=WADMIN_ENABLE_ENTERPRISE from MSP_WEB_ADMIN
    IF (@fEnt = 1)
    BEGIN
      -- cache the my resources, so we don't have to calc it twice
      declare @myres_tbl table (WRES_ID int)
      IF ((@deny_rule_info & 16 != 0) OR ((@allow_rule_info & 16 != 0) AND (@allow_rule_info & 1 = 0)))
         OR
         ((@deny_rule_info & 32 != 0) OR ((@allow_rule_info & 32 != 0) AND (@allow_rule_info & 1 = 0)))
      begin
        insert into @myres_tbl (WRES_ID)
        (
          select WRES_ID from dbo.MSP_WEB_FN_SEC_GetResourcesManagedByResID(@res_id, 0, -1) -- 0: not including the resource himself.
        )
      end

      if (EXISTS(select TOP 1 WRES_ID from @myres_tbl))
      BEGIN
        --
        -- Handling rule 4: all current and future projects managed by resources that I manage (Enterprise)
        -- 
        IF (@deny_rule_info & 16 != 0)
         begin
           insert into @deny_proj_tbl (WPROJ_ID)
           (
             ( select WPROJ_ID
                 from MSP_WEB_PROJECTS
                where WPROJ_IS_NONWORKING=0
                  and WPROJ_TYPE<>3
                  and WRES_ID in (select WRES_ID from @myres_tbl)
             )
             UNION
             (
               select WA.WPROJ_ID
                 from MSP_WEB_ASSIGNMENTS WA,
                      MSP_WEB_PROJECTS WP
                where WA.WPROJ_ID=WP.WPROJ_ID
                  and WP.WPROJ_IS_NONWORKING=0
                  and WP.WPROJ_TYPE<>3
                  and WA.WRES_ID_MGR in (select WRES_ID from @myres_tbl)
             )
           )
         end
        ELSE IF (@allow_rule_info & 16 != 0) AND (@allow_rule_info & 1 = 0)
         begin
           insert into @allow_proj_tbl (WPROJ_ID)
           (
             ( select WPROJ_ID
                 from MSP_WEB_PROJECTS
                where WPROJ_IS_NONWORKING=0
                  and WPROJ_TYPE<>3
                  and WRES_ID in (select WRES_ID from @myres_tbl)
             )
             UNION
             (
               select WA.WPROJ_ID
                 from MSP_WEB_ASSIGNMENTS WA,
                      MSP_WEB_PROJECTS WP
                where WA.WPROJ_ID=WP.WPROJ_ID
                  and WP.WPROJ_IS_NONWORKING=0
                  and WP.WPROJ_TYPE<>3
                  and WA.WRES_ID_MGR in (select WRES_ID from @myres_tbl)
             )
           )
         end

        --
        -- Handling rule 5: all current and future projects assigned to resources that I manage (Enterprise)
        -- 
        IF (@deny_rule_info & 32 != 0)
         begin
          insert into @deny_proj_tbl (WPROJ_ID)
          (
            (
              select A.WPROJ_ID
                from MSP_WEB_ASSIGNMENTS A,
                     MSP_WEB_PROJECTS P
               where A.WPROJ_ID=P.WPROJ_ID
                 and P.WPROJ_IS_NONWORKING=0
                 and P.WPROJ_TYPE<>3
                 and A.WRES_ID in (select WRES_ID from @myres_tbl)
            )
            UNION
            (
              select WP.WPROJ_ID 
                from MSP_WEB_PROJECTS WP,
                     MSP_WEB_RESOURCES WR,
                     MSP_RESOURCES ER
               where ER.PROJ_ID=WP.PROJ_ID
                 and WR.RES_EUID=ER.RES_EUID
                 and WR.WRES_ID in (select WRES_ID from @myres_tbl)
            )
          )
         end
        ELSE IF (@allow_rule_info & 32 != 0) AND (@allow_rule_info & 1 = 0)
         begin
          insert into @allow_proj_tbl (WPROJ_ID)
          (
            (
              select A.WPROJ_ID
                from MSP_WEB_ASSIGNMENTS A,
                     MSP_WEB_PROJECTS P
               where A.WPROJ_ID=P.WPROJ_ID
                 and P.WPROJ_IS_NONWORKING=0
                 and P.WPROJ_TYPE<>3
                 and A.WRES_ID in (select WRES_ID from @myres_tbl)
            )
            UNION
            (
              select WP.WPROJ_ID 
                from MSP_WEB_PROJECTS WP,
                     MSP_WEB_RESOURCES WR,
                     MSP_RESOURCES ER
               where ER.PROJ_ID=WP.PROJ_ID
                 and WR.RES_EUID=ER.RES_EUID
                 and WR.WRES_ID in (select WRES_ID from @myres_tbl)
            )
          )
         end
      END -- end of -- if (EXISTS(select TOP 1 WRES_ID from @myres_table)
    END

  End

ExitFunc:
  --
  -- Special handling for To-Do List.
  --
  IF (@proj_option & 2 != 0)
  BEGIN
    -- Task List rule 1 (All public task lists)
    INSERT INTO @allow_proj_tbl (WPROJ_ID)
    (
      Select WPROJ_ID From MSP_WEB_PROJECTS Where WPROJ_TYPE=3 and WPROJ_SCOPE=2
    )

    -- Task List rule 2 (All semi-public task lists that I have assignments)
    INSERT INTO @allow_proj_tbl (WPROJ_ID)
    (
      Select P.WPROJ_ID
        From MSP_WEB_PROJECTS P,
             MSP_WEB_ASSIGNMENTS A
       Where P.WPROJ_ID=A.WPROJ_ID
         and WPROJ_TYPE=3
         and WPROJ_SCOPE=1
         and A.WRES_ID=@res_id
    )

    -- Task List rule 3 (All my private task lists)
    INSERT INTO @allow_proj_tbl (WPROJ_ID)
    (
      Select WPROJ_ID From MSP_WEB_PROJECTS Where WRES_ID=@res_id and WPROJ_TYPE=3 and WPROJ_SCOPE<2
    )
  END

  ---------------------------------------------------------
  -- After taking care of rules. Generate the final list
  ---------------------------------------------------------
  INSERT INTO @ret_proj_tbl (WPROJ_ID)
  (
     select distinct WPROJ_ID
       from @allow_proj_tbl
      where WPROJ_ID not in 
            ( select distinct WPROJ_ID from @deny_proj_tbl )
  )

RETURN
END
GO
GRANT SELECT ON dbo.MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
--
-- PROCEDURE: MSP_WEB_SP_SEC_GetAllProjectsResCanViewByViewID
--
-- DESCRIPTION:
--   Wrapper SP for MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID,
--   so that it can be exposed out to ADO
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetAllProjectsResCanViewByViewID
   @res_id     int,
   @fea_act_id int,
   @view_id    int
AS
BEGIN
  select WPROJ_ID 
    from dbo.MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID(@res_id, @fea_act_id, @view_id, 3) -- 3: all projects and todolists
   order by WPROJ_ID
RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetAllProjectsResCanViewByViewID TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
--
-- PROCEDURE: MSP_WEB_SP_SEC_GetAllEntProjectsForResWithTwoPermissions
--
-- DESCRIPTION:
--   This stored procedure is used to speed up PDS ProjectStatus call.
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetAllEntProjectsForResWithTwoPermissions
   @res_id     int,
   @act_id1    int,
   @act_id2    int
AS
BEGIN
  (
   select distinct PROJ_ID 
     from MSP_WEB_PROJECTS P1,
          dbo.MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID(@res_id, @act_id1, -1, 1) P2
    where P1.WPROJ_ID = P2.WPROJ_ID and P1.PROJ_ID IS NOT NULL
  )
  UNION ALL ( select -1 as PROJ_ID )
  UNION ALL
  (
   select distinct PROJ_ID 
     from MSP_WEB_PROJECTS P3,
          dbo.MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID(@res_id, @act_id2, -1, 1) P4
    where P3.WPROJ_ID = P4.WPROJ_ID and P3.PROJ_ID IS NOT NULL
  )
RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetAllEntProjectsForResWithTwoPermissions TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
--
-- PROCEDURE: MSP_WEB_SP_SEC_CheckSPProjectPermission
--
-- DESCRIPTION:
--   Check if the given user has a certain permission on a given project,
--   including to-do list.
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_CheckSPProjectPermission
   @sp_guid  uniqueidentifier,
   @proj_id  int,
   @act_id   int,
   @fAllow   tinyint OUTPUT
AS
BEGIN
  declare @catid   int
  declare @fRet    tinyint

  /*-- initialize OUTPUT false --*/
  set @fAllow = 0

  /*-- check for Organization permission --*/
  set @fAllow = dbo.MSP_WEB_FN_SEC_CheckOrgPermission(@act_id)
  if (@fAllow = 0)   goto ExitProc
  set @fAllow = 0

  -- check input @sp_guid, and get WRES_ID
  declare @res_id int
  set @res_id = 0
  select @res_id=WRES_ID from MSP_WEB_RESOURCES where WRES_GUID=@sp_guid
  if (@res_id = 0)  goto ExitProc

  -- Check the existence of the project, also get the type
  -- if it is a TODO list, then we can optimize
  declare @proj_type int, @proj_option int
  set @proj_type = -1
  select @proj_type = WPROJ_TYPE from MSP_WEB_PROJECTS where WPROJ_ID = @proj_id and WPROJ_IS_NONWORKING=0
  if (@proj_type = -1)  goto ExitProc

  if (@proj_type = 3) -- todolist
    set @proj_option = 2
  else
    set @proj_option = 1

  -- check if the proj id is in the projects that the resource has the permission
  if (EXISTS(select WPROJ_ID
               from MSP_WEB_PROJECTS
              where WPROJ_ID = @proj_id
                and WPROJ_ID in (
                      select WPROJ_ID
                        from dbo.MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID(@res_id, @act_id, -1, @proj_option)
                    )))
  begin
    set @fAllow = 1
  end

ExitProc:
  select 'WSEC_ALLOW'=@fAllow
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_CheckSPProjectPermission TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
--
-- FUNCTION: MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID 
--
-- DESCRIPTION:
--   eg. Get all the resources that the given user have "SEE RESOURCES ASSIGNMENT VIEW"
--       permission, and can view in the given assignment view (@view_id)
--
--   if @view_id is -1, then get all the resources that a user has the given permission.
--
-------------------------------------------------------------------------------
CREATE FUNCTION dbo.MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID (
   @res_id     int,
   @fea_act_id int,
   @view_id    int
)
RETURNS @ret_res_tbl table (WRES_ID int)
AS
BEGIN
  -- Get the WRES_GUID for the resource
  declare @res_guid uniqueidentifier
  select @res_guid=WRES_GUID from MSP_WEB_RESOURCES where WRES_ID=@res_id
  if (@res_guid is null)  RETURN

  declare @res_allow_info_tbl table (WSEC_RULE_INFO int, WSEC_CAT_ID int)
  declare @res_deny_info_tbl  table (WSEC_RULE_INFO int, WSEC_CAT_ID int)

  -- Get the ALLOW rule/cat_list info cache table
  insert into @res_allow_info_tbl (WSEC_RULE_INFO, WSEC_CAT_ID) (
    select WSEC_RULE_INFO, WSEC_CAT_ID
     from dbo.MSP_WEB_FN_SEC_GetAllObjectsResCanViewByViewIDInfo(@res_guid, @fea_act_id, 1, 2, @view_id)
  )

  -- Get the DENY rule/cat_list info into local cache table
  insert into @res_deny_info_tbl (WSEC_RULE_INFO, WSEC_CAT_ID) (
    select WSEC_RULE_INFO, WSEC_CAT_ID
     from dbo.MSP_WEB_FN_SEC_GetAllObjectsResCanViewByViewIDInfo(@res_guid, @fea_act_id, 0, 2, @view_id)
  )

  --
  -- Get the ALLOW/DENY rule info
  --
  declare @allow_rule_info  int
  declare @deny_rule_info   int
  set @allow_rule_info = 0
  set @deny_rule_info = 0

  select TOP 1 @allow_rule_info=WSEC_RULE_INFO from @res_allow_info_tbl
  select TOP 1 @deny_rule_info=WSEC_RULE_INFO from @res_deny_info_tbl

  declare @deny_res_tbl table  (WRES_ID int)
  declare @allow_res_tbl table (WRES_ID int)

  -------------------------------------------------
  -- Check the returned info, optimize the query
  -------------------------------------------------
  --
  -- Handling rule 0: all current and future resources
  --
  if (@deny_rule_info & 1 != 0) -- Deny ALL: no need for further operation
    RETURN

  if (@allow_rule_info = 0)  -- No infomation in @proj_allow_rule_info
    RETURN

  if (@allow_rule_info & 1 != 0) -- Allow: all resources
  begin
    insert into @allow_res_tbl (WRES_ID)
    (
      select WRES_ID from MSP_WEB_RESOURCES
    )
  end

  --
  -- Handling rule 1: All resources in the list
  --
  if (@allow_rule_info & 2 != 0) AND (@allow_rule_info & 1 = 0)
  begin
    insert into @allow_res_tbl (WRES_ID)
    (
      select distinct WSEC_OBJ_ID as WRES_ID
        from MSP_WEB_SECURITY_CATEGORY_OBJECTS
        where WSEC_OBJ_TYPE=2 -- Resource
          and WSEC_CAT_ID in (select WSEC_CAT_ID from @res_allow_info_tbl)
    )
  end

  if (@deny_rule_info & 2 != 0)
  begin
    insert into @deny_res_tbl (WRES_ID)
    (
      select distinct WSEC_OBJ_ID as WRES_ID
        from MSP_WEB_SECURITY_CATEGORY_OBJECTS
        where WSEC_OBJ_TYPE=2 -- Resources
          and WSEC_CAT_ID in (select WSEC_CAT_ID from @res_deny_info_tbl)
    )
  end

  --
  -- Handling rule 2: Resource himself/herself
  --
  IF (@deny_rule_info & 4 != 0)
   begin
    insert into @deny_res_tbl (WRES_ID)
    (
      select @res_id
    )
   end
  ELSE IF (@allow_rule_info & 4 != 0) AND (@allow_rule_info & 1 = 0)
   begin
    insert into @allow_res_tbl (WRES_ID)
    (
      select @res_id
    )
   end

  --
  -- Handling rule 3: Resources that I assign task to ( I am a project manager)
  -- 
  IF (@deny_rule_info & 8 != 0)
   begin
    insert into @deny_res_tbl (WRES_ID)
    (
      (
        select distinct WRES_ID from MSP_WEB_ASSIGNMENTS where WRES_ID_MGR=@res_id and WRES_ID<>-1
      )
      UNION
      (
        select distinct WR.WRES_ID
          from MSP_WEB_PROJECTS WP INNER JOIN MSP_RESOURCES ER ON (WP.PROJ_ID=ER.PROJ_ID and ER.RES_EUID IS NOT NULL)
               INNER JOIN MSP_WEB_RESOURCES WR ON (ER.RES_EUID=WR.RES_EUID)
         where WP.WRES_ID=@res_id or WP.WPROJ_ID in (
                 select WP2.WPROJ_ID 
                   from MSP_WEB_PROJECTS WP2 INNER JOIN MSP_WEB_ASSIGNMENTS WA on WA.WPROJ_ID=WP2.WPROJ_ID
                  where WA.WRES_ID_MGR=@res_id
               )
      )
    )
   end
  ELSE IF (@allow_rule_info & 8 != 0) AND (@allow_rule_info & 1 = 0)
   begin
    insert into @allow_res_tbl (WRES_ID)
    (
      (
        select distinct WRES_ID from MSP_WEB_ASSIGNMENTS where WRES_ID_MGR=@res_id and WRES_ID<>-1
      )
      UNION
      (
        select distinct WR.WRES_ID
          from MSP_WEB_PROJECTS WP INNER JOIN MSP_RESOURCES ER ON (WP.PROJ_ID=ER.PROJ_ID and ER.RES_EUID IS NOT NULL)
               INNER JOIN MSP_WEB_RESOURCES WR ON (ER.RES_EUID=WR.RES_EUID)
         where WP.WRES_ID=@res_id or WP.WPROJ_ID in (
                 select WP2.WPROJ_ID 
                   from MSP_WEB_PROJECTS WP2 INNER JOIN MSP_WEB_ASSIGNMENTS WA on WA.WPROJ_ID=WP2.WPROJ_ID
                  where WA.WRES_ID_MGR=@res_id
               )
      )
    )
   end

  -- Get the enterprise info
  declare @fEnt int
  set @fEnt = 0
  select @fEnt=WADMIN_ENABLE_ENTERPRISE from MSP_WEB_ADMIN
  IF (@fEnt = 1)
  BEGIN
    -- cache the my resources, so we don't have to calc it twice
    declare @myres_tbl table (WRES_ID int)
    declare @myres1_tbl table (WRES_ID int)
    IF ((@deny_rule_info & 16 != 0) OR ((@allow_rule_info & 16 != 0) AND (@allow_rule_info & 1 = 0)))
    begin
      insert into @myres_tbl (WRES_ID)
      (
        select WRES_ID from dbo.MSP_WEB_FN_SEC_GetResourcesManagedByResID(@res_id, 0, -1) -- 0: not including the resource himself.
      )
    end

    -- cache the my direct reports (which is a subset of my resources).
    -- Optimize according to the rule setting for "My Resources"
    IF ((@deny_rule_info & 32 != 0 AND @deny_rule_info & 16 = 0) OR 
        ((@allow_rule_info & 32 != 0) AND (@allow_rule_info & 16 = 0) AND (@allow_rule_info & 1 = 0)))
    begin
      insert into @myres1_tbl (WRES_ID)
      (
        select WRES_ID from dbo.MSP_WEB_FN_SEC_GetResourcesManagedByResID(@res_id, 0, 1) -- 1: only 1 RBS level
      )
    end

    if (EXISTS(select TOP 1 WRES_ID from @myres_tbl) OR EXISTS(select TOP 1 WRES_ID from @myres1_tbl))
    BEGIN
      --
      -- Handling rule 4 : Resources that I manage
      --      and rule 5 : Resources that I manage directly (This is a subset of rule 4)
      -- Optimize the rule 5 with rule 4
      --
      IF (@deny_rule_info & 16 != 0)
       begin
         insert into @deny_res_tbl (WRES_ID)
         (
           select WRES_ID from @myres_tbl
         )
       end
      ELSE 
       begin
         IF (@allow_rule_info & 16 != 0) AND (@allow_rule_info & 1 = 0)
          begin
          insert into @allow_res_tbl (WRES_ID)
          (
            select WRES_ID from @myres_tbl
          )
          end
         ELSE IF (@allow_rule_info & 32 != 0) AND (@allow_rule_info & 1 = 0) AND (@deny_rule_info & 32 = 0)
          begin
            insert into @allow_res_tbl (WRES_ID)
            (
              select WRES_ID from @myres1_tbl
            )
          end

         IF (@deny_rule_info & 32 != 0)
          begin
           insert into @deny_res_tbl (WRES_ID)
           (
             select WRES_ID from @myres1_tbl
           )
          end
       end
    END -- end of -- if (EXISTS(select TOP 1 WRES_ID from @myres_table)
  END

  ---------------------------------------------------------
  -- After taking care of rules. Generate the final list
  ---------------------------------------------------------
  INSERT INTO @ret_res_tbl (WRES_ID)
  (
    select distinct R1.WRES_ID
      from @allow_res_tbl R1 INNER JOIN MSP_WEB_RESOURCES R ON (R1.WRES_ID=R.WRES_ID and NOT (R.WRES_IS_ENABLED=0 and R.WRES_CAN_LOGIN=0 and WRES_COUNT_LICENSE=0 and R.RES_EUID IS NULL))
     where R1.WRES_ID not in 
           ( select distinct WRES_ID from @deny_res_tbl )
  )

RETURN
END
GO
GRANT SELECT ON dbo.MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
-- 
-- PROCEDURE: MSP_WEB_SP_SEC_GetAllResourcesResCanViewByViewID
--
-- DESCRIPTION:
--   Wrapper SP of MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID,
--   so that it can be exposed out to ADO.
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetAllResourcesResCanViewByViewID
   @res_id     int,
   @fea_act_id int,
   @view_id    int,
   @fEntOnly   int
AS
BEGIN
  If (@fEntOnly = 0)
   Begin

    select WRES_ID 
      from dbo.MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(@res_id, @fea_act_id, @view_id)

   End
  Else
   Begin

    select R.RES_EUID 
      from MSP_WEB_RESOURCES R
           INNER JOIN dbo.MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(@res_id, @fea_act_id, @view_id) A
           ON (R.WRES_ID = A.WRES_ID and R.RES_EUID is not NULL)

   End


RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetAllResourcesResCanViewByViewID TO MSProjectServerRole
GO



-------------------------------------------------------------------------------
-- 
-- PROCEDURE: MSP_WEB_SP_SEC_GetNumberOfResourcesResCanViewByViewID
--
-- DESCRIPTION:
--   Get number of resources res can view.
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetNumberOfResourcesResCanViewByViewID
   @res_id     int,
   @fea_act_id int,
   @view_id    int,
   @fEntOnly   int
AS
BEGIN
  If (@fEntOnly = 0)
   Begin

    select count(WRES_ID)
      from dbo.MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(@res_id, @fea_act_id, @view_id)

   End
  Else
   Begin

    select count(R.RES_EUID)
      from MSP_WEB_RESOURCES R
           INNER JOIN dbo.MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(@res_id, @fea_act_id, @view_id) A
           ON (R.WRES_ID = A.WRES_ID and R.RES_EUID is not NULL)

   End

RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetNumberOfResourcesResCanViewByViewID TO MSProjectServerRole
GO



-------------------------------------------------------------------------------
-- 
-- PROCEDURE: MSP_WEB_SP_SEC_GetResourcesResCanViewByViewIDFromList
--
-- DESCRIPTION:
--   Get resources from a given list that the res can view.
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetResourcesResCanViewByViewIDFromList
   @res_id     int,
   @fea_act_id int,
   @view_id    int,
   @res_list   NTEXT,
   @fEntOnly   int
AS
BEGIN
  If (@fEntOnly = 0)
   Begin

    select A.TokenVal as WRES_ID 
      from dbo.MSP_WEB_FN_ConvertListToTable(@res_list) A
           INNER JOIN dbo.MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(@res_id, @fea_act_id, @view_id) B ON A.TokenVal = B.WRES_ID

   End
  Else
   Begin

    select A.TokenVal as RES_EUID
      from dbo.MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(@res_id, @fea_act_id, @view_id) B
           INNER JOIN MSP_WEB_RESOURCES R ON (R.RES_EUID is not NULL and R.WRES_ID = B.WRES_ID)
           INNER JOIN dbo.MSP_WEB_FN_ConvertListToTable(@res_list) A ON (A.TokenVal = R.RES_EUID)

   End

RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetResourcesResCanViewByViewIDFromList TO MSProjectServerRole
GO



-------------------------------------------------------------------------------
--
-- PROCEDURE: MSP_WEB_SP_SEC_CheckSPResourcePermission
--
-- DESCRIPTION:
--   Check if a given user has a certain permission on another resource
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_CheckSPResourcePermission
   @sp_guid  uniqueidentifier,
   @res_id   int,
   @act_id   int,
   @fAllow   tinyint OUTPUT
AS
BEGIN
  -- initialize OUTPUT false --
  set @fAllow = 0

  -- check for Organization permission --
  set @fAllow = dbo.MSP_WEB_FN_SEC_CheckOrgPermission(@act_id)
  if (@fAllow = 0)   goto ExitProc
  set @fAllow = 0

  -- check input @sp_guid, and get WRES_ID
  declare @sp_res_id int
  set @sp_res_id = 0
  select @sp_res_id=WRES_ID from MSP_WEB_RESOURCES where WRES_GUID=@sp_guid
  if (@sp_res_id = 0)  RETURN

  -- check if the proj id is in the projects that the resource has the permission
  if (EXISTS(select WRES_ID
               from MSP_WEB_RESOURCES
              where WRES_ID = @res_id
                and WRES_ID in (
                      select WRES_ID
                        from dbo.MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(@sp_res_id, @act_id, -1)
                    )))
  begin
    set @fAllow = 1
  end

ExitProc:
  select 'WSEC_ALLOW'=@fAllow
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_CheckSPResourcePermission TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
--
-- FUNCTION: MSP_WEB_FN_SEC_GetAllModelsResCanView
--
-- DESCRIPTION:
--   Get all the models a given user has a certain permissions on.
--
-------------------------------------------------------------------------------
CREATE FUNCTION dbo.MSP_WEB_FN_SEC_GetAllModelsResCanView (
   @res_id     int,
   @fea_act_id int
)
RETURNS @ret_model_tbl table (WMOD_MODEL_UID int)
AS
BEGIN
  -- Get the WRES_GUID for the resource
  declare @res_guid uniqueidentifier
  select @res_guid=WRES_GUID from MSP_WEB_RESOURCES where WRES_ID=@res_id
  if (@res_guid is null)  RETURN

  declare @model_allow_info_tbl table (WSEC_RULE_INFO int, WSEC_CAT_ID int)
  declare @model_deny_info_tbl  table (WSEC_RULE_INFO int, WSEC_CAT_ID int)

  -- Get the ALLOW rule/cat_list info cache table
  insert into @model_allow_info_tbl (WSEC_RULE_INFO, WSEC_CAT_ID) (
    select WSEC_RULE_INFO, WSEC_CAT_ID
     from dbo.MSP_WEB_FN_SEC_GetAllObjectsResCanViewByViewIDInfo(@res_guid, @fea_act_id, 1, 4, -1)
  )

  -- Get the DENY rule/cat_list info into local cache table
  insert into @model_deny_info_tbl (WSEC_RULE_INFO, WSEC_CAT_ID) (
    select WSEC_RULE_INFO, WSEC_CAT_ID
     from dbo.MSP_WEB_FN_SEC_GetAllObjectsResCanViewByViewIDInfo(@res_guid, @fea_act_id, 0, 4, -1)
  )

  --
  -- Get the ALLOW/DENY rule info
  --
  declare @allow_rule_info  int
  declare @deny_rule_info   int
  set @allow_rule_info = 0
  set @deny_rule_info = 0

  select TOP 1 @allow_rule_info=WSEC_RULE_INFO from @model_allow_info_tbl
  select TOP 1 @deny_rule_info=WSEC_RULE_INFO from @model_deny_info_tbl

  declare @deny_res_tbl table  (WMOD_MODEL_UID int)
  declare @allow_model_tbl table (WMOD_MODEL_UID int)

  ----------------------------------------------------------
  -- Check the returned info, optimize the query
  -- Currently supported rules for Model :
  --  Rule 0: All current and future models
  --  Rule 1: Models in the list
  --  Rule 2: Models owned
  --  Rule 3: Models created by resources that I manage
  ----------------------------------------------------------
  --
  -- Handling rule 0: All current and future models
  --
  if (@deny_rule_info & 1 != 0) -- Deny ALL: no need for further operation
    RETURN

  if (@allow_rule_info = 0)  -- No infomation in @proj_allow_rule_info
    RETURN

  if (@allow_rule_info & 1 != 0) -- Allow: all models
  begin
    insert into @allow_model_tbl (WMOD_MODEL_UID)
    (
      select WMOD_MODEL_UID from MSP_WEB_MODELS
    )
  end

  --
  -- Handling rule 1: Models in the list
  --
  if (@allow_rule_info & 2 != 0) AND (@allow_rule_info & 1 = 0)
  begin
    insert into @allow_model_tbl (WMOD_MODEL_UID)
    (
      select distinct WSEC_OBJ_ID as WMOD_MODEL_UID
        from MSP_WEB_SECURITY_CATEGORY_OBJECTS
        where WSEC_OBJ_TYPE=4 -- Model
          and WSEC_CAT_ID in (select WSEC_CAT_ID from @model_allow_info_tbl)
    )
  end

  if (@deny_rule_info & 2 != 0)
  begin
    insert into @deny_res_tbl (WMOD_MODEL_UID)
    (
      select distinct WSEC_OBJ_ID as WMOD_MODEL_UID
        from MSP_WEB_SECURITY_CATEGORY_OBJECTS
        where WSEC_OBJ_TYPE=4 -- Resources
          and WSEC_CAT_ID in (select WSEC_CAT_ID from @model_deny_info_tbl)
    )
  end

  --
  -- Handling rule 2: Models owned
  --
  IF (@deny_rule_info & 4 != 0)
   begin
    insert into @deny_res_tbl (WMOD_MODEL_UID)
    (
      select WMOD_MODEL_UID from MSP_WEB_MODELS where WMOD_CREATED_BY_ID=@res_id
    )
   end
  ELSE IF (@allow_rule_info & 4 != 0) AND (@allow_rule_info & 1 = 0)
   begin
    insert into @allow_model_tbl (WMOD_MODEL_UID)
    (
      select WMOD_MODEL_UID from MSP_WEB_MODELS where WMOD_CREATED_BY_ID=@res_id
    )
   end

  -- Get the enterprise info
  declare @fEnt int
  set @fEnt = 0
  select @fEnt=WADMIN_ENABLE_ENTERPRISE from MSP_WEB_ADMIN
  IF (@fEnt = 1)
  BEGIN
    -- cache the my resources, so we don't have to calc it twice
    declare @myres_tbl table (WRES_ID int)
    IF ((@deny_rule_info & 8 != 0) OR ((@allow_rule_info & 8 != 0) AND (@allow_rule_info & 1 = 0)))
    begin
      insert into @myres_tbl (WRES_ID)
      (
        select WRES_ID from dbo.MSP_WEB_FN_SEC_GetResourcesManagedByResID(@res_id, 0, -1) -- 0: not including the resource himself.
      )
    end

    If (EXISTS(select TOP 1 WRES_ID from @myres_tbl))
    BEGIN
      --
      -- Handling rule 3: Models created by resources that I manage
      -- 
      IF (@deny_rule_info & 8 != 0)
       begin
         insert into @deny_res_tbl (WMOD_MODEL_UID)
         (
           select WMOD_MODEL_UID from MSP_WEB_MODELS where WMOD_CREATED_BY_ID in ( select WRES_ID from @myres_tbl )
         )
       end
      ELSE IF (@allow_rule_info & 8 != 0) AND (@allow_rule_info & 1 = 0)
       begin
         insert into @allow_model_tbl (WMOD_MODEL_UID)
         (
           select WMOD_MODEL_UID from MSP_WEB_MODELS where WMOD_CREATED_BY_ID in ( select WRES_ID from @myres_tbl )
         )
       end
    END -- end of -- if (EXISTS(select TOP 1 WRES_ID from @myres_table)
  END

  ---------------------------------------------------------
  -- After taking care of rules. Generate the final list
  ---------------------------------------------------------
  INSERT INTO @ret_model_tbl (WMOD_MODEL_UID)
  (
    select distinct WMOD_MODEL_UID
      from @allow_model_tbl
     where WMOD_MODEL_UID not in 
           ( select distinct WMOD_MODEL_UID from @deny_res_tbl )
  )

RETURN
END
GO
GRANT SELECT ON dbo.MSP_WEB_FN_SEC_GetAllModelsResCanView TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
--
-- PROCEDURE: MSP_WEB_SP_SEC_GetAllModelsResCanView
--
-- DESCRIPTION:
--   Wrapper SP for MSP_WEB_FN_SEC_GetAllModelResCanView, 
--   so that it can be exposed out to ADO.
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_GetAllModelsResCanView
   @res_id     int,
   @fea_act_id int
AS
BEGIN
  select distinct WMOD_MODEL_UID 
    from dbo.MSP_WEB_FN_SEC_GetAllModelsResCanView(@res_id, @fea_act_id)
   order by WMOD_MODEL_UID
RETURN
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_GetAllModelsResCanView TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
--
-- PROCEDURE: MSP_WEB_SP_SEC_CheckSPModelPermission
--
-- DESCRIPTION:
--   Check if a given user has a certain permission on a given model
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_CheckSPModelPermission
   @sp_guid   uniqueidentifier,
   @model_uid int,
   @act_id    int,
   @fAllow    tinyint OUTPUT
AS
BEGIN
  -- initialize OUTPUT false --
  set @fAllow = 0

  -- check for Organization permission --
  set @fAllow = dbo.MSP_WEB_FN_SEC_CheckOrgPermission(@act_id)
  if (@fAllow = 0)   goto ExitProc
  set @fAllow = 0

  -- check input @sp_guid, and get WRES_ID
  declare @sp_res_id int
  set @sp_res_id = 0
  select @sp_res_id=WRES_ID from MSP_WEB_RESOURCES where WRES_GUID=@sp_guid
  if (@sp_res_id = 0)  RETURN

  -- check if the proj id is in the projects that the resource has the permission
  if (EXISTS(select WMOD_MODEL_UID
               from MSP_WEB_MODELS
              where WMOD_MODEL_UID=@model_uid
                and WMOD_MODEL_UID in (
                      select WMOD_MODEL_UID
                        from dbo.MSP_WEB_FN_SEC_GetAllModelsResCanView(@sp_res_id, @act_id)
                    )))
  begin
    set @fAllow = 1
  end

ExitProc:
  select 'WSEC_ALLOW'=@fAllow
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_CheckSPModelPermission TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
--
-- PROCEDURE: MSP_WEB_SP_SEC_CheckSPObjectPermission
--
-- DESCRIPTION:
--   Check if a given user has a certain permission on a given object of
--   the given object type.
--
--   In Project Server, currently we have 4 object types:
--   1 -- Projects
--   2 -- Resources
--   3 -- Views (Views do not have rules with it)
--   4 -- Models
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_CheckSPObjectPermission
   @sp_guid  uniqueidentifier,
   @obj_id   int,
   @obj_type int,
   @act_id   int,
   @fAllow   tinyint OUTPUT
AS
BEGIN
  declare @bAllow  tinyint
  declare @bDeny   tinyint
  declare @bAccess tinyint

  -- initialize as Denied
  set @fAllow = 0

  -- Projects --
  if (@obj_type = 1)
  begin
    exec dbo.MSP_WEB_SP_SEC_CheckSPProjectPermission @sp_guid, @obj_id, @act_id, @fAllow OUTPUT
    goto ExitProc
  end

  -- Resources --
  if (@obj_type = 2)
  begin
    exec dbo.MSP_WEB_SP_SEC_CheckSPResourcePermission @sp_guid, @obj_id, @act_id, @fAllow OUTPUT
    goto ExitProc  
  end

  -- Views. There are no category permissions associated with Views --
  if (@obj_type = 3)
    goto ExitProc

  -- Models --
  if (@obj_type = 4)
  begin
    exec dbo.MSP_WEB_SP_SEC_CheckSPModelPermission @sp_guid, @obj_id, @act_id, @fAllow OUTPUT
    goto ExitProc  
  end

  --------------------------------------------------------------------------
  -- For user-defined object types: Add permission checking support here. --
  --------------------------------------------------------------------------

ExitProc:
  -- return result in a recordset
  select 'WSEC_ALLOW'=@fAllow
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_CheckSPObjectPermission TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
--
-- PROCEDURE: MSP_WEB_SP_SEC_CheckSPObjectListPermission
--
-- DESCRIPTION:
--   Check if a given user has a certain category permission on a given
--   comma seperate list of objects of the given object type.
--
--   Returns TRUE if the user has the permission on all of the objects in the list.
--   Or FALSE if the user is denied of any of the given object in the list.
--
--   In Project Server, currently we have 4 object types:
--   1 -- Projects
--   2 -- Resources
--   3 -- Views (Views do not have rules with it)
--   4 -- Models
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_SEC_CheckSPObjectListPermission
   @sp_guid  uniqueidentifier,
   @obj_list ntext,
   @obj_type int,
   @act_id   int
AS
BEGIN
  declare @fAllow tinyint
  set @fAllow = 0  -- Default: DENY

  -- Get the WRES_ID for the given user --
  declare @sp_res_id int
  set @sp_res_id = 0
  select @sp_res_id=WRES_ID from MSP_WEB_RESOURCES where WRES_GUID=@sp_guid
  if (@sp_res_id = 0)  goto ExitProc

  -- Projects --
  if (@obj_type = 1)
  begin
    if NOT EXISTS(select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@obj_list)
                   where TokenVal not in (
                           select WPROJ_ID 
                             from dbo.MSP_WEB_FN_SEC_GetAllProjectsResCanViewByViewID(@sp_res_id, @act_id, -1, 3) -- 3: all projects and todolists
                         )
                 )
    begin
        set @fAllow = 1
    end
    goto ExitProc
  end

  -- Resources --
  if (@obj_type = 2)
  begin
    if NOT EXISTS(select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@obj_list)
                   where TokenVal not in (
                           select distinct WRES_ID 
                             from dbo.MSP_WEB_FN_SEC_GetAllResourcesResCanViewByViewID(@sp_res_id, @act_id, -1)
                         )
                 )
    begin
        set @fAllow = 1
    end
    goto ExitProc
  end

  -- Views. There are no category permissions associated with Views --
  if (@obj_type = 3)
    goto ExitProc

  -- Models --
  if (@obj_type = 4)
  begin
    if NOT EXISTS(select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@obj_list)
                   where TokenVal not in (
                           select distinct WMOD_MODEL_UID
                             from dbo.MSP_WEB_FN_SEC_GetAllModelsResCanView(@sp_res_id, @act_id)
                         )
                 )
    begin
        set @fAllow = 1
    end
    goto ExitProc  
  end

ExitProc:
  select 'WSEC_ALLOW' = @fAllow
END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_SEC_CheckSPObjectListPermission TO MSProjectServerRole
GO


-------------------------------------------------------------------------------
--
-- PROCEDURE: MSP_WEB_SP_QRY_AddLinkForSTS
--
-- DESCRIPTION:
--   Creates a link between two objects in MSP_WEB_OBJECT_LINKS table unless the
--   link already exists. It also updates the refcounts for objects in 
--	  MSP_WEB_OBJECTS table. (This was previously a function in ObjLinkProvider
--   but we were having concurency problems and there was a need to convert the
--   whole function into a stored procedure).
--
--   In MSP_WEB_OBJECTS table currently we have 5 object types:
--   1 -- Projects
--   2 -- Tasks
--   3 -- Document
--   4 -- Issue
--   5 -- Risk
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_AddLinkForSTS
   @obj1_id   int,
   @obj2_id   int,
   @link_type int
AS
BEGIN

BEGIN TRANSACTION

   declare @bSuccess int
   set @bSuccess = 0

   -- Add the link between 2 object unless it already exists.
   declare @obj1 int
   declare @obj2 int
   declare @link int

   SELECT @obj1=WOBJLINK_OBJECT1, @obj2=WOBJLINK_OBJECT2, @link=WOBJLINK_TYPE
   FROM MSP_WEB_OBJECT_LINKS
   WHERE (WOBJLINK_OBJECT1 = @obj1_id AND WOBJLINK_OBJECT2 = @obj2_id) OR 
         (WOBJLINK_OBJECT1 = @obj2_id AND WOBJLINK_OBJECT2 = @obj1_id)

   -- If the record does not already exist then insert it.
   if(@@rowcount = 0)
   begin
      INSERT INTO MSP_WEB_OBJECT_LINKS (WOBJLINK_OBJECT1, WOBJLINK_OBJECT2, WOBJLINK_TYPE) VALUES (@obj1_id,@obj2_id,@link_type)
   end
   else
      goto ExitProc

   -- Get the record for the first object.
   declare @objtype1     int
   declare @docrefcnt1   int
   declare @issuerefcnt1 int
   declare @riskrefcnt1 int
   declare @otherrefcnt1 int

   SELECT @objtype1=WOBJ_TYPE,
          @docrefcnt1=WOBJ_DOC_REF_CNT,
          @issuerefcnt1=WOBJ_ISSUE_REF_CNT,
          @riskrefcnt1=WOBJ_RISK_REF_CNT,
          @otherrefcnt1=WOBJ_OTHER_REF_CNT
   FROM MSP_WEB_OBJECTS WHERE WOBJ_ID = @obj1_id

   -- Make sure this returns only 1 record.
   if(@@rowcount != 1) goto ExitProc

   -- Get the record for the second object.
   declare @objtype2     int
   declare @docrefcnt2   int
   declare @issuerefcnt2 int
   declare @riskrefcnt2 int
   declare @otherrefcnt2 int

   SELECT @objtype2=WOBJ_TYPE,
          @docrefcnt2=WOBJ_DOC_REF_CNT,
          @issuerefcnt2=WOBJ_ISSUE_REF_CNT,
          @riskrefcnt2=WOBJ_RISK_REF_CNT,
          @otherrefcnt2=WOBJ_OTHER_REF_CNT
   FROM MSP_WEB_OBJECTS WHERE WOBJ_ID = @obj2_id

   -- Make sure this returns only 1 record.
   if(@@rowcount != 1) goto ExitProc

   --
   -- Update the appropriate reference counts for object 2.
   --
   -- Check if object type is 'document'.
   if(@objtype2 = 3)
   begin
      UPDATE MSP_WEB_OBJECTS SET WOBJ_DOC_REF_CNT=(@docrefcnt1+1) WHERE WOBJ_ID=@obj1_id
   end

   -- Check if object type is 'issue'.
   else if(@objtype2 = 4)
   begin
      UPDATE MSP_WEB_OBJECTS SET WOBJ_ISSUE_REF_CNT=(@issuerefcnt1+1) WHERE WOBJ_ID=@obj1_id
   end

   -- Check if object type is 'risk'.
   else if(@objtype2 = 5)
   begin
      UPDATE MSP_WEB_OBJECTS SET WOBJ_RISK_REF_CNT=(@riskrefcnt1+1) WHERE WOBJ_ID=@obj1_id
   end

   -- All the other types such as 'project' and 'task'.
   else
   begin
      UPDATE MSP_WEB_OBJECTS SET WOBJ_OTHER_REF_CNT=(@otherrefcnt1+1) WHERE WOBJ_ID=@obj1_id
   end

   --
   -- Update the appropriate reference counts for object 1.
   --
   -- Check if object type is 'document'.
   if(@objtype1 = 3)
   begin
      UPDATE MSP_WEB_OBJECTS SET WOBJ_DOC_REF_CNT=(@docrefcnt2+1) WHERE WOBJ_ID=@obj2_id
   end

   -- Check if object type is 'issue'.
   else if(@objtype1 = 4)
   begin
      UPDATE MSP_WEB_OBJECTS SET WOBJ_ISSUE_REF_CNT=(@issuerefcnt2+1) WHERE WOBJ_ID=@obj2_id
   end

   -- Check if object type is 'risk'.
   else if(@objtype1 = 5)
   begin
      UPDATE MSP_WEB_OBJECTS SET WOBJ_RISK_REF_CNT=(@riskrefcnt2+1) WHERE WOBJ_ID=@obj2_id
   end

   -- All the other types such as 'project' and 'task'.
   else
   begin
      UPDATE MSP_WEB_OBJECTS SET WOBJ_OTHER_REF_CNT=(@otherrefcnt2+1) WHERE WOBJ_ID=@obj2_id
   end

   set @bSuccess = 1

ExitProc:

   if(@bSuccess = 0)
      ROLLBACK TRANSACTION
   else
      COMMIT TRANSACTION

END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_AddLinkForSTS TO MSProjectServerRole
GO


/* Query #30060 */
-------------------------------------------------------------------------------
--
-- PROCEDURE: MSP_WEB_SP_QRY_RemoveLinkForSTS
--
-- DESCRIPTION:
--   Deletes a link between two objects in MSP_WEB_OBJECT_LINKS table. 
--   It also updates the refcounts for objects in MSP_WEB_OBJECTS table.
--   (This was previously a function in ObjLinkProvider but we were having
--   concurency problems and there was a need to convert the whole function into
--   a stored procedure).
--
--   In MSP_WEB_OBJECTS table currently we have 5 object types:
--   1 -- Projects
--   2 -- Tasks
--   3 -- Document
--   4 -- Issue
--   5 -- Risk
--
-------------------------------------------------------------------------------
CREATE PROCEDURE dbo.MSP_WEB_SP_QRY_RemoveLinkForSTS
   @obj1_id   int,
   @obj2_id   int
AS
BEGIN

BEGIN TRANSACTION

   declare @bSuccess int
   set @bSuccess = 0

   -- Remove the link between 2 object if it exists.
   declare @obj1 int
   declare @obj2 int

   SELECT @obj1=WOBJLINK_OBJECT1, @obj2=WOBJLINK_OBJECT2
   FROM MSP_WEB_OBJECT_LINKS
   WHERE (WOBJLINK_OBJECT1 = @obj1_id AND WOBJLINK_OBJECT2 = @obj2_id) OR 
         (WOBJLINK_OBJECT1 = @obj2_id AND WOBJLINK_OBJECT2 = @obj1_id)

   -- If the record does not exist then exit procedure.
   if(@@rowcount = 0)
   begin
      goto ExitProc
   end
   else
      DELETE FROM MSP_WEB_OBJECT_LINKS
      WHERE (WOBJLINK_OBJECT1 = @obj1_id AND WOBJLINK_OBJECT2 = @obj2_id) OR
            (WOBJLINK_OBJECT1 = @obj2_id AND WOBJLINK_OBJECT2 = @obj1_id)

   --
   -- Update refcounts.
   --

   -- Get the record for the first object.
   declare @objtype1     int
   declare @docrefcnt1   int
   declare @issuerefcnt1 int
   declare @riskrefcnt1 int
   declare @otherrefcnt1 int

   SELECT @objtype1=WOBJ_TYPE,
          @docrefcnt1=WOBJ_DOC_REF_CNT,
          @issuerefcnt1=WOBJ_ISSUE_REF_CNT,
          @riskrefcnt1=WOBJ_RISK_REF_CNT,
          @otherrefcnt1=WOBJ_OTHER_REF_CNT
   FROM MSP_WEB_OBJECTS WHERE WOBJ_ID = @obj1_id

   -- Make sure this returns only 1 record.
   if(@@rowcount != 1) goto ExitProc

   -- Get the record for the second object.
   declare @objtype2     int
   declare @docrefcnt2   int
   declare @issuerefcnt2 int
   declare @riskrefcnt2 int
   declare @otherrefcnt2 int

   SELECT @objtype2=WOBJ_TYPE,
          @docrefcnt2=WOBJ_DOC_REF_CNT,
          @issuerefcnt2=WOBJ_ISSUE_REF_CNT,
          @riskrefcnt2=WOBJ_RISK_REF_CNT,
          @otherrefcnt2=WOBJ_OTHER_REF_CNT
   FROM MSP_WEB_OBJECTS WHERE WOBJ_ID = @obj2_id

   -- Make sure this returns only 1 record.
   if(@@rowcount != 1) goto ExitProc

   --
   -- Update the appropriate reference counts for object 2.
   --

   -- Check if object type is 'document'.
   if(@objtype2 = 3)
   begin
      -- If each refcount is 0 then remove the object from MSP_WEB_OBJECTS table.
      if ((@docrefcnt1-1) < 1) AND (@issuerefcnt1 < 1) AND (@riskrefcnt1 < 1) AND (@otherrefcnt1 < 1)
      begin
         DELETE FROM MSP_WEB_OBJECTS WHERE WOBJ_ID=@obj1_id
      end
      else
      begin
         UPDATE MSP_WEB_OBJECTS SET WOBJ_DOC_REF_CNT=(@docrefcnt1-1) WHERE WOBJ_ID=@obj1_id
      end
   end

   -- Check if object type is 'issue'.
   else if(@objtype2 = 4)
   begin
      -- If each refcount is 0 then remove the object from MSP_WEB_OBJECTS table.
      if (@docrefcnt1 < 1) AND ((@issuerefcnt1-1) < 1) AND (@riskrefcnt1 < 1) AND (@otherrefcnt1 < 1)
      begin
         DELETE FROM MSP_WEB_OBJECTS WHERE WOBJ_ID=@obj1_id
      end
      else
      begin
         UPDATE MSP_WEB_OBJECTS SET WOBJ_ISSUE_REF_CNT=(@issuerefcnt1-1) WHERE WOBJ_ID=@obj1_id
      end
   end

   -- Check if object type is 'risk'.
   else if(@objtype2 = 5)
   begin
      -- If each refcount is 0 then remove the object from MSP_WEB_OBJECTS table.
      if (@docrefcnt1 < 1) AND (@issuerefcnt1 < 1) AND ((@riskrefcnt1-1) < 1) AND (@otherrefcnt1 < 1)
      begin
         DELETE FROM MSP_WEB_OBJECTS WHERE WOBJ_ID=@obj1_id
      end
      else
      begin
         UPDATE MSP_WEB_OBJECTS SET WOBJ_RISK_REF_CNT=(@riskrefcnt1-1) WHERE WOBJ_ID=@obj1_id
      end
   end

   -- All the other types such as 'project' and 'task'.
   else
   begin
      -- If each refcount is 0 then remove the object from MSP_WEB_OBJECTS table.
      if (@docrefcnt1 < 1) AND (@issuerefcnt1 < 1) AND (@riskrefcnt1 < 1) AND ((@otherrefcnt1-1) < 1)
      begin
         DELETE FROM MSP_WEB_OBJECTS WHERE WOBJ_ID=@obj1_id
      end
      else
      begin
         UPDATE MSP_WEB_OBJECTS SET WOBJ_OTHER_REF_CNT=(@otherrefcnt1-1) WHERE WOBJ_ID=@obj1_id
      end
   end

   --
   -- Update the appropriate reference counts for object 1.
   --

   -- Check if object type is 'document'.
   if(@objtype1 = 3)
   begin
      -- If each refcount is 0 then remove the object from MSP_WEB_OBJECTS table.
      if ((@docrefcnt2-1) < 1) AND (@issuerefcnt2 < 1) AND (@riskrefcnt2 < 1) AND (@otherrefcnt2 < 1)
      begin
         DELETE FROM MSP_WEB_OBJECTS WHERE WOBJ_ID=@obj2_id
      end
      else
      begin
         UPDATE MSP_WEB_OBJECTS SET WOBJ_DOC_REF_CNT=(@docrefcnt2-1) WHERE WOBJ_ID=@obj2_id
      end
   end

   -- Check if object type is 'issue'.
   else if(@objtype1 = 4)
   begin
      -- If each refcount is 0 then remove the object from MSP_WEB_OBJECTS table.
      if (@docrefcnt2 < 1) AND ((@issuerefcnt2-1) < 1) AND (@riskrefcnt2 < 1) AND (@otherrefcnt2 < 1)
      begin
         DELETE FROM MSP_WEB_OBJECTS WHERE WOBJ_ID=@obj2_id
      end
      else
      begin
         UPDATE MSP_WEB_OBJECTS SET WOBJ_ISSUE_REF_CNT=(@issuerefcnt2-1) WHERE WOBJ_ID=@obj2_id
      end
   end

   -- Check if object type is 'risk'.
   else if(@objtype1 = 5)
   begin
      -- If each refcount is 0 then remove the object from MSP_WEB_OBJECTS table.
      if (@docrefcnt2 < 1) AND (@issuerefcnt2 < 1) AND ((@riskrefcnt2-1) < 1) AND (@otherrefcnt2 < 1)
      begin
         DELETE FROM MSP_WEB_OBJECTS WHERE WOBJ_ID=@obj2_id
      end
      else
      begin
         UPDATE MSP_WEB_OBJECTS SET WOBJ_RISK_REF_CNT=(@riskrefcnt2-1) WHERE WOBJ_ID=@obj2_id
      end
   end

   -- All the other types such as 'project' and 'task'.
   else
   begin
      -- If each refcount is 0 then remove the object from MSP_WEB_OBJECTS table.
      if (@docrefcnt2 < 1) AND (@issuerefcnt2 < 1) AND (@riskrefcnt2 < 1) AND ((@otherrefcnt2-1) < 1)
      begin
         DELETE FROM MSP_WEB_OBJECTS WHERE WOBJ_ID=@obj2_id
      end
      else
      begin
         UPDATE MSP_WEB_OBJECTS SET WOBJ_OTHER_REF_CNT=(@otherrefcnt2-1) WHERE WOBJ_ID=@obj2_id
      end
   end

   set @bSuccess = 1

ExitProc:

   if(@bSuccess = 0)
      ROLLBACK TRANSACTION
   else
      COMMIT TRANSACTION

END
GO
GRANT EXECUTE ON dbo.MSP_WEB_SP_QRY_RemoveLinkForSTS TO MSProjectServerRole
GO

/* Query PDS001 */
CREATE PROCEDURE dbo.MSP_PDS_ReadWProjIDByProjID
   @p0 INT
AS
SELECT WPROJ_ID FROM MSP_WEB_PROJECTS WHERE PROJ_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_PDS_ReadWProjIDByProjID TO MSProjectServerRole
GO

/* Query PDS002 */
CREATE PROCEDURE dbo.MSP_PDS_ReadProjectInfoByProjID
   @p0 INT
AS
SELECT PROJ_ID,PROJ_NAME,PROJ_TYPE,PROJ_PROJECT,PROJ_VERSION,PROJ_LAST_SAVED,PROJ_CHECKEDOUT,PROJ_CHECKOUTBY,PROJ_CHECKOUTDATE,PROJ_ADMINPROJECT 
  FROM MSP_PROJECTS 
 WHERE PROJ_ID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_PDS_ReadProjectInfoByProjID TO MSProjectServerRole
GO

/* Query PDS003 */
CREATE PROCEDURE dbo.MSP_PDS_ReadProjectInfoByProjType
   @p0 INT
AS
SELECT PROJ_ID,PROJ_NAME,PROJ_TYPE,PROJ_PROJECT,PROJ_VERSION,PROJ_LAST_SAVED,PROJ_CHECKEDOUT,PROJ_CHECKOUTBY,PROJ_CHECKOUTDATE,PROJ_ADMINPROJECT 
  FROM MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE)
 WHERE PROJ_TYPE=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_PDS_ReadProjectInfoByProjType TO MSProjectServerRole
GO

/* Query PDS004 */
CREATE PROCEDURE dbo.MSP_PDS_ReadProjectInfoByProjName
   @p0 varchar(255)
AS
SELECT PROJ_ID,PROJ_NAME,PROJ_TYPE,PROJ_PROJECT,PROJ_VERSION,PROJ_LAST_SAVED,PROJ_CHECKEDOUT,PROJ_CHECKOUTBY,PROJ_CHECKOUTDATE,PROJ_ADMINPROJECT 
  FROM MSP_PROJECTS 
 WHERE lower(PROJ_NAME)=lower(@p0) RETURN	
GO

GRANT EXECUTE ON dbo.MSP_PDS_ReadProjectInfoByProjName TO MSProjectServerRole
GO

/* Query PDS005 */
CREATE PROCEDURE dbo.MSP_PDS_ReadResourceInfoByResUID
   @p0 INT,
   @p1 INT
AS
SELECT RES_UID,RES_NAME,RES_ID,RES_TYPE,RES_RTYPE,RES_CHECKEDOUT,RES_CHECKOUTBY,RES_CHECKOUTDATE,RES_ENTERPRISE_TIMESTAMP,RES_PHONETICS,RES_AD_GUID
  FROM MSP_RESOURCES 
 WHERE PROJ_ID=@p1 AND RES_UID=@p0 RETURN
GO

GRANT EXECUTE ON dbo.MSP_PDS_ReadResourceInfoByResUID TO MSProjectServerRole
GO

/* Query PDS006 */
CREATE PROCEDURE dbo.MSP_PDS_ReadResourceInfoByResName
   @p0 varchar(255),
   @p1 INT
AS
SELECT RES_UID,RES_NAME,RES_ID,RES_TYPE,RES_RTYPE,RES_CHECKEDOUT,RES_CHECKOUTBY,RES_CHECKOUTDATE,RES_ENTERPRISE_TIMESTAMP,RES_PHONETICS,RES_AD_GUID 
  FROM MSP_RESOURCES 
 WHERE PROJ_ID=@p1 AND lower(RES_NAME)=lower(@p0) RETURN 
GO

GRANT EXECUTE ON dbo.MSP_PDS_ReadResourceInfoByResName TO MSProjectServerRole
GO

/* Query PDS007 */
CREATE PROCEDURE dbo.MSP_PDS_ReadGlobalInfo
AS
SELECT PROJ_NAME,PROJ_ID FROM MSP_PROJECTS WITH (NOLOCK, INDEX=I_MSP_PROJECTS_PROJ_TYPE)   WHERE PROJ_TYPE = 2 RETURN
GO

GRANT EXECUTE ON dbo.MSP_PDS_ReadGlobalInfo TO MSProjectServerRole
GO

/* Query PDS008 */
CREATE PROCEDURE dbo.MSP_PDS_ReadResglobalInfo
   @userid INT = 1 -- Added for P11/7264 (modified for P11/10258)
AS
SELECT PROJ_NAME,PROJ_ID,WRES_USE_NT_LOGON,WRES_USE_NT_LOGON,WRES_NT_ACCOUNT 
  FROM MSP_PROJECTS WITH (NOLOCK, INDEX=I_MSP_PROJECTS_PROJ_TYPE), MSP_WEB_RESOURCES
 WHERE PROJ_TYPE = 3 AND WRES_ID = @userid
RETURN
GO

GRANT EXECUTE ON dbo.MSP_PDS_ReadResglobalInfo TO MSProjectServerRole
GO

/* Query PDS009 */
CREATE PROCEDURE dbo.MSP_PDS_ReadResourceExtraInfo
   @p0 INT,
   @p1 INT
AS
SELECT TEXT_FIELD_ID,TEXT_VALUE
  FROM MSP_TEXT_FIELDS 
 WHERE PROJ_ID=@p0 AND TEXT_REF_UID=@p1 RETURN
GO

GRANT EXECUTE ON dbo.MSP_PDS_ReadResourceExtraInfo TO MSProjectServerRole
GO


/* Query PDS010 */
CREATE PROCEDURE dbo.MSP_PDS_ResourcesAccessGrant
   @p0 SMALLINT,
   @p1 DATETIME,
   @p2 TINYINT,
   @p3 TINYINT,
   @p4 NTEXT
AS
begin

  -- We need to check for multiple resource globals, and throw an error if there are many
  DECLARE @resglobalcount INT
  SELECT @resglobalcount = count(*) FROM MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE) WHERE PROJ_TYPE=3
  IF (@resglobalcount > 1) 
    BEGIN
      RAISERROR ('Multiple Resglobals', 16, 1)
      RETURN
    END

  INSERT INTO MSP_RES_SECURITY (SEC_SPID,SEC_SPIDDATESTAMP,SEC_READCOUNT,SEC_WRITECOUNT,ERUID)
  (
    select @p0, @p1, @p2, @p3, TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@p4)
  )
return
end
GO

GRANT EXECUTE ON dbo.MSP_PDS_ResourcesAccessGrant TO MSProjectServerRole
GO

/* Query PDS011 */
CREATE PROCEDURE dbo.MSP_PDS_ResourceAssign
   @res_proj_id int,
   @res_euid int,
   @proj_id int,
   @res_uid int,
   @res_id int,
   @booking_type int = -1
AS
begin
	/* Bump up the res_ids to make room for this entry */
	UPDATE MSP_RESOURCES 
	   SET RES_ID = RES_ID + 1
	 WHERE PROJ_ID = @proj_id 
	   AND RES_ID >= @res_id
	
	INSERT INTO MSP_RESOURCES (
		PROJ_ID,RES_UID,RES_ID,RES_EUID,
		RESERVED_DATA,RES_ACWP,RES_BCWP,RES_BCWS,RES_NUM_OBJECTS,
		EXT_EDIT_REF_DATA,RES_HAS_LINKED_FIELDS,RES_IS_OVERALLOCATED,
		RES_TYPE,RES_HAS_NOTES,RES_CAN_LEVEL,RES_STD_RATE_FMT,RES_OVT_RATE_FMT,
		RES_ACCRUE_AT,RES_WORKGROUP_MESSAGING,RES_CAL_UID,RES_AVAIL_FROM,RES_AVAIL_TO,
		RES_STD_RATE,RES_OVT_RATE,RES_MAX_UNITS,RES_WORK,RES_ACT_WORK,
		RES_BASE_WORK,RES_OVT_WORK,RES_COST_PER_USE,RES_REM_WORK,RES_REG_WORK,
		RES_ACT_OVT_WORK,RES_REM_OVT_WORK,RES_PEAK,RES_ACT_COST,RES_COST,
		RES_BASE_COST,RES_REM_COST,RES_OVT_COST,RES_ACT_OVT_COST,RES_REM_OVT_COST,
		RES_NAME,RES_INITIALS,RES_PHONETICS,RES_MATERIAL_LABEL,RES_RTF_NOTES,
		RES_RTYPE,RES_ENTERPRISE_TIMESTAMP,RES_BOOKING_TYPE
	) (SELECT 
		@proj_id,@res_uid,@res_id,RES_EUID,
		RESERVED_DATA,RES_ACWP,RES_BCWP,RES_BCWS,RES_NUM_OBJECTS,
		N'1',RES_HAS_LINKED_FIELDS,RES_IS_OVERALLOCATED,
		RES_TYPE,RES_HAS_NOTES,RES_CAN_LEVEL,RES_STD_RATE_FMT,RES_OVT_RATE_FMT,
		RES_ACCRUE_AT,RES_WORKGROUP_MESSAGING,RES_CAL_UID,RES_AVAIL_FROM,RES_AVAIL_TO,
		RES_STD_RATE,RES_OVT_RATE,RES_MAX_UNITS,RES_WORK,RES_ACT_WORK,
		RES_BASE_WORK,RES_OVT_WORK,RES_COST_PER_USE,RES_REM_WORK,RES_REG_WORK,
		RES_ACT_OVT_WORK,RES_REM_OVT_WORK,RES_PEAK,RES_ACT_COST,RES_COST,
		RES_BASE_COST,RES_REM_COST,RES_OVT_COST,RES_ACT_OVT_COST,RES_REM_OVT_COST,
		RES_NAME,RES_INITIALS,RES_PHONETICS,RES_MATERIAL_LABEL,RES_RTF_NOTES,
		RES_RTYPE,RES_ENTERPRISE_TIMESTAMP,
                CASE WHEN @booking_type < 0 THEN RES_BOOKING_TYPE ELSE @booking_type END
	FROM MSP_RESOURCES WHERE PROJ_ID = @res_proj_id AND RES_UID = @res_euid)

  -- Get the first available calendar UID in the project
  DECLARE @CalUID INT
  SELECT @CalUID = (MAX(CAL_UID) + 1) FROM MSP_CALENDARS WHERE PROJ_ID = @proj_id
  
  -- Get the EUID of the resource's calendar in the resglobal's calendar table
  DECLARE @CalEUID INT
  SET @CalEUID = -1
  SELECT @CalEUID = CAL_UID FROM MSP_CALENDARS WHERE PROJ_ID = @res_proj_id AND RES_UID = @res_euid

  -- Add a resource calendar for the resource
  INSERT INTO MSP_CALENDARS (PROJ_ID,CAL_UID,RES_UID,CAL_BASE_UID,CAL_IS_BASE_CAL,CAL_ENTUID) 
     VALUES(@proj_id,@CalUID,@res_uid,1,0,@CalEUID)
 
return
end
GO

GRANT EXECUTE ON dbo.MSP_PDS_ResourceAssign TO MSProjectServerRole
GO

/* Query PDS012 */
CREATE     PROCEDURE dbo.MSP_PDS_AssignmentsGetData
   @assn_list	 NTEXT           -- comma-delimited list of WUIDs 
AS
BEGIN

SELECT 	WA.WASSN_ID, WA.WRES_ID,
	WA.ASSN_WORK,  WA.ASSN_REM_WORK, WA.ASSN_ACT_WORK, 
       	WA.WASSN_PCT_COMP, WA.ASSN_START_DATE, WA.ASSN_FINISH_DATE, 
	WP.PROJ_ID, WP.PROJ_NAME, WP.WPROJ_TYPE, 
	WA.TASK_NAME, WA.TASK_UID, 
	WR.RES_NAME, WR.RES_EUID,
	WA.WASSN_CURRENT_TRACKING_MODE,
	WA.WASSN_COMMENTS, WA.TASK_IS_SUMMARY, WA.TASK_IS_MILESTONE, 
	WA.WASSN_PARENT_ID,(CASE WHEN WA.WASSN_PARENT_ID <> -1 THEN (select TASK_NAME from MSP_WEB_ASSIGNMENTS WA2 WHERE WA2.WASSN_ID=WA.WASSN_PARENT_ID) ELSE null END) as 'PARENTNAME',
	(select count(TASK_UID) from MSP_WEB_ASSIGNMENTS WA2 where WA2.TASK_IS_SUMMARY=1 and WA2.TASK_UID=WA.TASK_UID and WA2.WASSN_ID<>WA.WASSN_ID and WA2.WPROJ_ID=WA.WPROJ_ID and WA2.WRES_ID=WA.WRES_ID) as 'ISASSIGNEDSUMMARY',
	WA.WASSN_DELETED_IN_PROJ, WR.WRES_ID, WA.WRES_ID_MGR, WA.WASSN_SEND_UPDATE_NEEDED, WP.WPROJ_ADMINPROJECT, 
	WR2.RES_NAME AS 'PROJECTMANAGERNAME', WA.WASSN_UPDATE_STATUS -- P11/8822 - Return Project Manager Name & Update Status
FROM (((MSP_WEB_ASSIGNMENTS WA INNER JOIN MSP_WEB_PROJECTS WP ON WA.WPROJ_ID=WP.WPROJ_ID)
	INNER JOIN MSP_WEB_RESOURCES WR ON WA.WRES_ID=WR.WRES_ID) 
	LEFT JOIN MSP_WEB_RESOURCES WR2 ON WA.WRES_ID_MGR = WR2.WRES_ID  ) 
WHERE 	(WA.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@assn_list)))
return
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_AssignmentsGetData TO MSProjectServerRole
GO

/* Query PDS013 */
CREATE     PROCEDURE dbo.MSP_PDS_GetAvailableAssignments
   @avail_res_list  	ntext,     	-- comma-delimited list of resources the user has access to
   @assn_list	 	varchar(4000), -- comma-delimited list of WUIDs (or no list at all)
   @res_list     	varchar(4000),	-- comma-delimited list of resources (or no list at all)
   @dStartDate   	datetime,  	-- start date (or no date at all)
   @dFinishDate  	datetime,  	-- finish date (or no date at all)
   @fHaveDates		INT,       	-- whether the start and finish dates passed in are valid and to be used (1 or 0)	
   @adminproj_type	INT,		-- filtering by admin project type (0 = normal, 1 = admin NWT projects, 2 = both)
   @approval_status     INT             -- filtering by whether assignment has ANY work with the given approval status (0=pending,1=accepted,2=rejected,3=any)
AS
BEGIN

SELECT DISTINCT	WA.WASSN_ID
FROM (((MSP_WEB_ASSIGNMENTS WA INNER JOIN MSP_WEB_PROJECTS WP ON WA.WPROJ_ID=WP.WPROJ_ID)
	INNER JOIN MSP_WEB_RESOURCES WR ON WA.WRES_ID=WR.WRES_ID)
        LEFT JOIN MSP_WEB_WORK_APPROVAL WWA ON WA.WASSN_ID = WWA.WASSN_ID )
WHERE 	(WA.WASSN_IS_CONFIRMED<>0 OR WP.WPROJ_ADMINPROJECT<>0)
     and WA.WASSN_REMOVED_BY_RESOURCE=0
     and (WA.WRES_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@avail_res_list)))
     and (LEN(@assn_list) = 0 or (WA.WASSN_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@assn_list))))
     and (LEN(@res_list) = 0 or (WA.WRES_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@res_list))))
     and ( (@fHaveDates = 0) or 
			((@dStartDate <= WA.ASSN_START_DATE) and (WA.ASSN_START_DATE <= @dFinishDate)) or
			((@dStartDate <= WA.ASSN_FINISH_DATE) and (WA.ASSN_FINISH_DATE <= @dFinishDate)) or 
			((WA.ASSN_START_DATE <= @dStartDate) and (@dFinishDate <= WA.ASSN_FINISH_DATE)))
     and ( ( @adminproj_type = 2 ) or 
		(@adminproj_type = WPROJ_ADMINPROJECT) or 
		(@adminproj_type = 0 and WPROJ_ADMINPROJECT IS NULL) )
     and ( ( @approval_status = 3) or (WWA.WAPPROVAL_STATUS = @approval_status))
ORDER BY WA.WASSN_ID

RETURN
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_GetAvailableAssignments TO MSProjectServerRole
GO


/* Query PDS014 */
CREATE FUNCTION dbo.MSP_PDS_FN_MatchResourcesByMV (
   @res_global_proj_id int,
   @code_field_id int,
   @list ntext
)
returns @tmptable table (RES_UID int, num int)
as
begin

insert into @tmptable (RES_UID, num) (
   select T.CODE_REF_UID, Count(T.CODE_REF_UID) as num
     from MSP_MV_FIELDS T
    inner join dbo.MSP_WEB_FN_ConvertListToTable(@list) on (T.CODE_UID = TokenVal)
    where T.PROJ_ID = @res_global_proj_id AND T.CODE_FIELD_ID = @code_field_id
    group by T.CODE_REF_UID
)
return
end
GO

GRANT SELECT ON dbo.MSP_PDS_FN_MatchResourcesByMV TO MSProjectServerRole
GO

/* Query PDS015 */
CREATE PROCEDURE dbo.MSP_PDS_SP_MatchResourcesByMV
   @res_global_proj_id int,
   @code_field_id int,
   @list   ntext,
   @min_num   int
as
begin
  select R.RES_UID 
    from dbo.MSP_PDS_FN_MatchResourcesByMV(@res_global_proj_id,@code_field_id,@list) R
   where R.num >= @min_num
  
end
GO


GRANT EXECUTE ON dbo.MSP_PDS_SP_MatchResourcesByMV TO MSProjectServerRole
GO

/* Query PDS016 */
CREATE PROCEDURE dbo.MSP_PDS_GetWebWork
   @p0 INT
AS
(
SELECT WASSN_ID, WWORK_START AS 'START', WWORK_FINISH AS 'FINISH', WWORK_TYPE AS 'TYPE', WWORK_VALUE AS 'VALUE', WWORK_READONLY AS 'READONLY', 'BLANKAPPROVER' AS 'APPROVER', -1 AS 'STATUS', 'WORK' AS 'ROWTYPE'
  FROM MSP_WEB_WORK 
 WHERE WASSN_ID=(@p0)
)
UNION
(
SELECT WASSN_ID, WPRD_START_DATE AS 'START', WPRD_FINISH_DATE AS 'FINISH', 0 AS 'TYPE', 0.0 AS 'VALUE', 0 AS 'READONLY', WR.RES_NAME AS 'APPROVER', WAPPROVAL_STATUS AS 'STATUS', 'APPROVALSTATUS' AS 'ROWTYPE' 
  FROM MSP_WEB_WORK_APPROVAL WWA LEFT JOIN MSP_WEB_RESOURCES WR ON WWA.WRES_ID_APPROVER = WR.WRES_ID
 WHERE WASSN_ID = (@p0)
)
GO

GRANT EXECUTE ON dbo.MSP_PDS_GetWebWork TO MSProjectServerRole
GO


/* Query PDS017 */
CREATE PROCEDURE dbo.MSP_PDS_SetAssignmentData
   @p0  decimal,
   @p1  decimal,
   @p2  decimal,
   @p3  INT,
   @p4  INT
AS
UPDATE 	MSP_WEB_ASSIGNMENTS 
   SET 	ASSN_WORK=@p0,
	ASSN_ACT_WORK=@p1,
	ASSN_REM_WORK=@p2,
	WASSN_PCT_COMP=@p3, 
	WASSN_SEND_UPDATE_NEEDED=1,
	WASSN_UPDATE_STATUS=1 
 WHERE 	WASSN_ID = @p4
GO

GRANT EXECUTE ON dbo.MSP_PDS_SetAssignmentData TO MSProjectServerRole
GO


/* Query PDS018 */
CREATE PROCEDURE dbo.MSP_PDS_SetAssignmentComments
   @p0  NTEXT,
   @p1  INT
AS
UPDATE 	MSP_WEB_ASSIGNMENTS 
   SET	WASSN_COMMENTS = @p0,
	WASSN_NOTE_STATUS=1 
 WHERE 	WASSN_ID = @p1
GO

GRANT EXECUTE ON dbo.MSP_PDS_SetAssignmentComments TO MSProjectServerRole
GO

/* Query PDS019 */
CREATE PROCEDURE dbo.MSP_PDS_AddWebWorkEntry
	@p0   	INT, -- WebResourceID,
	@p1 	INT, -- WUID
	@p2 	datetime, -- Start
	@p3 	datetime, -- Finish
	@p4 	INT, -- WorkType
	@p5 	decimal, -- Value
	@p6 	INT -- ReadOnly
AS
INSERT INTO MSP_WEB_WORK (WRES_ID, WASSN_ID,WWORK_START, WWORK_FINISH, WWORK_TYPE, WWORK_VALUE, WWORK_READONLY, WWORK_UPDATE_STATUS) 
     VALUES ( @p0, @p1, @p2, @p3, @p4, @p5, @p6, 1) 
GO

GRANT EXECUTE ON dbo.MSP_PDS_AddWebWorkEntry TO MSProjectServerRole
GO

/* Query PDS020 */
CREATE PROCEDURE dbo.MSP_PDS_ResName2WResID
	@p0   	nvarchar(256)
AS
SELECT WRES_ID FROM MSP_WEB_RESOURCES WHERE lower(RES_NAME)=lower(@p0) -- P11/5599 (ensure name case-insensitivity)
GO

GRANT EXECUTE ON dbo.MSP_PDS_ResName2WResID TO MSProjectServerRole
GO


/* Required for Query PDS021 */
CREATE PROCEDURE dbo.MSP_PDS_SP_INSERT_WEB_ASSN
	@WProjID INTEGER,
	@ProjName NVARCHAR(200)
AS
	INSERT INTO MSP_WEB_ASSIGNMENTS (WRES_ID, WASSN_PARENT_ID, WPROJ_ID, ASSN_UID, TASK_UID, TASK_ID, TASK_UID_SUMMARY, TASK_NAME)
		VALUES (-1, -1, @WProjID, -1, 0, 0, -1, @ProjName)
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_INSERT_WEB_ASSN TO MSProjectServerRole
GO


/* Query PDS021 */
CREATE PROCEDURE dbo.MSP_PDS_SP_ProjectCreateFromTemplate
@template_proj_id int,
@new_proj_id int,
@new_proj_type int,
@new_proj_name varchar(255),
@new_proj_prefix varchar(203),
@new_proj_version varchar(50),
@new_proj_creation_date datetime,
@list_of_permissible_euids ntext,
@proj_prop_manager varchar(255),
@proj_start_date datetime = NULL
AS
BEGIN
   -- MSP_PROJECTS
   SELECT * INTO #MSP_PROJECTS FROM MSP_PROJECTS WHERE PROJ_ID = @template_proj_id

   UPDATE #MSP_PROJECTS 
     SET PROJ_ID=@new_proj_id,PROJ_NAME=@new_proj_name,PROJ_PROJECT=@new_proj_prefix,PROJ_VERSION=@new_proj_version,PROJ_PROP_TITLE=@new_proj_name,PROJ_EXT_EDITED=1,PROJ_TYPE=@new_proj_type,PROJ_CREATION_DATE_EX=@new_proj_creation_date,PROJ_LAST_SAVED=@new_proj_creation_date
     WHERE PROJ_ID = @template_proj_id

   INSERT INTO MSP_PROJECTS SELECT * FROM #MSP_PROJECTS WHERE PROJ_ID = @new_proj_id

   -- MSP_CALENDARS
   SELECT * INTO #MSP_CALENDARS FROM MSP_CALENDARS WHERE PROJ_ID = @template_proj_id

   UPDATE #MSP_CALENDARS
     SET PROJ_ID=@new_proj_id
     WHERE PROJ_ID = @template_proj_id

   INSERT INTO MSP_CALENDARS SELECT * FROM #MSP_CALENDARS WHERE PROJ_ID = @new_proj_id

   -- MSP_RESOURCES
   SELECT * INTO #MSP_RESOURCES FROM MSP_RESOURCES WHERE PROJ_ID = @template_proj_id

   UPDATE #MSP_RESOURCES
     SET PROJ_ID=@new_proj_id
     WHERE PROJ_ID = @template_proj_id

   INSERT INTO MSP_RESOURCES SELECT * FROM #MSP_RESOURCES WHERE PROJ_ID = @new_proj_id

   -- MSP_TASKS
   SELECT * INTO #MSP_TASKS FROM MSP_TASKS WHERE PROJ_ID = @template_proj_id

   UPDATE #MSP_TASKS
     SET PROJ_ID=@new_proj_id
     WHERE PROJ_ID = @template_proj_id

   INSERT INTO MSP_TASKS SELECT * FROM #MSP_TASKS WHERE PROJ_ID = @new_proj_id

   -- MSP_LINKS
   SELECT * INTO #MSP_LINKS FROM MSP_LINKS WHERE PROJ_ID = @template_proj_id

   UPDATE #MSP_LINKS
     SET PROJ_ID=@new_proj_id
     WHERE PROJ_ID = @template_proj_id

   INSERT INTO MSP_LINKS SELECT * FROM #MSP_LINKS WHERE PROJ_ID = @new_proj_id

   -- MSP_ASSIGNMENTS
   SELECT * INTO #MSP_ASSIGNMENTS FROM MSP_ASSIGNMENTS WHERE PROJ_ID = @template_proj_id

   UPDATE #MSP_ASSIGNMENTS
     SET PROJ_ID=@new_proj_id
     WHERE PROJ_ID = @template_proj_id

   INSERT INTO MSP_ASSIGNMENTS SELECT * FROM #MSP_ASSIGNMENTS WHERE PROJ_ID = @new_proj_id

   -- MSP_OUTLINE_CODES
   SELECT * INTO #MSP_OUTLINE_CODES FROM MSP_OUTLINE_CODES WHERE PROJ_ID = @template_proj_id

   UPDATE #MSP_OUTLINE_CODES
     SET PROJ_ID=@new_proj_id
     WHERE PROJ_ID = @template_proj_id

   INSERT INTO MSP_OUTLINE_CODES SELECT * FROM #MSP_OUTLINE_CODES WHERE PROJ_ID = @new_proj_id

   DROP TABLE #MSP_OUTLINE_CODES
   DROP TABLE #MSP_ASSIGNMENTS
   DROP TABLE #MSP_TASKS
   DROP TABLE #MSP_LINKS
   DROP TABLE #MSP_RESOURCES
   DROP TABLE #MSP_CALENDARS
   DROP TABLE #MSP_PROJECTS

   -- This is how we enforce both the Assign Resource object-level permission and the
   -- Build Team on New Project global-level permission in the case of ProjectCreate
   -- from template.  We change all non-permitted ent resources to local resources.  
   UPDATE MSP_RESOURCES
      SET RES_EUID = NULL
    WHERE PROJ_ID = @new_proj_id
      AND NOT ( RES_EUID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@list_of_permissible_euids)))

  -- P11/9288 - Set Project Manager and/or Start Date if they were passed in 
  if LEN(@proj_prop_manager) > 0 UPDATE MSP_PROJECTS SET PROJ_PROP_MANAGER = @proj_prop_manager WHERE PROJ_ID = @new_proj_id
  if not ( @proj_start_date IS NULL) UPDATE MSP_PROJECTS SET PROJ_INFO_START_DATE = @proj_start_date WHERE PROJ_ID = @new_proj_id

END
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_ProjectCreateFromTemplate TO MSProjectServerRole
GO


/* Query PDS022 */
CREATE PROCEDURE dbo.MSP_PDS_ProjectOutlineValues
   @outlcodepid  INT,
   @availprojlist NTEXT
AS
--Note that below, where MSP_PROJECTS.PROJ_TYPE = 2, 2 is the type for the enterprise global project
SELECT 	MSP_CODE_FIELDS.CODE_UID, MSP_OUTLINE_CODES.OC_CACHED_FULL_NAME, 
        MSP_CODE_FIELDS.PROJ_ID , MSP_PROJECTS_1.PROJ_NAME 
  FROM  MSP_PROJECTS INNER JOIN 
        MSP_OUTLINE_CODES ON MSP_PROJECTS.PROJ_ID = MSP_OUTLINE_CODES.PROJ_ID INNER JOIN 
        MSP_CODE_FIELDS ON MSP_OUTLINE_CODES.CODE_UID = MSP_CODE_FIELDS.CODE_UID INNER JOIN 
        MSP_PROJECTS MSP_PROJECTS_1 ON MSP_CODE_FIELDS.PROJ_ID = MSP_PROJECTS_1.PROJ_ID 
  WHERE (MSP_CODE_FIELDS.CODE_FIELD_ID = @outlcodepid ) 
        And (MSP_PROJECTS.PROJ_TYPE = 2) 
	And (MSP_PROJECTS_1.PROJ_ID in (select TokenVal from dbo.MSP_WEB_FN_ConvertListToTable(@availprojlist)))
  ORDER BY MSP_CODE_FIELDS.PROJ_ID ASC
GO

GRANT EXECUTE ON dbo.MSP_PDS_ProjectOutlineValues TO MSProjectServerRole
GO


/* Query PDS023 */
CREATE PROCEDURE dbo.MSP_PDS_DeleteWebWork
	@p0   	INT -- WUID
AS
DELETE 	MSP_WEB_WORK 
 WHERE 	WASSN_ID = @p0 and 
	( WWORK_TYPE = 1 or WWORK_TYPE = 2) -- 1=ActualWork, 2=OvertimeActualWork
GO

GRANT EXECUTE ON dbo.MSP_PDS_DeleteWebWork TO MSProjectServerRole
GO


/* Query PDS024 */
CREATE PROCEDURE dbo.MSP_PDS_GetNotificationsServer
AS
SELECT 	WADMIN_INTRANET_SERVER_URL as 'INTRANET', WADMIN_EXTRANET_SERVER_URL as 'EXTRANET'
  from 	MSP_WEB_ADMIN
GO

GRANT EXECUTE ON dbo.MSP_PDS_GetNotificationsServer TO MSProjectServerRole
GO

/* Query PDS025 */
CREATE PROCEDURE dbo.MSP_PDS_SP_GetPendingActuals
	@proj_id int
AS
SELECT A.WASSN_ACTUALS_PENDING, B.RES_EUID
  FROM MSP_WEB_ASSIGNMENTS A,MSP_WEB_RESOURCES B
  WHERE A.WRES_ID = B.WRES_ID AND A.WRES_ID > 0 AND A.WASSN_ACTUALS_PENDING > 0 AND A.WPROJ_ID = (SELECT WPROJ_ID FROM MSP_WEB_PROJECTS WHERE PROJ_ID = @proj_id)
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_GetPendingActuals TO MSProjectServerRole
GO

/* Query PDS026 */
CREATE FUNCTION dbo.MSP_PDS_FN_GetProject (
   @proj_type int,
   @proj_id int,
   @proj_name varchar(255),
   @proj_access_type int, -- Value from ProjectSQLAccessTypeEnum in CDataAccess.cls. 
   @proj_checkout_type int -- Value from EnsureCheckedStatusEnum in CDataAccess.cls.
)
returns int
as
begin
/* 
Here are the two VBA Enums necessary to understand where the constants below come from
Enum EnsureCheckedStatusEnum
    ecsDontCare = 0
    ecsCheckedOut = 1
    ecsCheckedIn = 2
End Enum
Enum ProjectSQLAccessTypeEnum
    psatProjectType = 0
    psatProjectName = 1
    psatProjectID = 2
    psatInvalid = 3
End Enum
*/ 
  declare @curpos int
  set @curpos = -1

  if @proj_access_type=0 -- psatProjectType = 0
    begin
	if @proj_checkout_type=1 	select @curpos=PROJ_ID from MSP_PROJECTS WHERE PROJ_TYPE=@proj_type AND PROJ_CHECKEDOUT=1 
	else if @proj_checkout_type=2 	select @curpos=PROJ_ID from MSP_PROJECTS WHERE PROJ_TYPE=@proj_type AND PROJ_CHECKEDOUT=0 
	else 				select @curpos=PROJ_ID from MSP_PROJECTS WHERE PROJ_TYPE=@proj_type 
    end
  else if @proj_access_type=1 -- psatProjectName = 1
    begin 
	if @proj_checkout_type=1 	select @curpos=PROJ_ID from MSP_PROJECTS WHERE lower(PROJ_NAME) = lower(@proj_name) AND PROJ_CHECKEDOUT=1 
	else if @proj_checkout_type=2 	select @curpos=PROJ_ID from MSP_PROJECTS WHERE lower(PROJ_NAME) = lower(@proj_name) AND PROJ_CHECKEDOUT=0 
	else 				select @curpos=PROJ_ID from MSP_PROJECTS WHERE lower(PROJ_NAME) = lower(@proj_name) 
    end
  else if @proj_access_type=2 -- psatProjectID = 2
    begin
	if @proj_checkout_type=1 	select @curpos=PROJ_ID from MSP_PROJECTS WHERE PROJ_ID=@proj_id AND PROJ_CHECKEDOUT=1 
	else if @proj_checkout_type=2 	select @curpos=PROJ_ID from MSP_PROJECTS WHERE PROJ_ID=@proj_id AND PROJ_CHECKEDOUT=0 
	else 				select @curpos=PROJ_ID from MSP_PROJECTS WHERE PROJ_ID=@proj_id  
    end

return @curpos
end
GO

GRANT EXECUTE ON dbo.MSP_PDS_FN_GetProject TO MSProjectServerRole
GO

/* Query PDS027 */
CREATE PROCEDURE dbo.MSP_PDS_SP_GetProjectCurrencyInformation
   @proj_type int,
   @proj_id int,
   @proj_name varchar(255),
   @proj_access_type int -- Value from ProjectSQLAccessTypeEnum in CDataAccess.cls. 
AS
   SELECT PROJ_OPT_CURRENCY_SYMBOL,PROJ_OPT_CURRENCY_POSITION,PROJ_OPT_CURRENCY_DIGITS 
     FROM MSP_PROJECTS 
    WHERE PROJ_ID = dbo.MSP_PDS_FN_GetProject(@proj_type, @proj_id,@proj_name,@proj_access_type,0)
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_GetProjectCurrencyInformation TO MSProjectServerRole
GO

/* Query PDS028 */
CREATE PROCEDURE dbo.MSP_PDS_SP_GetProjectInfo
   @proj_type int,
   @proj_id int,
   @proj_name varchar(255),
   @proj_access_type int -- Value from ProjectSQLAccessTypeEnum in CDataAccess.cls. 
AS
   SELECT * 
     FROM MSP_PROJECTS 
    WHERE PROJ_ID = dbo.MSP_PDS_FN_GetProject(@proj_type, @proj_id,@proj_name,@proj_access_type,0)
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_GetProjectInfo TO MSProjectServerRole
GO

/* Query PDS029 */
CREATE PROCEDURE dbo.MSP_PDS_SP_UpdateProjType
   @new_proj_type int, 
   @proj_type int,
   @proj_id int,
   @proj_name varchar(255),
   @proj_access_type int, -- Value from ProjectSQLAccessTypeEnum in CDataAccess.cls. 
   @proj_checkout_type int -- Value from EnsureCheckedStatusEnum in CDataAccess.cls.
AS
 UPDATE MSP_PROJECTS 
    SET PROJ_TYPE = @new_proj_type 
  WHERE PROJ_ID = dbo.MSP_PDS_FN_GetProject(@proj_type,@proj_id,@proj_name,@proj_access_type,@proj_checkout_type)
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_UpdateProjType TO MSProjectServerRole
GO

/* Query PDS030 */
CREATE PROCEDURE dbo.MSP_PDS_SP_ProjectCheckin
   @proj_type int,
   @proj_id int,
   @proj_name varchar(255),
   @proj_access_type int, -- Value from ProjectSQLAccessTypeEnum in CDataAccess.cls. 
   @proj_checkout_type int, -- Value from EnsureCheckedStatusEnum in CDataAccess.cls.
   @checked_out int 
AS
 UPDATE MSP_PROJECTS 
    SET PROJ_CHECKEDOUT=@checked_out
  WHERE PROJ_ID = dbo.MSP_PDS_FN_GetProject(@proj_type,@proj_id,@proj_name,@proj_access_type,@proj_checkout_type)
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_ProjectCheckin TO MSProjectServerRole
GO

/* Query PDS031 */
CREATE PROCEDURE dbo.MSP_PDS_SP_ProjectCheckout
   @proj_type int,
   @proj_id int,
   @proj_name varchar(255),
   @proj_access_type int, -- Value from ProjectSQLAccessTypeEnum in CDataAccess.cls. 
   @proj_checkout_type int, -- Value from EnsureCheckedStatusEnum in CDataAccess.cls.
   @checked_out int,
   @checked_out_by varchar(255),
   @checked_out_date DATETIME
AS
 UPDATE MSP_PROJECTS 
    SET PROJ_CHECKEDOUT=@checked_out,PROJ_CHECKOUTBY=@checked_out_by,PROJ_CHECKOUTDATE=@checked_out_date
  WHERE PROJ_ID = dbo.MSP_PDS_FN_GetProject(@proj_type,@proj_id,@proj_name,@proj_access_type,@proj_checkout_type)
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_ProjectCheckout TO MSProjectServerRole
GO

/* Query PDS032 */
CREATE PROCEDURE dbo.MSP_PDS_SP_HandleProjFlags
   @proj_type int,
   @proj_id int,
   @proj_name varchar(255),
   @proj_access_type int, -- Value from ProjectSQLAccessTypeEnum in CDataAccess.cls. 
   @proj_checkout_type int, -- Value from EnsureCheckedStatusEnum in CDataAccess.cls.
   @proj_machine_id varchar(100),
   @on_off int
AS
begin
  declare @proj int
  set @proj = dbo.MSP_PDS_FN_GetProject(@proj_type,@proj_id,@proj_name,@proj_access_type,@proj_checkout_type)
  if @on_off = 0 
   begin
   UPDATE MSP_PROJECTS 
      SET PROJ_READ_ONLY=0,PROJ_READ_WRITE=0,PROJ_READ_COUNT=0,PROJ_LOCKED=0
    WHERE PROJ_ID=@proj

   UPDATE MSP_PROJECTS 
      SET PROJ_EXT_EDITED=1
    WHERE PROJ_ID=@proj AND PROJ_LOCKED <> 0

   end
  else
   begin
   UPDATE MSP_PROJECTS 
      SET PROJ_READ_ONLY=1,PROJ_READ_WRITE=1,PROJ_READ_COUNT=1
    WHERE PROJ_ID=@proj
   end

   UPDATE MSP_PROJECTS
      SET PROJ_MACHINE_ID=@proj_machine_id
    WHERE PROJ_ID=@proj
end 
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_HandleProjFlags TO MSProjectServerRole
GO

/* Query PDS033 */
CREATE PROCEDURE dbo.MSP_PDS_SP_ProjLockUnLock
   @proj_type int,
   @proj_id int,
   @proj_name varchar(255),
   @proj_access_type int, -- Value from ProjectSQLAccessTypeEnum in CDataAccess.cls. 
   @proj_checkout_type int, -- Value from EnsureCheckedStatusEnum in CDataAccess.cls.
   @fLock tinyint -- 0 means unlock, <>0 means lock
AS
begin
   if @fLock=0 -- Unlock
     UPDATE MSP_PROJECTS 
        SET PROJ_LOCKED=1 
      WHERE PROJ_ID=dbo.MSP_PDS_FN_GetProject(@proj_type,@proj_id,@proj_name,@proj_access_type,@proj_checkout_type) 
	AND PROJ_LOCKED = 0
   else -- Lock
     UPDATE MSP_PROJECTS 
        SET PROJ_LOCKED=0 
      WHERE PROJ_ID=dbo.MSP_PDS_FN_GetProject(@proj_type,@proj_id,@proj_name,@proj_access_type,@proj_checkout_type) 
	AND PROJ_LOCKED <> 0
end 
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_ProjLockUnLock TO MSProjectServerRole
GO

/* Query PDS034 */
CREATE PROCEDURE dbo.MSP_PDS_SP_SetSavedDate
   @proj_type int,
   @proj_id int,
   @proj_name varchar(255),
   @proj_access_type int, -- Value from ProjectSQLAccessTypeEnum in CDataAccess.cls. 
   @proj_checkout_type int, -- Value from EnsureCheckedStatusEnum in CDataAccess.cls.
   @proj_last_saved DATETIME
AS
begin
     UPDATE MSP_PROJECTS 
        SET PROJ_LAST_SAVED=@proj_last_saved
      WHERE PROJ_ID=dbo.MSP_PDS_FN_GetProject(@proj_type,@proj_id,@proj_name,@proj_access_type,@proj_checkout_type) 
end 
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_SetSavedDate TO MSProjectServerRole
GO

/* Query PDS035 */
CREATE PROCEDURE dbo.MSP_PDS_SetProjectExternalEditFlag
   @proj_id int,
   @last_saved_date DATETIME = 0, -- used to set MSP_PROJECTS.LAST_SAVED_DATE (p11/5176)
   @other_ext_edited_field varchar(50) = N'' -- Used to specify another field to set also (eg: PROJ_EXT_EDITED_CODE) (p11/5176)
AS
begin
 UPDATE MSP_PROJECTS 
    SET PROJ_EXT_EDITED=1
  WHERE PROJ_ID=@proj_id

 if @last_saved_date <> 0 
   begin
     UPDATE MSP_PROJECTS 
        SET PROJ_LAST_SAVED = @last_saved_date
      WHERE PROJ_ID=@proj_id
   end

 if 0 < LEN(@other_ext_edited_field) AND LEN(@other_ext_edited_field) < 1000 
   begin
     declare @sql_query  nvarchar(4000)
     set @sql_query = N'UPDATE MSP_PROJECTS SET ' + @other_ext_edited_field + ' = 1 WHERE PROJ_ID = ' + CAST(@proj_id AS char(100)) 
     exec sp_executesql @sql_query
   end
end 
GO

GRANT EXECUTE ON dbo.MSP_PDS_SetProjectExternalEditFlag TO MSProjectServerRole
GO

/* Query PDS036 */
CREATE PROCEDURE dbo.MSP_PDS_SP_DetermineWUIDExistance
   @wuid int
AS
begin
   SELECT WASSN_ID
     FROM MSP_WEB_ASSIGNMENTS
    WHERE WASSN_ID=@wuid
end 
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_DetermineWUIDExistance TO MSProjectServerRole
GO

/* Query PDS037 */
CREATE PROCEDURE dbo.MSP_PDS_SP_GetLookAhead
AS
begin
   SELECT WADMIN_LOOKAHEAD
     FROM MSP_WEB_ADMIN
end 
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_GetLookAhead TO MSProjectServerRole
GO

/* Query PDS038 */
CREATE PROCEDURE dbo.MSP_PDS_SP_CLEANUP
	@ProjID INTEGER
AS
	DELETE FROM MSP_PROJECTS WHERE PROJ_ID = @ProjID	
	DELETE FROM MSP_TASKS WHERE PROJ_ID = @ProjID
	DELETE FROM MSP_RESOURCES WHERE PROJ_ID = @ProjID
	DELETE FROM MSP_ASSIGNMENTS WHERE PROJ_ID = @ProjID
	DELETE FROM MSP_CALENDARS WHERE PROJ_ID = @ProjID
	DELETE FROM MSP_OUTLINE_CODES WHERE PROJ_ID = @ProjID
	DELETE FROM MSP_TEXT_FIELDS WHERE PROJ_ID = @ProjID
	DELETE FROM MSP_NUMBER_FIELDS WHERE PROJ_ID = @ProjID
	DELETE FROM MSP_FIELD_ATTRIBUTES WHERE PROJ_ID = @ProjID
	DELETE FROM MSP_ATTRIBUTE_STRINGS WHERE PROJ_ID = @ProjID
	DELETE FROM MSP_WEB_PROJECTS WHERE PROJ_ID = @ProjID
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_CLEANUP TO MSProjectServerRole
GO


/* Query PDS039 */
CREATE PROCEDURE dbo.MSP_PDS_SP_INSERT_TASK_MIN
	@ProjID INTEGER
AS
	DECLARE @ReturnCode INT
INSERT MSP_TASKS (PROJ_ID, TASK_UID) VALUES (@ProjID, -65536);
INSERT MSP_TASKS (PROJ_ID, TASK_UID) VALUES (@ProjID, -65535);
INSERT MSP_TASKS (PROJ_ID, TASK_UID) VALUES (@ProjID, -65534);
INSERT MSP_TASKS (PROJ_ID, TASK_UID, TASK_ID) VALUES (@ProjID, 0, 0);
	SELECT @ReturnCode = 1
	RETURN @ReturnCode
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_INSERT_TASK_MIN TO MSProjectServerRole
GO

/* Query PDS040 */
CREATE PROCEDURE dbo.MSP_PDS_SP_INSERT_RESOURCE_MIN
	@ProjID INTEGER
AS
	DECLARE @ReturnCode INT
INSERT MSP_RESOURCES (PROJ_ID, RES_UID) VALUES (@ProjID, -65536);
INSERT MSP_RESOURCES (PROJ_ID, RES_UID) VALUES (@ProjID, -65535);
INSERT MSP_RESOURCES (PROJ_ID, RES_UID) VALUES (@ProjID, -65534);
INSERT MSP_RESOURCES (PROJ_ID, RES_UID, RES_ID) VALUES (@ProjID, 0, 0);
	SELECT @ReturnCode = 1
	RETURN @ReturnCode
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_INSERT_RESOURCE_MIN TO MSProjectServerRole
GO

/* Query PDS041 */
CREATE PROCEDURE dbo.MSP_PDS_SP_INSERT_OUTLINE_CODE_MIN
	@ProjID INTEGER
AS
	DECLARE @ReturnCode INT
INSERT MSP_OUTLINE_CODES (PROJ_ID, CODE_UID) VALUES (@ProjID, -65536);
INSERT MSP_OUTLINE_CODES (PROJ_ID, CODE_UID) VALUES (@ProjID, -65535);
INSERT MSP_OUTLINE_CODES (PROJ_ID, CODE_UID) VALUES (@ProjID, -65534);
INSERT MSP_OUTLINE_CODES (PROJ_ID, CODE_UID) VALUES (@ProjID, 0);
	SELECT @ReturnCode = 1
	RETURN @ReturnCode
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_INSERT_OUTLINE_CODE_MIN TO MSProjectServerRole
GO

/* Query PDS042 */
CREATE PROCEDURE dbo.MSP_PDS_SP_INSERT_CALENDAR_MIN
	@ProjID INTEGER
AS
	DECLARE @ReturnCode INT
INSERT MSP_CALENDARS (PROJ_ID, CAL_UID) VALUES (@ProjID, -65536);
INSERT MSP_CALENDARS (PROJ_ID, CAL_UID) VALUES (@ProjID, -65535);
INSERT MSP_CALENDARS (PROJ_ID, CAL_UID) VALUES (@ProjID, -65534);
INSERT MSP_CALENDARS (PROJ_ID, CAL_UID) VALUES (@ProjID, -65533);

-- P11 3614 - We need to add a row for the Standard calendar, otherwise we get
-- a Standard and a Standard1 calendar in the project once opened in Winproj. 
-- First, get the name of the Standard calendar from the global
DECLARE @STANDARDCALNAME VARCHAR(256)
SET @STANDARDCALNAME = ''
SELECT @STANDARDCALNAME = PROJ_INFO_CAL_NAME 
  FROM MSP_PROJECTS 
 WHERE PROJ_TYPE = 2 -- global type

-- We also need to get the EUID of the Standard calendar
DECLARE @STANDARDCALEUID INT
SET @STANDARDCALEUID = -1
SELECT @STANDARDCALEUID = C.CAL_ENTUID 
  FROM MSP_CALENDARS C INNER JOIN MSP_PROJECTS P ON C.PROJ_ID = P.PROJ_ID
 WHERE P.PROJ_TYPE = 2
   AND LOWER(C.CAL_NAME) = LOWER(@STANDARDCALNAME)

-- Set the Standard calendar name on the new project
UPDATE MSP_PROJECTS
   SET PROJ_INFO_CAL_NAME = @STANDARDCALNAME
 WHERE PROJ_ID = @ProjID

-- Insert a row in the new project's calendar container for the Standard calendar
INSERT INTO MSP_CALENDARS ( PROJ_ID, CAL_UID, CAL_BASE_UID, RES_UID, CAL_IS_BASE_CAL, CAL_NAME, CAL_ENTUID)
                   VALUES ( @ProjID,       1,           -1,      -1,               1, @STANDARDCALNAME, @STANDARDCALEUID)

	SELECT @ReturnCode = 1
	RETURN @ReturnCode
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_INSERT_CALENDAR_MIN TO MSProjectServerRole
GO

/* Query PDS043 */
CREATE PROCEDURE dbo.MSP_PDS_SP_ResourceAssignmentForTask
	@proj_id int,
	@task_uid int,
	@res_uid int,
	@task_dur int output, -- P11/3125 - we need to find out the task's duration
	@assn_exists int output -- returns whether the assignment already exists
AS
BEGIN
  SET @task_dur = -1 -- initialize
  SELECT @task_dur = TASK_DUR 
    FROM MSP_TASKS 
   WHERE PROJ_ID = @proj_id 
     AND TASK_UID = @task_uid

  -- P11/3125 - If the task has no assignments, then we need to delete the task's placeholder 
  -- assignment to the unassigned resource. 
  DECLARE @assn_count INT
  SET @assn_count = -1
  SELECT @assn_count = COUNT(*) 
    FROM MSP_ASSIGNMENTS 
   WHERE PROJ_ID = @proj_id 
     AND TASK_UID = @task_uid
     AND RES_UID <> -65535 -- unassigned resource's UID
  IF @assn_count < 1 
    BEGIN
      DELETE FROM MSP_ASSIGNMENTS 
            WHERE TASK_UID = @task_uid
              AND PROJ_ID = @proj_id
              AND RES_UID = -65535 -- unassigned resource's UID
    END

  -- Now we actually want to return some data to the caller
  set @assn_exists = 1
  SELECT @assn_exists = COUNT(*) 
    FROM MSP_ASSIGNMENTS 
   WHERE PROJ_ID = @proj_id
     AND TASK_UID = @task_uid
     AND RES_UID = @res_uid
	
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_ResourceAssignmentForTask TO MSProjectServerRole
GO


/* Query PDS044 */
CREATE PROCEDURE dbo.MSP_PDS_SP_BumpResourceIDsForProject
	@proj_id int,
	@res_id int
AS
BEGIN
	UPDATE MSP_RESOURCES 
	   SET RES_ID=RES_ID+1,EXT_EDIT_REF_DATA=N'1' 
	 WHERE PROJ_ID = @proj_id AND RES_ID >= @res_id
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_BumpResourceIDsForProject TO MSProjectServerRole
GO

/* Query PDS045 */
CREATE PROCEDURE dbo.MSP_PDS_SP_GetAdminProtectActuals
AS
begin
   SELECT WADMIN_PROTECT_ACTUALS
     FROM MSP_WEB_ADMIN
end 
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_GetAdminProtectActuals TO MSProjectServerRole
GO

/* Query PDS046 */
CREATE PROCEDURE dbo.MSP_PDS_SP_GetClosedPeriods
   @start_actuals DATETIME,
   @finish_actuals DATETIME
AS
begin
 SELECT WPRD_START_DATE, WPRD_FINISH_DATE
   FROM MSP_WEB_TIME_PERIODS 
  WHERE WPRD_STATE=1 -- Means closed
    AND (((@start_actuals <= WPRD_START_DATE) and (WPRD_START_DATE <= @finish_actuals)) or
 	     ((@start_actuals <= WPRD_FINISH_DATE) and (WPRD_FINISH_DATE <= @finish_actuals)) or 
	     ((WPRD_START_DATE <= @start_actuals) and (@finish_actuals <= WPRD_FINISH_DATE)))
  ORDER BY WPRD_START_DATE
end 
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_GetClosedPeriods TO MSProjectServerRole
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/* Query PDS047 */
CREATE PROCEDURE dbo.MSP_PDS_SP_BumpTaskIDsForProject
	@proj_id int,
	@task_id int
AS
BEGIN
	UPDATE MSP_TASKS 
	   SET TASK_ID=TASK_ID+1 
	 WHERE PROJ_ID = @proj_id AND TASK_ID >= @task_id
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_BumpTaskIDsForProject TO MSProjectServerRole
GO

/* Query PDS048 */
CREATE PROCEDURE dbo.MSP_PDS_SP_WriteAssnLog
   @wassn_id integer,
   @wwork_date DATETIME, 
   @wwork_type integer,
   @wwork_value decimal,
   @wwork_value_adjusted decimal,
   @wwork_adjust_date DATETIME,
   @wres_id integer
AS
begin
 -- Note that WADJUST_ID is automatically created
insert MSP_WEB_WORK_ADJUSTED ( WASSN_ID, WWORK_DATE, WWORK_TYPE, WWORK_VALUE, WWORK_VALUE_ADJUSTED, WWORK_ADJUST_DATE, WRES_ID)
	              VALUES (@wassn_id,@wwork_date,@wwork_type,@wwork_value,@wwork_value_adjusted,@wwork_adjust_date,@wres_id)
end 
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_WriteAssnLog TO MSProjectServerRole
GO

/* Query PDS049 */
CREATE PROCEDURE dbo.MSP_PDS_SetExtEditRefDataOnResource
	@proj_id integer,
	@res_uid integer
AS
UPDATE MSP_RESOURCES SET EXT_EDIT_REF_DATA=N'1' where PROJ_ID=@proj_id AND RES_UID=@res_uid
GO

GRANT EXECUTE ON dbo.MSP_PDS_SetExtEditRefDataOnResource TO MSProjectServerRole
GO

/* Query PDS050 */
CREATE PROCEDURE dbo.MSP_PDS_SetExtEditRefDataAndWBSOnTask
	@proj_id integer,
	@task_uid integer,
	@wbs ntext
AS
 UPDATE MSP_TASKS 
    SET EXT_EDIT_REF_DATA=N'1', TASK_WBS=@wbs 
  WHERE PROJ_ID=@proj_id AND TASK_UID=@task_uid
GO

GRANT EXECUTE ON dbo.MSP_PDS_SetExtEditRefDataAndWBSOnTask TO MSProjectServerRole
GO

/* Query PDS051 */
CREATE PROCEDURE dbo.MSP_PDS_SetExtEditRefDataOnLink
	@proj_id integer,
	@link_uid integer
AS
 UPDATE MSP_LINKS 
    SET EXT_EDIT_REF_DATA=N'1' 
  WHERE PROJ_ID=@proj_id AND LINK_UID=@link_uid
GO

GRANT EXECUTE ON dbo.MSP_PDS_SetExtEditRefDataOnLink TO MSProjectServerRole
GO

/* Query PDS052 */
CREATE PROCEDURE dbo.MSP_PDS_SP_SetWebStartAndFinishDate
	@start DATETIME,
	@finish DATETIME,
	@wproj_id integer
AS
 UPDATE	MSP_WEB_ASSIGNMENTS
    SET ASSN_START_DATE=@start, ASSN_FINISH_DATE=@finish
  WHERE WPROJ_ID=@wproj_id
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_SetWebStartAndFinishDate TO MSProjectServerRole
GO

/* Query PDS053 */
CREATE PROCEDURE dbo.MSP_PDS_SetExtEditRefDataOnAssn
	@proj_id integer,
	@assn_uid integer
AS
 UPDATE MSP_ASSIGNMENTS 
    SET EXT_EDIT_REF_DATA=N'1' 
  WHERE PROJ_ID=@proj_id AND ASSN_UID=@assn_uid
GO

GRANT EXECUTE ON dbo.MSP_PDS_SetExtEditRefDataOnAssn TO MSProjectServerRole
GO

/* Query PDS054 */
CREATE PROCEDURE dbo.MSP_PDS_ResourcesCheckout
   @checkoutby varchar(255),
   @checkoutdate DATETIME,
   @res_euid INTEGER
AS
BEGIN
  DECLARE @resglobal_proj_id INT
  SELECT @resglobal_proj_id=PROJ_ID FROM MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE) WHERE PROJ_TYPE=3 

  -- We need to check for multiple resource globals, and throw an error if there are many (P11/4486)
  DECLARE @resglobalcount INT
  SELECT @resglobalcount = count(*) FROM MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE) WHERE PROJ_TYPE=3 
  IF (@resglobalcount > 1) 
    BEGIN
      RAISERROR ('Multiple Resglobals', 16, 1)
      RETURN
    END

  -- We need to copy the RBS value from the web security tables to the MSP_CODE_FIELDS table.  This
  -- ensures that a normal user with Manage Users and Groups permissions does not unknowningly 
  -- commit a hacker's previous changes, which stuck in MSP_CODE_FIELDS but not the web security tables.
  declare @rbs_uid INT
  set @rbs_uid = -1 
  select @rbs_uid = WRES_RBS_UID FROM MSP_WEB_RESOURCES WHERE RES_EUID = @res_euid
  if @rbs_uid > 0
    begin
     update MSP_CODE_FIELDS 
        set CODE_UID = @rbs_uid
      where PROJ_ID = @resglobal_proj_id
        and CODE_REF_UID = @res_euid
        and CODE_FIELD_ID = 205521540 -- RBS
    end
  else -- There is no entry in the web security tables, so there should be no entry in MSP_CODE_FIELDS
    begin 
     delete from MSP_CODE_FIELDS
      where PROJ_ID = @resglobal_proj_id
        and CODE_REF_UID = @res_euid
        and CODE_FIELD_ID = 205521540 -- RBS
    end
    
 UPDATE MSP_RESOURCES 
    SET RES_CHECKEDOUT=1,RES_CHECKOUTBY=@checkoutby,RES_CHECKOUTDATE=@checkoutdate,RES_ENTERPRISE_TIMESTAMP=NULL
  WHERE RES_CHECKEDOUT=0 
    AND @resglobal_proj_id=PROJ_ID 
    AND RES_UID=@res_euid

RETURN @@ROWCOUNT
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_ResourcesCheckout TO MSProjectServerRole
GO

/* Query PDS055 */
CREATE PROCEDURE dbo.MSP_PDS_ProjectsCheckout
   @checkoutby varchar(255),
   @checkoutdate DATETIME,
   @proj_id INTEGER
AS
BEGIN
  -- We need to check for multiple enterprise globals, and throw an error if there are many
  DECLARE @@globalcount INT
  SELECT @@globalcount = count(*) FROM MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE) WHERE PROJ_TYPE=2
  IF (@@globalcount > 1) 
    BEGIN
      RAISERROR ('Multiple Globals', 16, 1)
      RETURN
    END

  -- We need to check for multiple resource globals, and throw an error if there are many (P11/4642)
  DECLARE @resglobalcount INT
  SELECT @resglobalcount = count(*) FROM MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE) WHERE PROJ_TYPE=3 
  IF (@resglobalcount > 1) 
    BEGIN
      RAISERROR ('Multiple Resglobals', 16, 1)
      RETURN
    END
    
 UPDATE MSP_PROJECTS 
    SET PROJ_CHECKEDOUT=1,PROJ_CHECKOUTBY=@checkoutby,PROJ_CHECKOUTDATE=@checkoutdate
  WHERE PROJ_CHECKEDOUT=0 
    AND PROJ_ID=@proj_id

RETURN
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_ProjectsCheckout TO MSProjectServerRole
GO

/* Query PDS056 */
CREATE PROCEDURE dbo.MSP_PDS_ProjectAccessGrant
   @sec_spid SMALLINT,
   @sec_spiddatestamp DATETIME,
   @bwriteaccess TINYINT,
   @proj_id INTEGER
AS
BEGIN
  -- We need to check for multiple enterprise globals, and throw an error if there are many
  DECLARE @@globalcount INT
  SELECT @@globalcount = count(*) FROM MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE) WHERE PROJ_TYPE=2
  IF (@@globalcount > 1) 
    BEGIN
      RAISERROR ('Multiple Globals', 16, 1)
      RETURN
    END

  -- We need to check for multiple resource globals, and throw an error if there are many
  DECLARE @resglobalcount INT
  SELECT @resglobalcount = count(*) FROM MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE) WHERE PROJ_TYPE=3
  IF (@resglobalcount > 1) 
    BEGIN
      RAISERROR ('Multiple Resglobals', 16, 1)
      RETURN
    END

  -- Check to see if we are dealing with the resglobal
  DECLARE @resglobalid INTEGER
  SELECT @resglobalid = PROJ_ID FROM MSP_PROJECTS WITH (INDEX=I_MSP_PROJECTS_PROJ_TYPE) WHERE PROJ_TYPE=3

  -- If we're dealing with the resglobal, then we are trying to add a new resource.  
  -- WRITE ACCESS - we need to give the user access to write resources and calendars with UID
  --    greater than the current MAX UIDs. We add the MAX UID's to the table for the SQL views to use.
  -- READ ACCESS - we need to give the user access to read the max resource and it's calendar 
  --    and the max calendar and it's resource.  Project needs this information in order to avoid
  --    duplicating the UID's.  To avoid backwards compatibility issues we need to open those 
  --    resources and calendars in winproj.  We add those UID's to the table for the SQL views to use.
  IF @resglobalid = @proj_id
    BEGIN

      -- Remove all the old entries from MSP_RESGLOBAL_SECURITY before we repopulate it
      DELETE FROM MSP_RESGLOBAL_SECURITY

      -- Get the MAX RES UID and it's calendar and add it to the table
      DECLARE @maxresuid as INTEGER
      DECLARE @matchingcaluid as INTEGER
      set @maxresuid = -1
      set @matchingcaluid = -1
      SELECT @maxresuid = MAX(RES_UID) FROM MSP_RESOURCES WHERE PROJ_ID=@proj_id
      SELECT @matchingcaluid = RES_CAL_UID FROM MSP_RESOURCES WHERE PROJ_ID=@proj_id AND RES_UID=@maxresuid
      INSERT INTO MSP_RESGLOBAL_SECURITY (SEC_RES_UID,SEC_CAL_UID) VALUES(@maxresuid,@matchingcaluid)

      -- Get the MAX CAL UID and it's resource and insert them into the
      -- table if they are different than the MAX RES UID and it's calendar
      DECLARE @maxcaluid as INTEGER
      DECLARE @matchingresuid as INTEGER
      set @maxcaluid = -1
      set @matchingresuid = -1
      SELECT @maxcaluid = MAX(CAL_UID) FROM MSP_CALENDARS WHERE PROJ_ID=@proj_id
      IF @maxcaluid <> @matchingcaluid
        BEGIN
          SELECT @matchingresuid = RES_UID FROM MSP_CALENDARS WHERE PROJ_ID=@proj_id AND CAL_UID=@maxcaluid
          INSERT INTO MSP_RESGLOBAL_SECURITY (SEC_RES_UID,SEC_CAL_UID) 
          VALUES(@matchingresuid,@maxcaluid)
        END

    END


  -- If we got this far, then we perform the actual update
  IF @bwriteaccess <> 0
    BEGIN
      INSERT INTO MSP_PROJ_SECURITY (SEC_SPID,SEC_SPIDDATESTAMP,SEC_READCOUNT,SEC_WRITECOUNT,PROJ_ID) 
      VALUES(@sec_spid,@sec_spiddatestamp,0,1,@proj_id)
    END
  ELSE -- IE: not write access but read-only access
    BEGIN
      INSERT INTO MSP_PROJ_SECURITY (SEC_SPID,SEC_SPIDDATESTAMP,SEC_READCOUNT,SEC_WRITECOUNT,PROJ_ID) 
      VALUES(@sec_spid,@sec_spiddatestamp,1,0,@proj_id)
    END

RETURN
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_ProjectAccessGrant TO MSProjectServerRole
GO

/* Query PDS057 */
CREATE PROCEDURE dbo.MSP_PDS_SecurityCheckRBSandNTValue
   @res_euid INT, -- EUID of the resource in question
   @calling_userid INT, -- WRES_ID of the user calling the PDS
   @candidate_rbs INT, -- the RBS the calling user is currently attempting to set on the resource
   @candidate_nt nvarchar(510), -- the NT account the calling user is currently attempting to set on the resource
   @res_name nvarchar(255) -- the name of the resource we are checking on
AS
BEGIN
-- RETURNS 1 for success
-- RETURNS -1 for invalid RBS
-- RETURNS -2 for invalid NT account

-- RULES FOR RBS VALIDITY.  If Manage Users and Groups is not present, an RBS value is valid if it is:
-- 1) Blank 
-- 2) The RBS value of the User herself
-- 2') A descendant of the RBS value of the user herself
-- 3) The RBS value that existed on the resource on open 
-- 3') A descendant of the RBS value that existed on the resource on open

  if @candidate_rbs > 0 -- Case (1) above
    begin
      -- Get the calling user's RBS value (if any)

      declare @users_rbs INT 
      set @users_rbs = -1 -- We need to handle no RBS alright
      SELECT @users_rbs = WRES_RBS_UID
        FROM MSP_WEB_RESOURCES
       WHERE WRES_ID = @calling_userid

      -- Get the resource's current RBS value (if any)
      declare @res_curr_rbs INT
      set @res_curr_rbs = -1 -- RBS might not yet be there
      SELECT @res_curr_rbs = WRES_RBS_UID 
        FROM MSP_WEB_RESOURCES 
       WHERE @res_euid = RES_EUID

      -- If neither the calling user or the resource have a RBS value, then the new value is clearly invalid
      if (@users_rbs < 1) and (@res_curr_rbs < 1) 
        begin
          return -1
        end

      -- Run @candidate_rbs all the way up its ancestors until we either meet the @current_rbs
      --    or @users_rbs (means valid), or we reach the top of the tree (means invalid).  
      declare @cnt int
      set @cnt = 0
      while ( @cnt < 260 ) -- @cnt avoids infinite loops.  255 is the max number of outlcode levels
        begin

           if @candidate_rbs < 1 -- then we have run to the top of the tree without finding either
             begin
               return -1
             end
           else if (@candidate_rbs = @users_rbs) or (@candidate_rbs = @res_curr_rbs) -- (2) (2') or (3) (3') above
             begin
               goto valid_rbs
             end

           -- set candidate_rbs to the next-highest level
           select @candidate_rbs=OC_PARENT 
             from MSP_OUTLINE_CODES OC, MSP_PROJECTS P
            where @candidate_rbs = OC.CODE_UID and 
                  OC.PROJ_ID = P.PROJ_ID and
                  P.PROJ_TYPE = 2 -- ent global is proj type 2

           -- increment the infinite-loop guard
           set @cnt = (@cnt+1)
        end
        return -1  -- If we are here, we ran over the infinite loop
    end
valid_rbs: -- If we are here, then the RBS was value, so we want to check the NT account
 
  -- First, make sure that there is only one web resource specified by the EUID and name
  declare @count_check int
  SELECT @count_check = count(*)
    FROM MSP_WEB_RESOURCES
   WHERE RES_EUID = @res_euid 
      OR lower(RES_NAME) = lower(@res_name)	-- P11/5599 (ensure name case-insensitivity)

  if @count_check > 1 -- p11/5395 p11/5182
    return -2 -- Something went quite wrong

  declare @users_nt nvarchar(510)
  set @users_nt = ''
  SELECT @users_nt = WRES_NT_ACCOUNT
    FROM MSP_WEB_RESOURCES
   WHERE RES_EUID = @res_euid 
      OR lower(RES_NAME) = lower(@res_name)	-- P11/5599 (ensure name case-insensitivity)

  if LOWER(@users_nt) = LOWER(@candidate_nt)
    return 1
  else 
    return -2
end
GO

GRANT EXECUTE ON dbo.MSP_PDS_SecurityCheckRBSandNTValue TO MSProjectServerRole
GO

/* Query PDS058 */
CREATE PROCEDURE dbo.MSP_PDS_ResourceCheckin -- Handles ResourcesCheckin and ResourcesNew (which is very similar)
   @res_euid INT  , -- EUID of resource being checked in
   @calling_wresid INT, -- WRES_ID of the user calling the PDS
   @fHasMUG INT, -- Whether the calling user has Manage Users and Groups Permissions
   @res_global_id INT,
   @ent_timestamp DATETIME, 
   @new_rbs INT = -1 OUTPUT , -- This will be used to return the RBS value
   @curr_time DATETIME = 0, -- equals now, not used for resourcescheckin
   @res_new INT = 0, -- equals 0 iff calling resourcescheckin.  equals 1 iff calling for resourcesnew
   @calling_user varchar(255) = NULL 
AS
BEGIN
  -- PLEASE NOTE: Setting this is a workaround for the following KB article:
  -- PRB: ADO Errors Collection Does Not Contain User-Defined Error Messages (254304)
  set NOCOUNT ON 

  -- We actually want to perform the checkin or resourcenew before performing the validity checks
  -- because we don't want to truly fail the save because of failing the validity checks
  declare @ret_val INT
    if 0 = @res_new 
     begin -- Then we are calling ResourcesCheckin
       UPDATE MSP_RESOURCES 
          SET RES_CHECKEDOUT=0, RES_ENTERPRISE_TIMESTAMP = @ent_timestamp
        WHERE PROJ_ID = @res_global_id 
   	   AND RES_CHECKEDOUT=1 -- only check in checked-out resources (detects concurrency issues)
           AND RES_UID = @res_euid 
     end
   else -- Then we are calling ResourcesNew and have a bit more to set
     begin 
       UPDATE MSP_RESOURCES 
          SET RES_CHECKEDOUT=0,   
              RES_CHECKOUTBY=@calling_user,
              RES_CHECKOUTDATE=@curr_time,
	      RES_ENTERPRISE_TIMESTAMP=@ent_timestamp
        WHERE PROJ_ID = @res_global_id 
           AND RES_UID = @res_euid 
     end  
   set @ret_val = @@rowcount

   -- Get the RBS value in the Winproj-written table (MSP_CODE_VALUES)
   declare @candidate_rbs INT
   set @candidate_rbs = -1 -- Default value if there is no RBS set on the resource
   SELECT @candidate_rbs = CODE_UID
     FROM MSP_CODE_FIELDS
    WHERE PROJ_ID = @res_global_id
          AND CODE_FIELD_ID = 205521540 -- RBS
          AND CODE_REF_UID = @res_euid

   -- We need to return this value
   set @new_rbs = @candidate_rbs

   if 0 = @fHasMUG -- If user does not have Manage Users and Groups, we need to check RBS and NT validity
     begin  
       -- Get the NT value in the Winproj written table (MSP_TEXT_FIELDS)
       declare @candidate_nt varchar(510)
       set @candidate_nt = ''
       SELECT @candidate_nt = TEXT_VALUE
         FROM MSP_TEXT_FIELDS
        WHERE PROJ_ID = @res_global_id
          AND TEXT_REF_UID = @res_euid
          AND TEXT_CATEGORY = 1 -- 1 for resource
          AND TEXT_FIELD_ID = 205521207 -- NT Account
  
       -- Get the User name value from the Winproj written table (MSP_RESOURCES)
       declare @res_name nvarchar(255) 
       set @res_name = ''
       SELECT @res_name = RES_NAME
         FROM MSP_RESOURCES
        WHERE PROJ_ID = @res_global_id
          AND RES_UID = @res_euid

       declare @ValidityCode INT
       set @ValidityCode = -1
       EXEC @ValidityCode = MSP_PDS_SecurityCheckRBSandNTValue @res_euid, @calling_wresid, @candidate_rbs, @candidate_nt, @res_name
       if -1 = @ValidityCode -- RBS set in MSP_CODE_FIELDS is invalid
         begin
           RAISERROR ('Invalid RBS', 16, 1)
           RETURN 0
         end
       else if -2 = @ValidityCode 
         begin
           RAISERROR ('Invalid NT Account', 16, 1)
           RETURN 0
         end
       else if 1 <> @ValidityCode
         begin
           RAISERROR ('Invalid MSP_PDS_SecurityCheckRBSandNTValue',16,1)
	   RETURN 0
 	 end
     end        

   -- If it is valid, copy over the new RBS value to the web security tables   
   UPDATE MSP_WEB_RESOURCES
      SET WRES_RBS_UID = @candidate_rbs
    WHERE @res_euid = RES_EUID  
    
  return @ret_val -- We return the number of rows affected by the checkin/resourcesnew statement */
end
GO

GRANT EXECUTE ON dbo.MSP_PDS_ResourceCheckin TO MSProjectServerRole
GO

/* Query PDS059 */
CREATE PROCEDURE dbo.MSP_PDS_UpdateRBSUIDs
   @euid_rbs_pairs NTEXT
AS
BEGIN
   UPDATE WR
      SET WRES_RBS_UID = PAIRS.Y
     FROM MSP_WEB_RESOURCES WR INNER JOIN MSP_WEB_FN_ConvertPairListToPairTable(@euid_rbs_pairs) PAIRS ON WR.RES_EUID = PAIRS.X
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_UpdateRBSUIDs TO MSProjectServerRole
GO

/* Query PDS060 */
CREATE PROCEDURE dbo.MSP_PDS_ResourceDelete
   @res_euid INT,
   @new_local_name varchar(255) -- All instances where the fated resource is a team member will be renamed to this
AS
BEGIN

   -- Get the resglobal's Proj ID, as we will be using it a lot
   declare @res_global_id INT 
   select @res_global_id = PROJ_ID FROM MSP_PROJECTS WHERE PROJ_TYPE=3

   -- Check whether the resource is already checked out to a user
   -- Please note that the spec says we should return an error if the resource is checked out,
   -- implicitly meaning we still return an error if it is checked out to the current user. 
   declare @checked_out INT
   set @checked_out = -1
   select @checked_out = RES_CHECKEDOUT from MSP_RESOURCES WHERE PROJ_ID = @res_global_id and RES_UID = @res_euid
   if 0 <> @checked_out 
     begin
       RAISERROR ('Resource Checked Out', 16, 1) -- We will want to return rsResourceCannotDeleteWhenCheckedout for this
       RETURN 0
     end
   
   -- Unlike the P10 SDK Extension, we don't care if the resource is already deactivated.  We simply delete it. 

   -- We need to ensure that no other user has projects checked out that contain the resource we want to delete.
   declare @proj_checkout_count INT    
   SELECT @proj_checkout_count = COUNT(*) 
     FROM MSP_RESOURCES R INNER JOIN MSP_PROJECTS P ON R.PROJ_ID = P.PROJ_ID
    WHERE P.PROJ_CHECKEDOUT <> 0
      AND R.RES_EUID = @res_euid
      AND P.PROJ_TYPE <> 3 -- P11/8706 - We now actually REQUIRE that the resglobal be checked out for PDS ResourcesDelete
   if 0 < @proj_checkout_count 
     begin
       RAISERROR ('Containing Project Checked Out', 16, 1) -- We will want to return rsResourceContainingProjectCheckedOut for this
       RETURN 0
     end

   -- Delete the resource from the res global binary table 
   DELETE FROM MSP_RES_GLOBAL_BINARY -- sp_help MSP_RES_GLOBAL_BINARY
    WHERE PROJ_ID = @res_global_id
      AND GLB_CATEGORY = 1 -- 1 is for resource
      AND GLB_REF_UID = @res_euid

   -- Delete the resource's calendar from the res global binary table
   DELETE MSP_RES_GLOBAL_BINARY
     FROM MSP_RES_GLOBAL_BINARY RGB INNER JOIN MSP_CALENDARS C ON C.CAL_UID = RGB.GLB_REF_UID
    WHERE RGB.PROJ_ID = @res_global_id
      AND C.PROJ_ID = @res_global_id
      AND C.RES_UID = @res_euid
      AND RGB.GLB_CATEGORY = 2 -- 2 is for calendar data

   -- NOTE: The following set of 2 calls is NOT in the SDK article, which seems to be incomplete.
   -- This call deletes the summary resource assignments for the resource.  We could 
   -- leave them in and nothing would ever be noticable thru the UI, but for corporations that
   -- regularly refresh resource data via connector, this could make the resglobal huge thereby
   -- taking up a lot of space and potentially slowing down resglobal functions (eg: TeamBuilder load)
   DELETE MSP_RES_GLOBAL_BINARY 
     FROM MSP_RES_GLOBAL_BINARY RGB INNER JOIN MSP_RESOURCES R ON RGB.GLB_REF_ENT_PROJ_ID = R.PROJ_ID
    WHERE RGB.PROJ_ID = @res_global_id
      AND RGB.GLB_REF_UID = R.RES_UID
      AND R.RES_EUID = @res_euid

   DELETE FROM MSP_ASSN_ENTERPRISE
    WHERE PROJ_ID = @res_global_id
      AND RES_UID = @res_euid

   -- Now delete the resource from the resource table itself
   DELETE FROM MSP_RESOURCES
    WHERE PROJ_ID = @res_global_id
      AND RES_UID = @res_euid

   -- Now delete the resource's calendar from the calendars table itself
   DELETE FROM MSP_CALENDARS 
    WHERE PROJ_ID = @res_global_id 
      AND RES_UID = @res_euid

   -- Now we need to delete all the custom field data
   DELETE FROM MSP_NUMBER_FIELDS WHERE PROJ_ID = @res_global_id AND NUM_REF_UID = @res_euid
   DELETE FROM MSP_TEXT_FIELDS WHERE PROJ_ID = @res_global_id AND TEXT_REF_UID = @res_euid
   DELETE FROM MSP_DATE_FIELDS WHERE PROJ_ID = @res_global_id AND DATE_REF_UID = @res_euid
   DELETE FROM MSP_DURATION_FIELDS WHERE PROJ_ID = @res_global_id AND DUR_REF_UID = @res_euid
   DELETE FROM MSP_FLAG_FIELDS WHERE PROJ_ID = @res_global_id AND FLAG_REF_UID = @res_euid
   DELETE FROM MSP_CODE_FIELDS WHERE PROJ_ID = @res_global_id AND CODE_REF_UID = @res_euid
   DELETE FROM MSP_MV_FIELDS WHERE PROJ_ID = @res_global_id AND CODE_REF_UID = @res_euid -- P11/7221
		
   -- For P11/7562 we need to delete the resource's rows in the View Tables
   DELETE FROM MSP_VIEW_RES_TP_BY_DAY where ResourceUniqueID = @res_euid
   DELETE FROM MSP_VIEW_RES_CF where CF_ResourceUniqueID = @res_euid
   DELETE FROM MSP_VIEW_RES_ENT where ENT_ResourceUniqueID = @res_euid
   DELETE FROM MSP_VIEW_RES_STD where ResourceUniqueID = @res_euid
		
   -- P11/9722 - Mark the resource as local in the view tables
   UPDATE MSP_VIEW_PROJ_RES_STD SET ResourceEnterpriseUniqueID = -1 WHERE ResourceEnterpriseUniqueID = @res_euid
   UPDATE MSP_VIEW_PROJ_RES_ENT SET ENT_ResourceEnterpriseUniqueID = -1 WHERE ENT_ResourceEnterpriseUniqueID = @res_euid
   UPDATE MSP_VIEW_PROJ_RES_CF SET CF_ResourceEnterpriseUniqueID = -1 WHERE CF_ResourceEnterpriseUniqueID = @res_euid
		
   -- NOTE: The following call is the reason we checked above to see if there
   -- were any checked-out projects containing the resource.  
   -- Transform all instances of this resource into local resources and give them
   -- the new name that makes clear that they are deleted. 
   UPDATE MSP_RESOURCES 
      SET RES_EUID = NULL,
          RES_NAME = @new_local_name,
          RES_WORKGROUP_MESSAGING = 1 -- 1 means None, implying no messaging
    WHERE PROJ_ID <> @res_global_id 
      AND RES_EUID = @res_euid

   -- NOTE: we don't want to delete the corresponding PWA account here.  Rather,
   -- we will call Tao's PjSvrSecurity.DeleteAccount back in VB. 

RETURN 1
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_ResourceDelete TO MSProjectServerRole
GO

/* Query PDS061 */
CREATE PROCEDURE dbo.MSP_PDS_ProjectResourceSetBookingType
   @proj_id INT,
   @booking_type INT,
   @res_euid INT,
   @res_name varchar(255),
   @res_euid_out INT OUTPUT
AS
BEGIN
  -- If we get a @res_euid > 0 (eg: not 0 or -1) then we search by EUID
  -- Otherwise, we search by name
  UPDATE MSP_RESOURCES 
     SET RES_BOOKING_TYPE = @booking_type
   WHERE PROJ_ID = @proj_id 
     AND (   (@res_euid >  0 AND @res_euid = RES_EUID)
          OR (@res_euid <= 0 AND lower(@res_name) = lower(RES_NAME)))  -- P11/5599 (ensure name case-insensitivity)
  if @res_euid > 0 
    SET @res_euid_out = @res_euid
  else
    begin  
      SET @res_euid_out = 0   
      SELECT @res_euid_out = RES_EUID FROM MSP_RESOURCES WHERE PROJ_ID = @proj_id AND lower(@res_name) = lower(RES_NAME)
    end  
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_ProjectResourceSetBookingType TO MSProjectServerRole
GO

/* Query PDS062 */
CREATE PROCEDURE dbo.MSP_PDS_MultiValueSet
   @proj_id INT,
   @code_field_id INT,
   @code_ref_uid INT,
   @code_category INT,
   @code_uid_list NTEXT,
   @corres_code_field_id INT -- The Field ID for the single-value EROC corresponding to @code_field_id
AS
BEGIN
  -- PLEASE NOTE: Setting this is a workaround for the following KB article:
  -- PRB: ADO Errors Collection Does Not Contain User-Defined Error Messages (254304)
  set NOCOUNT ON 
  
  -- Start by deleting the current set of multivalues
  DELETE FROM MSP_MV_FIELDS
   WHERE PROJ_ID = @proj_id
     AND CODE_FIELD_ID = @code_field_id
     AND CODE_REF_UID = @code_ref_uid
     AND CODE_CATEGORY = @code_category

  -- Now insert the new set
  INSERT INTO MSP_MV_FIELDS (PROJ_ID, CODE_MV_UID, CODE_CATEGORY, CODE_REF_UID, CODE_FIELD_ID, CODE_UID)
  (
    SELECT @proj_id, PT.Y, @code_category, @code_ref_uid, @code_field_id, PT.X FROM dbo.MSP_WEB_FN_ConvertPairListToPairTable(@code_uid_list) PT
  )

  -- Check to make sure that the corresponding EROC value (if any) is among the values
  -- in the Multi-value set
  declare @eroc_uid INT
  set @eroc_uid = -1
  SELECT @eroc_uid=CODE_UID
    FROM MSP_CODE_FIELDS 
   WHERE PROJ_ID = @proj_id
     AND CODE_REF_UID = @code_ref_uid
     AND CODE_FIELD_ID = @corres_code_field_id
     AND CODE_CATEGORY = @code_category
  if @eroc_uid <> -1 
    begin -- then there is a corresponding single-value set
      declare @eroc_contained INT
      SELECT @eroc_contained = count(*)
        FROM MSP_MV_FIELDS
       WHERE CODE_UID = @eroc_uid
         AND CODE_REF_UID = @code_ref_uid
         AND CODE_CATEGORY = @code_category
         AND PROJ_ID = @proj_id
      if @eroc_contained <> 1 
        BEGIN -- Then the multi-value set does not contain the single value
          RAISERROR ('Multivalues Do Not Contain Codevalue', 16, 1)
          RETURN
        END
     end
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_MultiValueSet TO MSProjectServerRole
GO

/* Query PDS063 */
CREATE PROCEDURE dbo.MSP_PDS_GetUniqueWebResName
   @INITIAL_TRY NVARCHAR(255),
   @UNIQUE_NAME NVARCHAR(255) OUTPUT
AS
begin
  SET @UNIQUE_NAME = @INITIAL_TRY

  DECLARE @COUNT INT
  SELECT @COUNT = COUNT(*) FROM MSP_WEB_RESOURCES WHERE lower(RES_NAME) = lower(@INITIAL_TRY) -- P11/5599 (ensure name case-insensitivity)
  IF @COUNT = 0 RETURN -- The initial try was unique
  
  -- Since the initial try was not unique, we will truncate the initial try (to ensure
  -- the end result does not run over 255 characters) and keep on trying to append 
  -- integers (starting at 1) until we have a unique name.  For this to fail because
  -- there is no unique name left that can be constructed with this method, the database
  -- must already have at least 2^31 PWA accounts, each with a name of the form
  -- substring(@initial_try,0,229) + some integer, which is way beyond our operating 
  -- capacity anyhow.  
  DECLARE @ROOT NVARCHAR(230)
  SET @ROOT = SUBSTRING(@INITIAL_TRY,0,229)

  DECLARE @I INT
  SET @I = 1 -- START WITH 1
  WHILE 1=1
    BEGIN
      SET @UNIQUE_NAME = @ROOT + CAST(@I AS NVARCHAR)
      SELECT @COUNT = COUNT(*) FROM MSP_WEB_RESOURCES WHERE lower(RES_NAME) = lower(@UNIQUE_NAME) -- P11/5599 (ensure name case-insensitivity)
      IF @COUNT = 0 RETURN 
      SET @I = @I + 1 -- P11/8135
      CONTINUE 
    END
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_GetUniqueWebResName TO MSProjectServerRole
GO

/* Query PDS064 */
CREATE PROCEDURE dbo.MSP_PDS_CopyEntListSeparatorIfNull
   @old_eglobal_proj_id INT,
   @new_eglobal_proj_id INT
AS
begin
  DECLARE @NEW_SEP VARCHAR(2)
  SELECT @NEW_SEP = PROJ_ENT_LIST_SEPARATOR FROM MSP_PROJECTS WHERE PROJ_ID = @new_eglobal_proj_id

  IF (@NEW_SEP IS NULL) OR (LEN(@NEW_SEP) = 0)
    BEGIN
      DECLARE @OLD_SEP VARCHAR(2)
      SELECT @OLD_SEP = PROJ_ENT_LIST_SEPARATOR FROM MSP_PROJECTS WHERE PROJ_ID = @old_eglobal_proj_id
      IF (@OLD_SEP IS NULL) OR (LEN(@OLD_SEP) = 0) 
        BEGIN
          RAISERROR ('Blank EntListSep', 16, 1)
          RETURN
        END
      UPDATE MSP_PROJECTS SET PROJ_ENT_LIST_SEPARATOR = @OLD_SEP WHERE PROJ_ID = @new_eglobal_proj_id
    END
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_CopyEntListSeparatorIfNull TO MSProjectServerRole
GO

/* Query PDS065 */
CREATE PROCEDURE dbo.MSP_PDS_ProjectSelectiveDelete
   @proj_id INT
AS
begin
  BEGIN TRANSACTION
  SET XACT_ABORT ON -- P11/10301 - Supporting transactions in 3-way split-db

  DELETE FROM MSP_TASKS WHERE PROJ_ID = @proj_id AND RESERVED_DATA = 'X'
  DELETE FROM MSP_RESOURCES WHERE PROJ_ID = @proj_id AND RESERVED_DATA = 'X'  
  DELETE FROM MSP_ASSIGNMENTS WHERE PROJ_ID = @proj_id AND RESERVED_DATA = 'X'
  DELETE FROM MSP_CALENDARS WHERE PROJ_ID = @proj_id AND RESERVED_DATA = 'X'
  DELETE FROM MSP_ASSN_ENTERPRISE WHERE PROJ_ID = @proj_id AND RESERVED_DATA = 'X' -- AND ASSN_UID IS NOT NULL -- P11/7561 potential fix, if we go with it
  DELETE FROM MSP_OUTLINE_CODES WHERE PROJ_ID = @proj_id AND RESERVED_DATA = 'X'
  DELETE FROM MSP_CALENDAR_DATA WHERE PROJ_ID = @proj_id AND RESERVED_DATA = 'X'
  DELETE FROM MSP_RESOURCE_RATES WHERE PROJ_ID = @proj_id AND RESERVED_DATA = 'X'
  DELETE FROM MSP_AVAILABILITY WHERE PROJ_ID = @proj_id AND RESERVED_DATA = 'X'
  DELETE FROM MSP_TIMEPHASED_DATA WHERE PROJ_ID = @proj_id AND RESERVED_DATA = 'X'
  DELETE FROM MSP_LINKS WHERE PROJ_ID = @proj_id AND RESERVED_DATA = 'X'
  --     Clearing Baseline doesn't clear all of the data
  DELETE FROM MSP_MV_FIELDS WHERE PROJ_ID = @proj_id AND RESERVED_DATA = 'X'
    
  DELETE FROM MSP_TASK_BASELINES 
   WHERE (PROJ_ID = @proj_id) 
     AND (TB_BASE_DUR = 0 OR TB_BASE_DUR IS NULL) 
     AND (TB_BASE_START IS NULL) 	
     AND (TB_BASE_FINISH IS NULL) 
     AND (TB_BASE_WORK = 0 OR TB_BASE_WORK IS NULL)

  DELETE FROM MSP_RESOURCE_BASELINES 
   WHERE (PROJ_ID = @proj_id) 
     AND (RB_BASE_WORK = 0 OR RB_BASE_WORK IS NULL) 
     AND (RB_BASE_COST = 0 OR RB_BASE_COST IS NULL)

  DELETE FROM MSP_ASSIGNMENT_BASELINES   
   WHERE (PROJ_ID = @proj_id) 
     AND (AB_BASE_START IS NULL) AND (AB_BASE_FINISH IS NULL) 
     AND (AB_BASE_WORK = 0 OR AB_BASE_WORK IS NULL) 
     AND (AB_BASE_COST_PER_USE = 0 OR AB_BASE_COST_PER_USE IS  NULL)

  --  ' Remove the deleted summary resource assignments for the current project.
  --  ' We don't remove any summary resource assignments with ASSN_UID equal to NULL
  --  ' because those are the place holder summary resource assignments for non
  --  ' default projects.  See the CreateDummySummaryResourceAssignment function.
  DELETE FROM MSP_ASSN_ENTERPRISE 
   WHERE ASSN_ENTSUMPROJID = @proj_id 
     AND RESERVED_DATA = 'X' 
     AND ASSN_UID IS NOT NULL
  
  COMMIT TRANSACTION
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_ProjectSelectiveDelete TO MSProjectServerRole
GO

/* Query PDS066 */
CREATE PROCEDURE dbo.MSP_PDS_CopyEROCtoERMV
  @proj_id INT,
  @code_ref_uid INT,
  @code_uid INT,
  @code_category INT,
  @code_field_id_mv INT
AS
BEGIN
  declare @mv_count INT
  SELECT @mv_count = count(*) from MSP_MV_FIELDS
  WHERE CODE_FIELD_ID = @code_field_id_mv
    AND PROJ_ID = @proj_id
    AND CODE_CATEGORY = @code_category
    AND CODE_REF_UID = @code_ref_uid
    AND CODE_UID <> @code_uid
      
  if @mv_count >= 250 -- greater than OR equal will be a problem, since we still need to add the EROC @code_uid
    BEGIN
      RAISERROR ('Multi-Value 250 Limit Exceeded', 16, 1)
      RETURN
    END

  -- Find out whether the EROC UID is already in the set of ERMVs
  declare @uid_already_in_mv INT
  select @uid_already_in_mv = count(*) 
    from MSP_MV_FIELDS
   where CODE_FIELD_ID = @code_field_id_mv
     AND PROJ_ID = @proj_id
     AND CODE_CATEGORY = @code_category
     AND CODE_REF_UID = @code_ref_uid
     AND CODE_UID = @code_uid

  -- If there are no ERMV values, then we do not need to copy the EROC over
  if (@mv_count + @uid_already_in_mv) = 0 
    begin
      return
    end
  
  if @uid_already_in_mv = 0 
    begin
      -- Find the lowest available CODE_MV_UID for the UID
      declare @idx INT
      set @idx = 1
      while (select count(*) from MSP_MV_FIELDS where PROJ_ID = @proj_id AND CODE_MV_UID = @idx AND CODE_CATEGORY = @code_category AND CODE_REF_UID = @code_ref_uid AND CODE_FIELD_ID = @code_field_id_mv) = 1
        begin
          set @idx = @idx + 1
          continue
        end
      -- Insert the EROC value
      INSERT INTO MSP_MV_FIELDS (PROJ_ID, CODE_MV_UID, CODE_CATEGORY, CODE_REF_UID, CODE_FIELD_ID, CODE_UID)
        VALUES ( @proj_id, @idx, @code_category, @code_ref_uid, @code_field_id_mv, @code_uid )
    end
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_CopyEROCtoERMV TO MSProjectServerRole
GO

/* Query PDS067 */
CREATE PROCEDURE dbo.MSP_PDS_ResourceDeleteFromProject -- P11/9286 comprehensive fix
   @proj_id INT,
   @res_euid INT,
   @res_name varchar(255)
AS
BEGIN
   -- Get the resglobal's Proj ID, as we will be using it a lot
   declare @res_global_id INT 
   select @res_global_id = PROJ_ID FROM MSP_PROJECTS WHERE PROJ_TYPE=3

   -- Get the resource's local uid
   declare @res_uid INT
   set @res_uid = -1
   SELECT @res_uid = RES_UID 
     FROM MSP_RESOURCES
    WHERE PROJ_ID = @proj_id
      AND (( @res_euid > 0 AND RES_EUID = @res_euid) OR (@res_euid <= 0 AND lower(RES_NAME) = lower(@res_name)))
   if @res_uid = -1 
     begin
       RAISERROR('Resource Not Found', 16, 1)
       RETURN
     end

   -- Delete the resource's assignments in the project
   DELETE FROM MSP_ASSIGNMENTS
     WHERE PROJ_ID = @proj_id 
       AND RES_UID = @res_uid
 
   -- Delete the summary resource assignments
   if @res_euid > 0 
     begin 
       DELETE FROM MSP_ASSN_ENTERPRISE
        WHERE PROJ_ID = @res_global_id
          AND RES_UID = @res_euid
          AND ASSN_ENTSUMPROJID = @proj_id 

       -- We should never have more than 1 summary resource assignment for a resource/project combination
       if @@ROWCOUNT > 1 
         begin
           RAISERROR('Multiple Rows Deleted', 16, 1)
           RETURN
         end
     end

   -- Now delete the resource from the resource table itself
   DELETE FROM MSP_RESOURCES
    WHERE PROJ_ID = @proj_id
      AND RES_UID = @res_uid

   -- Now delete the resource's calendar from the calendars table itself
   DELETE FROM MSP_CALENDARS 
    WHERE PROJ_ID = @proj_id 
      AND RES_UID = @res_uid

   -- Now we need to delete all the custom field data
   DELETE FROM MSP_NUMBER_FIELDS WHERE PROJ_ID = @proj_id AND NUM_REF_UID = @res_uid
   DELETE FROM MSP_TEXT_FIELDS WHERE PROJ_ID = @proj_id AND TEXT_REF_UID = @res_uid
   DELETE FROM MSP_DATE_FIELDS WHERE PROJ_ID = @proj_id AND DATE_REF_UID = @res_uid
   DELETE FROM MSP_DURATION_FIELDS WHERE PROJ_ID = @proj_id AND DUR_REF_UID = @res_uid
   DELETE FROM MSP_FLAG_FIELDS WHERE PROJ_ID = @proj_id AND FLAG_REF_UID = @res_uid
   DELETE FROM MSP_CODE_FIELDS WHERE PROJ_ID = @proj_id AND CODE_REF_UID = @res_uid
   DELETE FROM MSP_MV_FIELDS WHERE PROJ_ID = @proj_id AND CODE_REF_UID = @res_uid
		
RETURN 1
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_ResourceDeleteFromProject TO MSProjectServerRole
GO

/* Query PDS068 */
CREATE PROCEDURE dbo.MSP_PDS_GenerateAndSetCubeGUID -- P11/4033
AS
  set NOCOUNT ON 

  update MSP_WEB_ADMIN_CUBE 
     set WADMIN_CUBE_BUILD_GUID = NEWID()

  select cast(WADMIN_CUBE_BUILD_GUID as varchar(100)) as 'GUID' from MSP_WEB_ADMIN_CUBE
GO

GRANT EXECUTE ON dbo.MSP_PDS_GenerateAndSetCubeGUID TO MSProjectServerRole
GO


/* Query PDS069 */
CREATE PROCEDURE dbo.MSP_PDS_CacheFullName
   @field_id INT
AS
BEGIN

SET NOCOUNT ON

-- Get the EGlobal's PROJ_ID 
declare @ent_global_id INT
select @ent_global_id = PROJ_ID from MSP_PROJECTS where PROJ_TYPE = 2

-- Get the code mask information
declare @code_mask varchar(256)
select @code_mask = AS_VALUE 
  from MSP_FIELD_ATTRIBUTES fa inner join MSP_ATTRIBUTE_STRINGS ats on fa.AS_ID = ats.AS_ID 
 where fa.ATTRIB_ID = 200 
   and fa.ATTRIB_FIELD_ID = @field_id
   and fa.PROJ_ID = @ent_global_id

-- Advance to the point of the first level separator
declare @idx int
set @idx = charindex(',',@code_mask)
set @idx = charindex(',',@code_mask,@idx+1)

-- No separator between summary elem and level-1 items
declare @sep varchar(255)
set @sep = '' 

-- Clear the values for the top-level items
declare @uid_tbl table (UID int)
insert into @uid_tbl select CODE_UID from MSP_OUTLINE_CODES where PROJ_ID = @ent_global_id and OC_FIELD_ID = @field_id and OC_PARENT = 0
update MSP_OUTLINE_CODES 
   set OC_CACHED_FULL_NAME = ''
 where PROJ_ID = @ent_global_id
   and CODE_UID in (select UID from @uid_tbl)

-- This is a temp table that will hold children
declare @child_uid_tbl table (UID int)

-- Start with the top-level items and run thru a while loop
declare @uid_count int
select @uid_count = count(*) from @uid_tbl

-- This indicates when we have run out of levels on the mask
declare @end_of_mask int
set @end_of_mask = 0

while @uid_count > 0 
  begin
    -- Here we actually construct the full name
    update oc1
       set oc1.OC_CACHED_FULL_NAME = ISNULL(cast(oc2.OC_CACHED_FULL_NAME as varchar(255)),'') + @sep + ISNULL(cast(oc1.OC_NAME as varchar(255)),'')
      from MSP_OUTLINE_CODES oc1 inner join MSP_OUTLINE_CODES oc2 on oc1.OC_PARENT = oc2.CODE_UID
     where oc1.PROJ_ID = @ent_global_id and oc2.PROJ_ID = @ent_global_id
       and oc1.CODE_UID in (select UID from @uid_tbl)

    -- Get all the lookup table items in the next level
    delete from @child_uid_tbl
    insert into @child_uid_tbl
    select CODE_UID from MSP_OUTLINE_CODES where PROJ_ID = @ent_global_id and OC_FIELD_ID = @field_id and OC_PARENT in (select UID from @uid_tbl)
    delete from @uid_tbl
    insert into @uid_tbl select UID from @child_uid_tbl
    select @uid_count = count(*) from @uid_tbl

    -- Get the list separator for the next level
    declare @next_idx INT
    set @next_idx = charindex(',', @code_mask, @idx+1)
    if @end_of_mask = 0
      begin
        if @next_idx = 0 
          begin
            set @next_idx = len(@code_mask) + 1 -- this if-statement handles getting the last separator in the mask
            set @end_of_mask = 1   
          end
        set @sep = substring(@code_mask, @idx+1, @next_idx - @idx - 1)
      end
    else set @sep = ''

    -- Handle the special encoding of the comma as a separator
    if @sep = '","' set @sep = ','

    -- Advance over the mask by 3 commas so we are in a position to get the next list separator
    set @idx = charindex(',', @code_mask, @idx+1)
    set @idx = charindex(',', @code_mask, @idx+1)
    set @idx = charindex(',', @code_mask, @idx+1)
  end
END
GO

GRANT EXECUTE ON dbo.MSP_PDS_CacheFullName TO MSProjectServerRole
GO

/* Query PDS070 */
CREATE PROCEDURE dbo.MSP_PDS_AdminSettings
   @user_id INT
AS
begin
  -- P11/10603 - Get the user's RBS UID
  declare @user_rbsuid INT
  set @user_rbsuid = -1
  select @user_rbsuid = CODE_UID
    from MSP_CODE_FIELDS cf, MSP_PROJECTS p, MSP_WEB_RESOURCES wr
   where cf.CODE_FIELD_ID = 205521540
     and cf.PROJ_ID = p.PROJ_ID
     and p.PROJ_TYPE = 3
     and wr.RES_EUID = cf.CODE_REF_UID 
     and wr.WRES_ID = @user_id

-- Return all the normal data
SELECT WADMIN_DISPLAY_MASTER_IN_ENTERPRISE,WADMIN_ALLOW_LOCAL_BASE_CALS_IN_ENTERPRISE,WADMIN_ENFORCE_CURRENCY,WADMIN_AUTHENTICATION_TYPE,WADMIN_PROTECT_ACTUALS, @user_rbsuid as 'RBSUID' FROM MSP_WEB_ADMIN

return
end
GO

GRANT EXECUTE ON dbo.MSP_PDS_AdminSettings TO MSProjectServerRole
GO



/*-------------------------------------------------------------------------
 * Function to return a table variable from a comma-separated ID list
 *------------------------------------------------------------------------*/

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.MSP_WEB_FN_charindex_ex')
and xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.MSP_WEB_FN_charindex_ex
GO

create function dbo.MSP_WEB_FN_charindex_ex (@searchar nvarchar(1),@str ntext,@startloc int)
returns int
as
begin
   declare @curpos int, @strlen int, @charval nchar(1)
   set @strlen = datalength(@str)
   set @curpos = @startloc 
   while @curpos <= @strlen
   begin
	   if substring(@str,@curpos,1) = @searchar
		   break
	   set @curpos = @curpos + 1
   end
return @curpos
end
GO

GRANT EXECUTE ON dbo.MSP_WEB_FN_charindex_ex TO MSProjectServerRole
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.MSP_WEB_FN_ConvertStringListToTable')
and xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.MSP_WEB_FN_ConvertStringListToTable
GO

CREATE FUNCTION dbo.MSP_WEB_FN_ConvertStringListToTable(@ntext ntext)
RETURNS @TokenVals table (TokenVal nvarchar(1024))
AS
BEGIN
  declare @maxStrLen int
  declare @s nvarchar(4000)
  declare @textLen int
  declare @textPos int
  declare @nextTextDelim int
  declare @strLen int
  declare @strPos int
  declare @nextStrDelim int
  declare @val nvarchar(1024)

  set @maxStrLen = 4000

  set @textLen = datalength(@ntext) / 2 --2 bytes per char
  set @textPos = 1

  if (@textLen = 0) return

  -- Parse the text into strings of 8000 chars
  While (@textPos <= @textLen)
  Begin

     If ((@textLen - @textPos + 1) > @maxStrLen)
       begin
        set @s = substring(@ntext, @textPos, @maxStrLen)
        -- Search for the last delimiter within the string
        set @nextTextDelim = @maxStrLen - charindex(',', reverse(@s)) + 1

        -- cut the text to the last delimiter before the maxStrLen mark
        if (@nextTextDelim > 0)
           set @s = substring(@s, 1, @nextTextDelim - 1)
        else
           -- Rare case, happens only when the delimiter is exactly after the last char
           set @nextTextDelim = @maxStrLen + 1

        set @textPos = @textPos + @nextTextDelim
       end
     Else
       begin
        -- Last text block - convert it into string
        set @s = substring(@ntext, @textPos, @textLen - @textPos + 1)
        set @textPos = @textLen + 1
       end


     -- Parse the string
     set @strLen = len(@s)
     set @strPos = 0
     
     -- For each token, load it into the table
     While @strPos <= @strLen
     Begin
        -- get the next token
        set @nextStrDelim = charindex(',', @s, @strPos)
        if @nextStrDelim = 0
           set @nextStrDelim = @strLen + 1
     
        set @val = substring(@s, @strPos, @nextStrDelim - @strPos)
     
        -- load the table variable
        insert @TokenVals values (@val)
     
        -- increment to the next position, and handle the last token
        set @strPos = @nextStrDelim + 1
     End --string handling

  End --text handling

RETURN
END
GO

GRANT SELECT ON dbo.MSP_WEB_FN_ConvertStringListToTable TO MSProjectServerRole
GO


IF EXISTS (SELECT id FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.MSP_PDS_SP_UpdateSummaryAssnVersions')
AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE dbo.MSP_PDS_SP_UpdateSummaryAssnVersions
GO

CREATE PROCEDURE dbo.MSP_PDS_SP_UpdateSummaryAssnVersions 
  @ProjID  int
AS
BEGIN

  -- Check to see if any of the summary resource assignments for the specified
  -- project need to be updated with the Version ID and the default proj ID.
  -- We store this information on the summary resource assignments to improve
  -- the performance determine which summary resource assignments to load while
  -- opening an enterprise project.
  declare @needupdate_count   integer
  select @needupdate_count = COUNT(*) 
    FROM MSP_ASSN_ENTERPRISE 
    where ASSN_ENTSUMPROJID = @ProjID
     AND ASSN_PROJ_VERSION_ID is NULL
  IF @needupdate_count = 0 return 


  -- Update the Version ID and the Default Proj ID on the summary resource 
  -- assignments for the specified project.
  declare @proj_version_id    integer
  declare @proj_prefix_name   nvarchar(1024)
  declare @proj_id_published  integer
  declare @wproj_id_published integer
  declare @vers_id_default    integer
  declare @vers_name_default  nvarchar(1024)

  select @proj_version_id = VERS_ID from MSP_VERSIONS where VERS_VERSION in
    (select PROJ_VERSION from MSP_PROJECTS where PROJ_ID = @ProjID)

  select @vers_id_default = VERS_ID, @vers_name_default=VERS_VERSION 
    from MSP_VERSIONS  where VERS_DEFAULT = 1

  if(@proj_version_id = @vers_id_default) 
  BEGIN
    set @proj_id_published = @ProjID
  END
  else
  BEGIN
    select @proj_prefix_name = PROJ_PROJECT from MSP_PROJECTS where PROJ_ID = @ProjID
    select @proj_id_published = PROJ_ID from MSP_PROJECTS 
      where PROJ_VERSION = @vers_name_default and LOWER(PROJ_PROJECT) = LOWER(@proj_prefix_name)
  END

  update MSP_ASSN_ENTERPRISE set 
    ASSN_PROJ_VERSION_ID = @proj_version_id, 
    ASSN_DEFAULT_VERSION_PROJ_ID = @proj_id_published
    where ASSN_ENTSUMPROJID = @ProjID and ASSN_PROJ_VERSION_ID is NULL

  return

END
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_UpdateSummaryAssnVersions TO MSProjectServerRole
GO


IF EXISTS (SELECT id FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.MSP_PDS_SP_CreateDummySummaryResAssn')
AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE dbo.MSP_PDS_SP_CreateDummySummaryResAssn
GO

CREATE PROCEDURE dbo.MSP_PDS_SP_CreateDummySummaryResAssn 
  @ProjID  int
AS
BEGIN

  -- If the project belongs to the default version then we don't need to create the dummy assignment
  declare @vers_default tinyint
  select @vers_default = VERS_DEFAULT from MSP_VERSIONS
    where LOWER(VERS_VERSION) in
    (select LOWER(PROJ_VERSION) from MSP_PROJECTS where PROJ_ID = @ProjID)
  IF @vers_default = 1 return

  -- Check to see if there's already a dummy summary resource assignment for this project.
  declare @dummyassn_count   integer
  select @dummyassn_count = COUNT(*) 
    FROM MSP_ASSN_ENTERPRISE 
    where ASSN_ENTSUMPROJID = @ProjID
     AND RESERVED_DATA = 'X'
     AND RES_UID is NULL
  IF @dummyassn_count > 0 return

  -- Get the resglobal's Proj ID
  declare @res_global_id INT 
  select @res_global_id = PROJ_ID FROM MSP_PROJECTS WHERE PROJ_TYPE=3

  -- Insert the dummy summary resource assignment
  insert into MSP_ASSN_ENTERPRISE 
    (RESERVED_DATA, PROJ_ID, ASSN_ENTSUMPROJID)
    values ('X', @res_global_id, @ProjID)

  -- Fix the version information for the dummy summary resource assignment
  EXEC MSP_PDS_SP_UpdateSummaryAssnVersions @ProjID

  return

END
GO

GRANT EXECUTE ON dbo.MSP_PDS_SP_CreateDummySummaryResAssn TO MSProjectServerRole
GO
