Showing posts with label PeopleSoft. Show all posts
Showing posts with label PeopleSoft. Show all posts

Friday, April 11, 2008

Camp9PT849DBrefresh.sql: PS CS database refresh

Author: Robert Lawson
Environment: Windows Server, MS SQL Server, PeopleSoft
Description: This script updates PeopleSoft Campus Solution's v9 database all the steps to make it operational, point to 'test' instances, update security and clean out working tables.

Code:
/*
File: Camp9PT849DBrefresh.sql
Update : 11-Apr-2008/Robert Lawson
Purpose: Post db updates for Campus Solutions 9/PT 8.49

*/
-- Fix database users
exec sp_change_users_login 'update_one','folks','folks'
exec sp_change_users_login 'update_one','Angel_Access','Angel_Access'
exec sp_change_users_login 'update_one','db-user','db-user'

-- \scripts\grant.sql
GRANT SELECT ON PSSTATUS TO folks
GRANT SELECT ON PSACCESSPRFL TO folks
GRANT SELECT ON PSOPRDEFN TO folks


-- Disable student accounts
UPDATE PSOPRDEFN SET ACCTLOCK = 1
WHERE OPRCLASS = 'STUDENT'

-- Clear references to reports
DELETE FROM PS_CDM_LIST WHERE DISTNODENAME <> 'LSTEST'

-- QA: App Messaging
DELETE FROM PSAPMSGDOMSTAT
DELETE FROM PSAPMSGDSPSTAT

-- IB: Local Gateway
UPDATE PSGATEWAY SET
CONNURL = 'http://cc1np.campus.edu:11/PSIGW/PeopleSoftListeningConnector'
WHERE CONNGATEWAYID = 'LOCAL'

-- IB: Nodes
UPDATE PSNODECONPROP SET
PROPVALUE = 'http://ff1np.campus.edu:11/PSIGW/PeopleSoftListeningConnector'
WHERE MSGNODENAME = 'PSFT_EP'

UPDATE PSNODECONPROP SET
PROPVALUE = 'http://cc1np.campus.edu:11/PSIGW/PeopleSoftListeningConnector'
WHERE MSGNODENAME = 'PSFT_LS'

-- IB: Connectors
UPDATE PSCONNPROP SET
PROPVALUE = 'http://ff1np.campus.edu:11/PSIGW/PeopleSoftListeningConnector'
WHERE PROPID = 'FINANCIAL'

UPDATE PSCONNPROP SET
PROPVALUE = 'http://cc1np.campus.edu:11/PSIGW/PeopleSoftListeningConnector'
WHERE PROPID = 'CAMPUS'

-- Report Distribution
UPDATE PS_SERVERDEFN SET DISTNODENAME = 'LSTEST ' WHERE SERVERNAME = 'PSNT '

-- Business Interlink (Credit Card Processing)
UPDATE PSIOSETTINGS SET
IOVALUE = REPLACE(IOVALUE,'LSPROD','LSTEST')
WHERE IONAME = 'CREDITCARD_TRANSACTION' AND
IOSETTINGNAME = 'properties_file'

-- REN server (rebuilt by App Server)
DELETE FROM PSMCFRENURLID
DELETE FROM PSREN

-- Change Assistant
UPDATE PSOPTIONS SET
SHORTNAME = 'LSTEST',
LONGNAME = 'LSTEST',
GUID = '',
SYSTEMTYPE = 'STS'

-- Security
INSERT INTO PSROLEUSER
(ROLEUSER, ROLENAME,DYNAMIC_SW) VALUES
('cgreen', 'UPG_STDN_REC','N')
INSERT INTO PSROLEUSER
(ROLEUSER, ROLENAME,DYNAMIC_SW) VALUES
('cgreen', 'UPG_STDTNFIN','N')

-- appmsgpurgeall.dms (remove log statement; clears app messages)
-- core tables:
DELETE FROM PSAPMSGPUBHDR;
DELETE FROM PSAPMSGPUBDATA;
DELETE FROM PSAPMSGPUBCON;
DELETE FROM PSAPMSGSUBCON;
DELETE FROM PSAPMSGPUBERR;
DELETE FROM PSAPMSGPUBERRP;
DELETE FROM PSAPMSGPUBCERR;
DELETE FROM PSAPMSGPUBCERRP;
DELETE FROM PSAPMSGSUBCERR;
DELETE FROM PSAPMSGSUBCERRP;
DELETE FROM PSAPMSGPCONDATA;
DELETE FROM PSAPMSGSCONDATA;
DELETE FROM PSIBERR;
DELETE FROM PSIBERRP;

-- synchronous core tables:
DELETE FROM PSIBLOGHDR;
DELETE FROM PSIBLOGDATA;
DELETE FROM PSIBLOGERR;
DELETE FROM PSIBLOGERRP;
DELETE FROM PSIBLOGIBINFO;

-- archive tables:
DELETE FROM PSAPMSGARCHPH;
DELETE FROM PSAPMSGARCHPD;
DELETE FROM PSAPMSGARCHPC;
DELETE FROM PSAPMSGARCHSC;
DELETE FROM PSAPMSGARCHPT;
DELETE FROM PSAPMSGARCHST;
DELETE FROM PSIBLOGHDRARCH;
DELETE FROM PSIBLOGDATAARCH;
DELETE FROM PSIBLOGIBINFOAR;

Thursday, June 8, 2006

OC.CreatePSLearnUser: Create PeopleSoft Campus Solutions user

Author: Robert Lawson
Environment: Windows Server, Access/VBA, Microsoft SQL Server, PeopleSoft
Description: This code creates a PeopleSoft Campus Solutions user for a student, and is part of the OneCard system. All students require this user and are given the same access. This account is created in sync with the Active Directory account, so that LDAP authentication can be readily accomplished.
Features:
- Writes to application event log
- Email administrator upon any error
- PeopleSoft user created to work with LDAP authentication
Sample:




Code:
Public Sub CreatePSLearnUser(strID As String, strUType As String, bolOnLine As Boolean, intStatus2 As Integer)

' Creates PeopleSoft Learning Solutions 8.8 user

' 08-Jun-2006 Robert Lawson Creation date (Learning Solutions 8.1/PeopleTools 8.22)

' 23-Apr-2008 Robert Lawson Updated for Campus Solutions 9.0

' **** NOTE, this is centric to student in AV, any other user must look closely!!! ***************



' strID Passed OneCard ID number

' strUType Passed User Type from GetUtype function

' bolOnLine Passed TRUE=you're interactive

' IntStatus2 Returned 0=OK, <>0 You're not OK

On Error GoTo ErrorBegin

Dim strName As String

strName = "CreatePSLearnUser"



Dim intStatus As Integer

Dim objRS As ADODB.Recordset, objRS2 As ADODB.Recordset

Dim strNETUser As String, strNETEmail As String, strFullName As String, strPeopleSoftID As String

Dim strEmailType As String, strGroupRole As String, strOprClass As String, strEnrlAccessGroup As String



intStatus2 = 0

strMessage = conNoMessage



Call LoadSysDbconn(intStatus)

If intStatus <> 0 Then

strMessage = "Error calling LoadSysDbconn."

Err.Raise (vbObjectError + 10), , strMessage

GoTo ErrorBegin

End If

strTodayDate = Format(Now(), "mm/dd/yyyy")

' Get person's info

strSQL = "SELECT * FROM OneCardMaster WHERE ID = '" & strID & "'"

Debug.Print strSQL

Set objRS = CreateObject("ADODB.Recordset")

objRS.Open strSQL, conDbOneCard, adOpenDynamic, adLockReadOnly ' read access

With objRS

If (.BOF Or .EOF) Then

strMessage = strName & ": Unable to get OneCardMaster record for ID = " & strID

intStatus2 = -10

GoTo ErrorBegin

Else

strNETUser = Nz(!NETUser, "")

strNETEmail = Nz(!NETEMail, "")

strPeopleSoftID = Nz(!PeopleSoftID, "")

strFullName = Trim(Nz(!NameFirst, "")) & " " & Trim(Nz(!NameLast, ""))

End If

End With

Set objRS = Nothing



' Can not create user without these key items!

If Len(strNETUser) = 0 Or Len(strNETEmail) = 0 Then

strMessage = strName & ":Unable to get NETUser or NETEmail for = " & strID

intStatus2 = -20

GoTo ErrorBegin

End If



' Figure out which role to give them

If strUType = "STAFF" Then

strGroupRole = "?"

strEnrlAccessGroup = "?"

strOprClass = "?"

ElseIf strUType = "FACULTY" Then

strGroupRole = "?"

strEnrlAccessGroup = "?"

strOprClass = "?"

ElseIf strUType = "SOKASTUDENT" Then

strGroupRole = conGroupRoleStudent

strEnrlAccessGroup = conEnrlAccessGroupStudent

strOprClass = conOprClassStudent9

Else

strGroupRole = "?"

strEnrlAccessGroup = "?"

strOprClass = "?"

End If



' This type is not yet figured out

If strGroupRole = "?" Then

strMessage = strName & ": Unable to get role for type = " & strUType & " for ID = " & strID

intStatus2 = -25

GoTo ErrorBegin

End If



' See if user already setup

strSQL = "SELECT * FROM PSOPRDEFN WHERE OPRID = '" & strNETUser & "'"

Debug.Print strSQL

Set objRS = CreateObject("ADODB.Recordset")

objRS.Open strSQL, conDbPSLearn, adOpenDynamic, adLockReadOnly ' read access

If Not (objRS.BOF Or objRS.EOF) Then

strMessage = strName & ": User already setup in PSOPRDEFN for ID = " & strID

intStatus2 = -30

GoTo ErrorBegin

End If

Set objRS = Nothing



' --- Add PSOPRDEFN (actual user)

Set objRS = CreateObject("ADODB.Recordset")

strSQL = "PSOPRDEFN"

Debug.Print strSQL

objRS.Open strSQL, conDbPSLearn, adOpenStatic, adLockPessimistic ' write access



With objRS

.AddNew

!OPRID = strNETUser

!Version = 1

!OPRDEFNDESC = strFullName

!EMPLID = strPeopleSoftID

!EMAILID = strNETEmail

!OPRCLASS = strOprClass

!ROWSECCLASS = strOprClass

!OPERPSWD = conLearnOPERPSWD

!ENCRYPTED = 1

!SYMBOLICID = conLearnSYMBOLICID

!LANGUAGE_CD = "ENG"

!MULTILANG = 0

!CURRENCY_CD = "USD"

!LASTPSWDCHANGE = strTodayDate

!ACCTLOCK = 0

!PRCSPRFLCLS = strOprClass

!DEFAULTNAVHP = conStdDEFAULTNAVHP

!FAILEDLOGINS = 0

!EXPENT = 0

!OPRTYPE = 0

!USERIDALIAS = conBlank

!LASTSIGNONDTTM = Null

!LASTUPDDTTM = strTodayDate

!LASTUPDOPRID = conPLearnLASTUPDOPRID

!PTALLOWSWITCHUSER = 0

.Update

End With

Set objRS = Nothing



' ----- Add PSOPRALIAS (EMPLID reference)

Set objRS = CreateObject("ADODB.Recordset")

strSQL = "PSOPRALIAS"

Debug.Print strSQL

objRS.Open strSQL, conDbPSLearn, adOpenStatic, adLockPessimistic ' write access



With objRS

.AddNew

!OPRID = strNETUser

!OPRALIASTYPE = "EMP"

!OPRALIASVALUE = strPeopleSoftID

!SETID = conBlank

!EMPLID = strPeopleSoftID

!CUST_ID = conBlank

!VENDOR_ID = conBlank

!APPLID = conBlank

!CONTACT_ID = conBlank

!PERSON_ID = conBlank

!EXT_ORG_ID = conBlank

!BIDDER_ID = conBlank

!EOTP_PARTNERID = 0

.Update

End With

Set objRS = Nothing



' ----- Add PS_ROLEXLATOPR

Set objRS = CreateObject("ADODB.Recordset")

strSQL = "PS_ROLEXLATOPR"

Debug.Print strSQL

objRS.Open strSQL, conDbPSLearn, adOpenStatic, adLockPessimistic ' write access



With objRS

.AddNew

!ROLEUSER = strNETUser

!DESCR = strFullName

!OPRID = strNETUser

!EMAILID = strNETEmail

!FORMID = conBlank

!WORKLIST_USER_SW = "Y"

!EMAIL_USER_SW = "Y"

!FORMS_USER_SW = "Y"

!EMPLID = strPeopleSoftID

!ROLEUSER_ALT = conBlank

!ROLEUSER_SUPR = conBlank

!EFFDT_FROM = Null

!EFFDT_TO = Null

.Update

End With

Set objRS = Nothing

Debug.Print strSQL



' ----- Add PSROLEUSER (gives security role)

Set objRS = CreateObject("ADODB.Recordset")

strSQL = "PSROLEUSER"

Debug.Print strSQL

objRS.Open strSQL, conDbPSLearn, adOpenStatic, adLockPessimistic ' write access



With objRS

.AddNew

!ROLEUSER = strNETUser

!ROLENAME = conGroupRoleStudent9 ' 1

!DYNAMIC_SW = "N"

.Update

.AddNew

!ROLEUSER = strNETUser

!ROLENAME = "EOPP_USER" ' 2

!DYNAMIC_SW = "N"

.Update

.AddNew

!ROLEUSER = strNETUser

!ROLENAME = "SUA_PAPP_USER" ' 3

!DYNAMIC_SW = "N"

.Update

.AddNew

!ROLEUSER = strNETUser

!ROLENAME = "GENERAL_PEOPLESOFTUSER" ' 4

!DYNAMIC_SW = "N"

.Update

.AddNew

!ROLEUSER = strNETUser

!ROLENAME = "SUA_Standard Non-Page Perms" ' 5

!DYNAMIC_SW = "N"

.Update

End With

Set objRS = Nothing



' ----- Add PS_OPR_DEF_TBL_CS (enables self-serve)

Set objRS = CreateObject("ADODB.Recordset")

strSQL = "PS_OPR_DEF_TBL_CS"

Debug.Print strSQL

objRS.Open strSQL, conDbPSLearn, adOpenStatic, adLockPessimistic ' write access



With objRS

.AddNew

!OPRID = strNETUser

!SETID = conBlank

!INSTITUTION = "SUA"

!BUSINESS_UNIT = conBlank

!ACAD_GROUP = conBlank

!Subject = conBlank

!STRM = conBlank

!ACAD_PROG = conBlank

!ACAD_PLAN = conBlank

!ACAD_SUB_PLAN = conBlank

!AID_YEAR = conBlank

!ACAD_CAREER = conBlank

!SETID_FACILITY = conBlank

!SETID_CAREER = conBlank

!ENRL_ACCESS_ID = conBlank

!OVRD_CLASS_LIMIT = "N"

!OVRD_UNIT_LOAD = "N"

!OVRD_CLASS_PRMSN = "N"

!OVRD_REQUISITES = "N"

!OVRD_TIME_CNFLCT = "N"

!WAIT_LIST_OKAY = "N"

!OVRD_ENRL_ACTN_DT = "N"

!CARRY_ID = "Y"

!ADM_RECR_CTR = conBlank

!ADM_APPL_CTR = conBlank

!CASHIER_OFFICE = conBlank

!DEPTID = conBlank

!ADMIT_TYPE = conBlank

!CAMPUS = conBlank

!OUTPUT_DEST = conBlank

!ACADEMIC_LEVEL = conBlank

!ADM_APPL_METHOD = conBlank

!TSCRPT_TYPE = conBlank

!ENRL_ACCESS_GROUP = strEnrlAccessGroup

!HOUSING_INTEREST = conBlank

!FIN_AID_INTEREST = "N"

!TRANSCRIPT_TYPE = conBlank

!DATA_MEDIUM_RCVD = conBlank

!DATA_SOURCE_RCVD = conBlank

!LAST_SCH_ATTEND = conBlank

!GRADUATION_DT = Null

!INSTITUTION_SET = "SUA"

!ISET_OVRD = "SUA"

!SEV_SCHOOL_CD = conBlank

!SEV_PRG_NBR = conBlank

!PRINTER_NAME = conBlank

!SAA_TSCRPT_TYPE = conBlank

.Update

End With

Set objRS = Nothing



' Write to trans log table, table = SUB-USER, field = PeopleSoft Portal

Call DoDataLog(strName, "IN", "SUB-USER", "PeopleSoft Learn", "", strID, strID, bolOnLine)



ExitBegin:

Exit Sub



ErrorBegin:

If intStatus2 = 0 Then ' General message

strMessage = "Error in " & strName & " " & Err.Number & " " & Err.Description & " on strID = " & Nz(strID, "")

intStatus2 = -100 ' I'm NOT OK

End If

If bolOnLine Then MsgBox strMessage

Call DoEventLog("ERR", strName, 500, strMessage, True, bolOnLine)

GoTo ExitBegin

End Sub

Friday, October 22, 2004

Fin8PT844PostDBRefresh.sql: PS Financial database refresh

Author: Robert Lawson
Environment: Windows Server, MS SQL Server, PeopleSoft
Description: This script updates PeopleSoft Financials v8.8 database all the steps to make it operational, point to 'test' instances, update security and clean out working tables.
Code:
/*
File : Fin8PT844PostDBRefresh.sql
Update : 22-Oct-2004/Robert Lawson
Purpose: Post db updates for Finance 8.8


*/
-- Fix user
exec sp_change_users_login 'update_one','folkss','folkss'
exec sp_change_users_login 'update_one','fdb-user','fdb-user'

-- Report node
UPDATE PS_SERVERDEFN SET DISTNODENAME = 'FITEST ' WHERE SERVERNAME = 'PSNT '

-- Change Assistant
UPDATE PSOPTIONS SET GUID = ''
UPDATE PSOPTIONS SET LONGNAME = 'FITEST', SHORTNAME = 'FITEST'

-- Home brandings
UPDATE PSMSGCATDEFN SET
MESSAGE_TEXT = 'FITEST Home'
WHERE MESSAGE_SET_NBR = '95'
AND MESSAGE_NBR = '401'

/*
-- non-core users lock out, removed 6/16/2005
UPDATE PSOPRDEFN SET ACCTLOCK = 1 WHERE
OPRID NOT IN ('VENUS','BINGO','weepy','sneezy','grouchy','sleepy')
*/

-- REN server (not working right now)
-- DELETE FROM PSREN
-- DELETE FROM PSMCFRENURLID

-- Integration Broker
DELETE FROM PSAPMSGDOMSTAT
DELETE FROM PSAPMSGDSPSTAT

-- Local Gateway
UPDATE PSGATEWAY SET
CONNURL = 'http://cs1np.campus.edu:12/PSIGW/PeopleSoftListeningConnector'
WHERE CONNGATEWAYID = 'LOCAL'

-- Node/Gateway
UPDATE PSNODECONPROP SET
PROPVALUE = 'http://fs1np.campus.edu:12/PSIGW/PeopleSoftListeningConnector'
WHERE MSGNODENAME = 'PSFT_EP'

UPDATE PSNODECONPROP SET
PROPVALUE = 'http://cs1.soka.campus:12/PSIGW/PeopleSoftListeningConnector'
WHERE MSGNODENAME = 'PSFT_LS'

-- IB, Local Gateway, Connectors

UPDATE PSCONNPROP SET
PROPVALUE = 'http://fs1np.campus.edu:12/PSIGW/PeopleSoftListeningConnector'
WHERE PROPID = 'FINANCIAL'

UPDATE PSCONNPROP SET
PROPVALUE = 'http://cs1.campus.edu:12/PSIGW/PeopleSoftListeningConnector'
WHERE PROPID = 'CAMPUS'

-- DM/QA: appmsgpurgeall.dms (remove log statement; clears app messages)
-- core tables:
DELETE FROM PSAPMSGPUBHDR;
DELETE FROM PSAPMSGPUBDATA;
DELETE FROM PSAPMSGPUBCON;
DELETE FROM PSAPMSGSUBCON;
DELETE FROM PSAPMSGPUBERR;
DELETE FROM PSAPMSGPUBERRP;
DELETE FROM PSAPMSGPUBCERR;
DELETE FROM PSAPMSGPUBCERRP;
DELETE FROM PSAPMSGSUBCERR;
DELETE FROM PSAPMSGSUBCERRP;
DELETE FROM PSAPMSGPCONDATA;
DELETE FROM PSAPMSGSCONDATA;

-- synchronous core tables:
DELETE FROM PSIBLOGHDR;
DELETE FROM PSIBLOGDATA;
DELETE FROM PSIBLOGERR;
DELETE FROM PSIBLOGERRP;

-- archive tables:
DELETE FROM PSAPMSGARCHPH;
DELETE FROM PSAPMSGARCHPD;
DELETE FROM PSAPMSGARCHPC;
DELETE FROM PSAPMSGARCHSC;
DELETE FROM PSAPMSGARCHPT;
DELETE FROM PSAPMSGARCHST;
DELETE FROM PSIBLOGHDRARCH;
DELETE FROM PSIBLOGDATAARCH;

Thursday, July 3, 2003

sp_CreateRoleTables: Translate PS security to DB security

Author: Robert Lawson
Environment: Windows Server, MS SQL Server, PeopleSoft (Learning Solutions 8/PT 8.19)
Description: This procedure creates a database security role from a PeopleSoft security role. This was used to mimic PeopleSoft security for MS Access user access.
Code:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_CreateRoleTables]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_CreateRoleTables]
GO

CREATE PROCEDURE sp_CreateRoleTables
@InputRole VARCHAR(100),
@Debug smallint = 0
AS
/*
Name: sp_CreateRoleTables

Purpose: Create database security role from a PeopleSoft security role.

Date Whom What
----------------------------------------------------------------------------------
03-JUL-03 Robert Lawson Creation date, PT 8.19 & SQL Server 2000

Parmaters
-----------------------------------------------------------------
@InputRole Passed Role name
@Degug Passed 0=no, 1=yes; default is 0.

Description:
This stored procedure helps setup security for non-PeopleSoft application access to
a PeopleSoft database. The technique is to create a database security group equal to
the PeopleSoft security role. The assumption is that you use NT authentication, and you
match the user's network account with the database security role.
The database security role is created from the PeopleSoft security role. The database
security role has SELECT permission ('read only') for all the tables the PeopleSoft
security role allows a user. The tables allowed to a PeopleSoft user are found
through this chain:
Security Role to Permissions List
Permission List/Query to Access Group Permissions
Access Group Permisssions (Tree Name/Access Group) to Tree Structure
Traverse Tree Structure to actual records
The traverse portion is complicated as T-SQL has no method like Oracle's "CONNECT BY.. PRIOR".

How To Use:
In Query Analyzer, in the database you are working in:
1. Execute this script to create the stored procedure
2. Execute this stored procedure for each security role, as such:
exec sp_CreateRoleTables 'UPG_STDN_REC'
In Enterprise Manager
3. In Security/Logins, add new user, if not there, using domain/user and Windows Authentication
- Database Access for this database roles are "public" and "security role"
- Default database is this database
*/

/*
==========================================================
Variables and temp table
==========================================================
*/
IF EXISTS (SELECT 'x' FROM tempdb.dbo.sysobjects WHERE type = 'U' AND LEFT(name,15) = '#CreateRoleTables')
DROP Table #CreateRoleTables
CREATE TABLE #CreateRoleTables
(Tree CHAR(20), Parent CHAR(20), Child CHAR(20), CNode int, PNode int, TLevel int, Type CHAR(1))

DECLARE
@TLevel int, -- Number of levels traversed. 0=first
@Tree CHAR(20), -- Tree name
@CNode int, -- Child node number
@PNode int, -- Parent node number
@Child CHAR(20), -- Parent "contains" level
@Parent CHAR(20), -- Parent level
@Type CHAR(1), -- 'R'ecord, 'G'roup
@CNode1 int, -- Node number
@PNode1 int, -- Node number
@Child1 CHAR(20), -- Child
@Parent1 CHAR(20), -- Parent
@Type1 VARCHAR(1), -- 'R'ecord, 'G'roup for Parent
@EndOfTree smallint, -- 0=no,1=yes. When true, then no more levels to traverse within tree
@SQLString NVARCHAR(500), -- from sp_helpsql
@Table VARCHAR(100), -- SQL table name
@RoleCursor CURSOR,
@ParentCursor CURSOR,
@ChildCursor CURSOR,
@TableCursor CURSOR

SET NOCOUNT ON -- Turn off row count
/*
==========================================================
Load tree name/access groups
==========================================================
*/
SET @TLevel = 0 -- Top of tree
SET @EndOfTree = 1 -- 0=not, 1=yes at EndofTree

SET @RoleCursor = CURSOR FOR
SELECT DISTINCT SA.TREE_NAME, TN.PARENT_NODE_NAME, TN.TREE_NODE,
TN.TREE_NODE_NUM, TN.PARENT_NODE_NUM, TN.TREE_NODE_TYPE
FROM PSTREENODE TN, PS_SCRTY_ACC_GRP SA, PSROLECLASS RC
WHERE
RC.ROLENAME = @InputRole AND
SA.CLASSID = RC.CLASSID AND
SA.ACCESSIBLE = 'Y' AND
TN.TREE_NAME = SA.TREE_NAME AND
TN.TREE_NODE = SA.ACCESS_GROUP AND
TN.TREE_NODE_TYPE = 'G' -- 'G'roup

OPEN @RoleCursor -- Returns all Tree Names & Access Group's for a security role
WHILE (0=0)
BEGIN
FETCH NEXT FROM @RoleCursor INTO
@Tree, @Parent, @Child, @CNode, @PNode, @Type
if @@Fetch_Status <> 0 break

IF @Debug = 1 PRINT 'RoleCursor ' + @Tree + ' ' + @Parent + ' ' + @Child

INSERT INTO #CreateRoleTables (Tree, Parent, Child, CNode, PNode, TLevel, Type) VALUES
(@Tree, @Parent, @Child, @CNode, @PNode, @TLevel, @Type)
SET @EndOfTree = 0
END -- RoleCursor
CLOSE @RoleCursor

/*
==========================================================
Traverse Tree Logic
==========================================================
*/
WHILE @EndOfTree = 0
BEGIN
IF @Debug = 1 PRINT @TLevel
SET @EndOfTree = 1

SET @ParentCursor = CURSOR FOR
SELECT Tree, Parent, Child, CNode, PNode, Type
FROM #CreateRoleTables
WHERE TLevel = @TLevel

OPEN @ParentCursor -- Get 'parent' level
WHILE (0=0)
BEGIN
FETCH NEXT FROM @ParentCursor INTO
@Tree, @Parent, @Child, @CNode, @PNode, @Type
if @@Fetch_Status <> 0 break
IF @Debug = 1 PRINT '@ParentCursor ' + @Parent + ' ' + @Child

SET @ChildCursor = CURSOR FOR
SELECT TREE_NAME, PARENT_NODE_NAME, TREE_NODE, TREE_NODE_NUM, PARENT_NODE_NUM, TREE_NODE_TYPE
FROM PSTREENODE WHERE
TREE_NAME = @Tree AND
PARENT_NODE_NUM = @CNode AND
PARENT_NODE_NAME = @Child

OPEN @ChildCursor -- Get level below 'parent' information
WHILE (0=0)
BEGIN
FETCH NEXT FROM @ChildCursor INTO
@Tree, @Parent1, @Child1, @CNode1, @PNode1, @Type1
if @@Fetch_Status <> 0 break

IF @Debug = 1 PRINT '@ChildCursor ' + @Parent1 + ' ' + @Child1

INSERT INTO #CreateRoleTables (Tree, Parent, Child, CNode, PNode, TLevel, Type) VALUES
(@Tree, @Parent1, @Child1, @CNode1, @PNode1, (@TLevel + 1), @Type1)
SET @EndOfTree = 0

END -- ChildCursor
END -- ParentCursor

SET @TLevel = @TLevel + 1 -- move down a level (the child becomes the parent, awwww...)
IF @Debug = 1 PRINT '@Tlevel = ' + CONVERT(CHAR(5),@TLevel) + ' @EndOfTree = ' + CONVERT(CHAR(5),@EndOfTree)
END -- EndOfTree

CLOSE @ChildCursor
CLOSE @ParentCursor

/*
==========================================================
Role: remove privledges (and retain membership) or create it
==========================================================
*/ -- From master.dbo.sp_helprole
IF EXISTS (select 'x' from sysusers where name = @InputRole and (issqlrole = 1 or isapprole = 1))
BEGIN
SET @SQLString = N'REVOKE ALL FROM ' + @InputRole
IF @Debug = 1 PRINT @SQLString
EXEC sp_executesql @SQLString
END
ELSE
BEGIN
SET @SQLString = N'sp_addrole ' + @InputRole + ', dbo'
IF @Debug = 1 PRINT @SQLString
EXEC sp_executesql @SQLString
END

/*
==========================================================
Permissions: add to role
==========================================================
*/
SET @TableCursor = CURSOR FOR
SELECT DISTINCT
CASE
WHEN RTRIM(RD.SQLTABLENAME) <> '' THEN RTRIM(RD.SQLTABLENAME)
ELSE 'PS_' + RTRIM(RT.Child)
END
FROM PSRECDEFN RD, #CreateRoleTables RT
WHERE
RT.Type = 'R' AND
RD.RECNAME = RT.Child AND
RD.RECTYPE IN (0,1) -- 0=Record,1=View

OPEN @TableCursor -- Returns list of SQL table names
WHILE (0=0)
BEGIN
FETCH NEXT FROM @TableCursor INTO
@Table
if @@Fetch_Status <> 0 break

-- Verify table actually exists in database (from master.dbo.sp_help)
IF EXISTS (select 'x' from sysobjects where id = object_id(@Table))
BEGIN
SET @SQLString = N'GRANT SELECT ON ' + @Table + ' TO ' + @InputRole
IF @Debug = 1 PRINT 'TableCursor ' + @SQLString
EXEC sp_executesql @SQLString
END
ELSE IF @Debug = 1 PRINT 'TableCursor, *** NO TALBE: ' + @Tree
END -- TableCursor
CLOSE @TableCursor

/*
==========================================================
The End
==========================================================
*/
DEALLOCATE @RoleCursor
DEALLOCATE @ParentCursor
DEALLOCATE @ChildCursor
DEALLOCATE @TableCursor