/* AUTOMATICALLY GENERATED on Fri Dec 10 04:22:05 AUSEDT 2010
 * for ManageSoft release 8.4 (build 8.1740)
 *
 * DO NOT EDIT THIS FILE BY HAND!
 * 
 * Protected by US patents 6,006,034 and 6,360,366.
 * Copyright 1995-2010 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 */

USE ManageSoft
/*
 * $Header$
 *
 * DESCRIPTION:
 *
 *	Stored procedure to copy permissions from one object in the
 *	database to another object
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'CopyPermission' AND xtype = 'P'
)
        DROP PROCEDURE CopyPermission
GO

CREATE PROCEDURE [CopyPermission]
	@ConfigureObj VARCHAR(80),	-- Object to configure perms on
	@CopyObj VARCHAR(80)		-- Object to copy perms from
AS

	DECLARE @c CURSOR

	SET @c = CURSOR FORWARD_ONLY FOR
	SELECT
		CASE p.protecttype
			WHEN 206 THEN 'DENY'
			ELSE 'GRANT'
		END
		+ ' ' +
		CASE p.action
			WHEN 193 THEN 'SELECT'
			WHEN 195 THEN 'INSERT'
			WHEN 196 THEN 'DELETE'
			WHEN 197 THEN 'UPDATE'
			WHEN 224 THEN 'EXECUTE'
		END
		+ ' ON [' + @ConfigureObj + '] TO [' + user_name(p.uid) + ']'
	from sysobjects o
		inner join sysprotects p on o.id = p.id
	where
		o.name = @CopyObj
		AND p.action in (193, 195, 196, 197, 224)

	OPEN @c

	DECLARE @stmt varchar(200)
	FETCH NEXT FROM @c INTO @stmt

	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXECUTE(@stmt)
		FETCH NEXT FROM @c INTO @stmt
	END

	CLOSE @c
	DEALLOCATE @c

GO
/*
 * $Id: DistGroups.sql 87214 2008-04-08 03:05:14Z pca $
 *
 * Update the database with changes in the Groups.cfg file
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 2000-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 */
-- USE ManageSoft
GO

PRINT 'Creating procedure to add a newly created deployment group'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'DistGroup_Create'
)
	DROP PROCEDURE DistGroup_Create
GO
CREATE PROCEDURE DistGroup_Create
	@Uid binary(16),
	@ParamName nvarchar(64)
AS
	DECLARE	@existingUID as binary(16)

	-- ensure that the deployment group does not already exist
	SELECT @existingUID = GroupUID FROM [DistributionGroup]
		WHERE GroupUID = @Uid

	-- only add the new group if a group with the same UID does
	-- not already exist
	IF (@existingUID IS NULL) BEGIN
		INSERT INTO [DistributionGroup] (GroupUID, GroupName)
			VALUES (@Uid, @ParamName)
	END
GO

PRINT 'Creating procedure to delete a deployment group'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'DistGroup_Delete'
)
	DROP PROCEDURE DistGroup_Delete
GO
CREATE PROCEDURE DistGroup_Delete
	@Uid binary(16)
AS
	DELETE FROM [DistributionGroupMember] WHERE MemberID = @Uid

	DELETE FROM [DistributionGroupMember] WHERE GroupUID = @Uid

	DELETE FROM [DistributionGroup] WHERE GroupUID = @Uid
GO


PRINT 'Creating procedure to rename a deployment group'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'DistGroup_Rename'
)
	DROP PROCEDURE DistGroup_Rename
GO
CREATE PROCEDURE DistGroup_Rename
	@Uid binary(16),
	@ParamName nvarchar(64)
AS
	DECLARE	@existingUID as binary(16)

	-- ensure that the deployment group already exists
	SELECT @existingUID = GroupUID FROM [DistributionGroup]
		WHERE GroupUID = @Uid

	-- only change the name if the group exists
	IF (@existingUID IS NOT NULL) BEGIN
		UPDATE [DistributionGroup] SET GroupName = @ParamName
			WHERE GroupUID = @Uid
	END
GO

PRINT 'Creating procedure to add a member to a deployment group'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'DistGroupMembership_Create'
)
	DROP PROCEDURE DistGroupMembership_Create
GO
CREATE PROCEDURE DistGroupMembership_Create
	@Uid binary(16),
	@Member binary(16)
AS
	DECLARE @type as int

	-- ensure that the deployment group already exists
	IF NOT EXISTS (SELECT GroupUID FROM [DistributionGroup]
		WHERE GroupUID = @Uid)
		RETURN

	-- if the member already exists, then we can't add it again
	IF EXISTS (SELECT GroupUID FROM [DistributionGroupMember]
		WHERE GroupUID = @Uid AND MemberID = @Member)
		RETURN

	-- set the type to be a group
	SELECT @type = DistributionServerTypeID FROM DistributionServerType
		WHERE DistributionServerTypeName = 'DistributionGroup'

	-- look for the member UID in the DeploymentServers table,
	-- if it's there then we change the type
	IF EXISTS (
		SELECT ServerUID FROM DistributionServer
		WHERE ServerUID = @Member
	)
	BEGIN
		SELECT @type = DistributionServerTypeID
		FROM DistributionServerType
		WHERE DistributionServerTypeName = 'DistributionLocation'
	END
	ELSE
	BEGIN
		IF EXISTS (
			SELECT GroupUID FROM DistributionGroup
			WHERE GroupUID = @Member
		)
		BEGIN
			SELECT @type = DistributionServerTypeID
			FROM DistributionServerType
			WHERE DistributionServerTypeName = 'DistributionGroup'
		END
		ELSE
			-- if it is not in the DistributionServer
			-- or DistributionGroup table, then we don't
			-- want this member added at all!
			-- The chances are that this is a
			-- ReportingLocation, but they are not stored in
			-- the database yet
			RETURN
	END

	-- only add a member if the group exists and the member does not
	INSERT INTO [DistributionGroupMember]
		(GroupUID, MemberID, MemberType)
		VALUES (@Uid, @Member, @type)
GO

PRINT 'Creating procedure to remove a member from a deployment group'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'DistGroupMembership_Delete'
)
	DROP PROCEDURE DistGroupMembership_Delete
GO
CREATE PROCEDURE DistGroupMembership_Delete
	@Uid binary(16),
	@Member binary(16)
AS
	DELETE FROM DistributionGroupMember
		WHERE GroupUID = @Uid AND MemberID = @Member
GO

PRINT 'Creating procedure to signal the start of a distribution'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'DistributedPackage_Start'
)
	DROP PROCEDURE DistributedPackage_Start
GO
CREATE PROCEDURE DistributedPackage_Start
	@Uid binary(16),
	@ObjectId nvarchar(256),
	@paramRequestState nvarchar(16),
	@paramLastRequestUpdate datetime,
	@paramLastRequestVersion nvarchar(32)
AS
	DECLARE @OldPackageVersionID AS INT
	SELECT @OldPackageVersionID =
			ISNULL(dp.ConfirmedVersionID, dp.RequestedVersionID)
		FROM DistributedPackage AS dp,
		     PackageVersion AS pv,
		     PackagePath AS pp
		WHERE dp.ServerUID = @Uid
		  AND pv.PackageVersionID =
			ISNULL(dp.ConfirmedVersionID, dp.RequestedVersionID)
		  AND pv.PackagePathID = pp.PackagePathID
		  AND pp.PackageFullName = @ObjectId

	DECLARE @NewPackageVersionID AS INT
	SELECT @NewPackageVersionID = pv.PackageVersionID
		FROM PackageVersion AS pv,
		     PackagePath AS pp
		WHERE pp.PackageFullName = @ObjectID
		  AND pv.PackagePathID = pp.PackagePathID
		  AND pv.Version = @paramLastRequestVersion

	IF @OldPackageVersionID IS NOT NULL
	BEGIN
		-- do the update here
		UPDATE [DistributedPackage]
		SET RequestedVersionID = @NewPackageVersionID,
		    RequestState = @paramRequestState,
		    RequestDate = @paramLastRequestUpdate
		WHERE ServerUID = @Uid
		  AND ISNULL(ConfirmedVersionID, RequestedVersionID) =
				@OldPackageVersionID
	END
	ELSE
	BEGIN
		-- do the insert here
		INSERT INTO [DistributedPackage]
		(ServerUID, RequestedVersionID, RequestState, RequestDate)
		VALUES
		(@Uid, @NewPackageVersionID,
		 @paramRequestState, @paramLastRequestUpdate)
	END
GO


PRINT 'Creating procedure to signal the completion of a distribution'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'DistributedPackage_Complete'
)
	DROP PROCEDURE DistributedPackage_Complete
GO
CREATE PROCEDURE DistributedPackage_Complete
	@Uid binary(16),
	@ObjectId nvarchar(256),
	@paramConfirmedState nvarchar(16),
	@paramUnavailableReason ntext,
	@paramLastConfirmedUpdate datetime,
	@paramLastConfirmedVersion nvarchar(32)
AS
	DECLARE @OldPackageVersionID AS INT
	SELECT @OldPackageVersionID =
			ISNULL(dp.ConfirmedVersionID, dp.RequestedVersionID)
		FROM DistributedPackage AS dp,
		     PackageVersion AS pv,
		     PackagePath AS pp
		WHERE dp.ServerUID = @Uid
		  AND pv.PackageVersionID =
			ISNULL(dp.ConfirmedVersionID, dp.RequestedVersionID)
		  AND pv.PackagePathID = pp.PackagePathID
		  AND pp.PackageFullName = @ObjectId

	DECLARE @NewPackageVersionID AS INT
	SELECT @NewPackageVersionID = pv.PackageVersionID
		FROM PackageVersion AS pv,
		     PackagePath AS pp
		WHERE pp.PackageFullName = @ObjectID
		  AND pv.PackagePathID = pp.PackagePathID
		  AND pv.Version = @paramLastConfirmedVersion

	IF @OldPackageVersionID IS NOT NULL
	BEGIN
		-- do the update here
		UPDATE [DistributedPackage]
		SET ConfirmedVersionID = @NewPackageVersionID,
		    ConfirmedState = @paramConfirmedState,
		    ConfirmedDate = @paramLastConfirmedUpdate,
		    ConfirmedReason = @paramUnavailableReason,
		    RequestState = 'empty'
		WHERE ServerUID = @Uid
		  AND ISNULL(ConfirmedVersionID, RequestedVersionID) =
				@OldPackageVersionID
	END
	ELSE
	BEGIN
		-- do the insert here
		INSERT INTO [DistributedPackage]
		(ServerUID, RequestedVersionID, RequestDate,
		 ConfirmedVersionID, ConfirmedState, ConfirmedDate,
		 ConfirmedReason, RequestState)
		VALUES
		(@Uid, @NewPackageVersionID, @paramLastConfirmedUpdate,
		 @NewPackageVersionID, @paramConfirmedState,
		 @paramLastConfirmedUpdate, @paramUnavailableReason, 'empty')
	END
GO

PRINT 'Creating procedure to signal the start of a package removal'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'RemovePackage_Start'
)
	DROP PROCEDURE RemovePackage_Start
GO
CREATE PROCEDURE RemovePackage_Start
	@Uid binary(16),
	@ObjectId nvarchar(256),
	@paramConfirmedState nvarchar(16),
	@paramRequestState nvarchar(16),
	@paramLastRequestUpdate datetime,
	@paramLastRequestVersion nvarchar(32)
AS
	DECLARE @OldPackageVersionID AS INT
	SELECT @OldPackageVersionID = dp.RequestedVersionID
		FROM DistributedPackage AS dp,
		     PackageVersion AS pv,
		     PackagePath AS pp
		WHERE dp.ServerUID = @Uid
		  AND pv.PackageVersionID =
			ISNULL(dp.ConfirmedVersionID, dp.RequestedVersionID)
		  AND pv.PackagePathID = pp.PackagePathID
		  AND pp.PackageFullName = @ObjectId

	DECLARE @NewPackageVersionID AS INT
	SELECT @NewPackageVersionID = pv.PackageVersionID
		FROM PackageVersion AS pv,
		     PackagePath AS pp
		WHERE pp.PackageFullName = @ObjectID
		  AND pv.PackagePathID = pp.PackagePathID
		  AND pv.Version = @paramLastRequestVersion

	IF @OldPackageVersionID IS NOT NULL
	BEGIN
		-- do the update here
		UPDATE [DistributedPackage]
		SET RequestedVersionID = @NewPackageVersionID,
		    RequestState = @paramRequestState,
		    RequestDate = @paramLastRequestUpdate
		WHERE ServerUID = @Uid
		  AND ISNULL(ConfirmedVersionID, RequestedVersionID) =
				@OldPackageVersionID
	END
	ELSE
	BEGIN
		-- do the insert here
		INSERT INTO [DistributedPackage]
		(ServerUID, RequestedVersionID,
		 RequestState, RequestDate, ConfirmedState)
		VALUES
		(@Uid, @NewPackageVersionID, @paramRequestState,
		 @paramLastRequestUpdate, @paramConfirmedState)
	END
GO


PRINT 'Creating procedure to signal the completion of a package removal'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'RemovePackage_Complete'
)
	DROP PROCEDURE RemovePackage_Complete
GO
CREATE PROCEDURE RemovePackage_Complete
	@Uid binary(16),
	@ObjectId nvarchar(256)
AS
	DECLARE @OldPackageVersionID AS INT
	SELECT @OldPackageVersionID = ISNULL(dp.ConfirmedVersionID, dp.RequestedVersionID)
		FROM DistributedPackage AS dp,
		     PackageVersion AS pv,
		     PackagePath AS pp
		WHERE dp.ServerUID = @Uid
		  AND pv.PackageVersionID =
			ISNULL(dp.ConfirmedVersionID, dp.RequestedVersionID)
		  AND pv.PackagePathID = pp.PackagePathID
		  AND pp.PackageFullName = @ObjectId

	IF @OldPackageVersionID IS NOT NULL
	BEGIN
		-- remove the row here
		DELETE [DistributedPackage]
		WHERE ServerUID = @Uid
		  AND ISNULL(ConfirmedVersionID, RequestedVersionID) =
				@OldPackageVersionID
	END
GO

PRINT 'Creating procedure to get a row from the DistributionServer table'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'FindServerOrLoc'
)
	DROP PROCEDURE FindServerOrLoc
GO
CREATE PROCEDURE FindServerOrLoc
	@Uid binary(16),
	@InServerType SmallInt
AS
	BEGIN
		SELECT ServerUID FROM DistributionServer
		WHERE ServerUID = @Uid AND ServerType = @InServerType
	END
GO

PRINT 'Creating procedure to create a row in distribution server table'
--Creates a row in the DistributionServer table.
--Only populates the ServerUID and ServerType field
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'NewEmptyDistServer'
)
	DROP PROCEDURE NewEmptyDistServer
GO
CREATE PROCEDURE NewEmptyDistServer
	@Uid binary(16),
	@paramServerType smallint
AS
	DECLARE	@existingUID as binary(16)

	SELECT @existingUID = ServerUID FROM [DistributionServer]
		WHERE ServerUID = @Uid

	-- only add the new server if a server with the same UID does
	-- not already exist
	IF (@existingUID IS NULL)
	BEGIN
		INSERT INTO [DistributionServer] (ServerUID, ServerType)
			VALUES (@Uid, @paramServerType)
	END
GO


PRINT 'Creating procedure to update "Configure Start" information on a DS'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'Config_Start'
)
	DROP PROCEDURE Config_Start
GO
CREATE PROCEDURE Config_Start
	@Uid binary(16),
	@InServerName nvarchar(64),
	@InConfigState nvarchar(20),
	@InLastConfigStart datetime,
	@InLastConfigJobId nvarchar(40)
AS
	DECLARE @dbLastConfigStart as DATETIME
	SELECT @dbLastConfigStart = (SELECT LastConfigStart FROM
		[DistributionServer] WHERE ServerUID = @Uid)

	-- Only do this if the entry exists in the database and
	-- the date in the database is older than the date passed
	-- in
	IF ((@dbLastConfigStart IS NULL) OR
		(DATEDIFF(second, @dbLastConfigStart, @InLastConfigStart) > 0))
		BEGIN
			UPDATE [DistributionServer]
			SET ConfigState = @InConfigState,
			    ServerName = @InServerName,
			    LastConfigStart = @InLastConfigStart,
			    LastConfigJobId =  @InLastConfigJobId,
			    ConfigFailReason = ''
			WHERE ServerUID = @Uid
		END
GO

PRINT 'Creating procedure to update "Configure Complete" information on a DS'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'Config_Complete'
)
	DROP PROCEDURE Config_Complete
GO
CREATE PROCEDURE Config_Complete
	@Uid binary(16),
	@InConfigState nvarchar(20),
	@InLastConfigJobId nvarchar(40),
	@InConfigFailReason ntext
AS
	DECLARE @dbJobId as nvarchar(40)

	-- Get the job id. Will need to check if it is NULL afterwards.
	SELECT @dbJobId = LastConfigJobId FROM [DistributionServer]
		WHERE ServerUID = @Uid

	-- Modify entries if it exists. Do not attempt to add
	-- new entry.
	IF EXISTS(
		SELECT ServerUID FROM [DistributionServer]
		WHERE ServerUID = @Uid
	)
		BEGIN

		-- Modify the entry if the job id is NULL or it
		-- matches the passed in parameter.
		IF EXISTS(
			SELECT ServerUID FROM [DistributionServer]
				WHERE ServerUID = @Uid AND
				LastConfigJobId = @InLastConfigJobId
		) OR (@dbJobId IS NULL)
			BEGIN
				UPDATE [DistributionServer]
				SET ConfigState = @InConfigState,
				    LastConfigJobId =  @InLastConfigJobId,
				    ConfigFailReason = @InConfigFailReason
				WHERE ServerUID = @Uid
			END
		END
GO

PRINT 'Creating procedure to update "Auto Config Complete" information on a DS'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'Auto_Config_Complete'
)
	DROP PROCEDURE Auto_Config_Complete
GO
CREATE PROCEDURE Auto_Config_Complete
	@Uid binary(16),
	@InConfigState nvarchar(20),
	@InLastConfigStart datetime,
	@InConfigFailReason ntext
AS
	DECLARE @dbLastConfigStart as DATETIME
	SELECT @dbLastConfigStart = (SELECT LastConfigStart FROM
		[DistributionServer] WHERE ServerUID = @Uid)

	-- Modify entries if it exists. Do not attempt to add
	-- new entry.  We ignore the job id and reset it to NULL as an
	-- auto configure has no valid job id (it actually uses the
	-- job id of the distribution that triggered it.
	-- Only do this if the entry exists in the database and
	-- the date in the database is older than the date passed
	-- in
	IF EXISTS(
		SELECT ServerUID FROM [DistributionServer]
		WHERE ServerUID = @Uid
	) AND (
		(@dbLastConfigStart IS NULL) OR
		(DATEDIFF(second, @dbLastConfigStart, @InLastConfigStart) > 0)
	)
		BEGIN

			UPDATE [DistributionServer]
			SET ConfigState = @InConfigState,
			    LastConfigJobId = NULL,
			    LastConfigStart = @InLastConfigStart,
			    ConfigFailReason = @InConfigFailReason
			WHERE ServerUID = @Uid
		END
GO


PRINT 'Creating procedure to update "Resynchronize State" information on a DS'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'Resync_State'
)
	DROP PROCEDURE Resync_State
GO
CREATE PROCEDURE Resync_State
	@Uid binary(16),
	@InResyncState nvarchar(20),
	@InConfigFailReason ntext
AS
		UPDATE [DistributionServer]
		SET ConfigState = @InResyncState,
		    ConfigFailReason = @InConfigFailReason
		WHERE ServerUID = @Uid
GO


PRINT 'Creating procedure to clear "Distributed Package" details on a DS/DL'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'Resync_Clear'
)
	DROP PROCEDURE Resync_Clear
GO
CREATE PROCEDURE Resync_Clear
	@Uid binary(16)
AS
	DELETE DistributedPackage WHERE ServerUID = @Uid
GO

PRINT 'Creating procedure to find all packages on or bound for a server'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'DistributedPackagePathGetByServerUID'
)
	DROP PROCEDURE DistributedPackagePathGetByServerUID
GO
CREATE PROCEDURE DistributedPackagePathGetByServerUID
	@ServerUID binary(16)
AS
	SELECT	DISTINCT(pp.PackageFullName)
	FROM	DistributedPackage AS dp,
		PackageVersion AS pv,
		PackagePath AS pp
	WHERE	dp.ServerUID = @ServerUID
	  AND	(dp.ConfirmedVersionID = pv.PackageVersionID
	  	OR dp.RequestedVersionID = pv.PackageVersionID)
	  AND	pv.PackagePathID = pp.PackagePathID
GO

PRINT 'Creating procedure to find count packages on a server'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'DistributedPackageCountByServerUID'
)
	DROP PROCEDURE DistributedPackageCountByServerUID
GO
CREATE PROCEDURE DistributedPackageCountByServerUID
	@ServerUID binary(16)
AS
	SELECT	COUNT(*)
	FROM	DistributedPackage
	WHERE	ServerUID = @ServerUID
GO

PRINT 'Creating procedure to remove distribution server and distribution locations'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'DepLoc_Delete'
)
	DROP PROCEDURE DepLoc_Delete
GO
CREATE PROCEDURE [DepLoc_Delete]
	@ServerUID BINARY(16)=NULL
AS
BEGIN
	-- Remove dependencies from DistributedPackage
	DELETE FROM DistributedPackage
	WHERE ServerUID = @ServerUID

	/*
		Remove dependencies from Wake On LAN Tables
		
		WakeOnLANDistributionJob *<--->1 WakeOnLANTask
					 1<--->* WakeOnLANStatus
	*/

	DELETE FROM WakeOnLANStatus
	WHERE DistJobUID IN (
		SELECT job.DistJobUID
		FROM WakeOnLANDistributionJob AS job
		WHERE job.ServerUID = @ServerUID
	)

	SELECT job.TaskUID
	INTO #TTaskUIDS
	FROM WakeOnLANDistributionJob AS job
	WHERE job.ServerUID = @ServerUID

	DELETE FROM WakeOnLANDistributionJob
	WHERE ServerUID = @ServerUID

	-- Delete the task if there are no other references to it.
	DELETE FROM WakeOnLANTask
	WHERE TaskUID IN (
		SELECT DISTINCT *
		FROM #TTaskUIDS AS t
		WHERE NOT EXISTS (
			SELECT TaskUID
			FROM WakeOnLANDistributionJob AS j
			WHERE j.TaskUID = t.TaskUID
		)
	)

	-- Remove any actions (and therefore actionapplies)
	DELETE FROM ActionApplies
	WHERE EXISTS
	(
		SELECT * FROM Action
		WHERE ActionApplies.ActionUID = Action.ActionUID
		AND ServerUID = @ServerUID
	)
	DELETE FROM Action
	WHERE ServerUID = @ServerUID

	-- Remove any jobs
	DELETE FROM Job
	WHERE ServerUID = @ServerUID

	-- Remove any empty tasks (from action removals)
	DELETE FROM Task
	WHERE NOT EXISTS
	(
		SELECT * FROM Action
		WHERE Task.TaskID = Action.TaskID
	)
	AND NOT EXISTS
	(
		SELECT * FROM Job
		WHERE Task.TaskID = Job.TaskID
	)

	-- Remove any networkdevicediscoveredbys
	DELETE FROM NetworkDeviceDiscoveredBy
	WHERE ServerUID = @ServerUID

	-- Remove any memberships of Distribution Groups
	DELETE FROM DistributionGroupMember
	WHERE MemberID = @ServerUID

	-- Remove the distribution server
	DELETE FROM DistributionServer
	WHERE ServerUID = @ServerUID
END

GO

PRINT 'Creating procedure to mark the result of a remote execution distribution'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'RemoteExec_Complete'
)
	DROP PROCEDURE RemoteExec_Complete
GO
CREATE PROCEDURE RemoteExec_Complete
	@Uid binary(16),
	@InActionStateID int,
	@InFailureReason ntext
AS
	-- Update all records for the given job UID where the state is
	-- DistributionInProgress, as other logs may already have been
	-- processed moving the state to scheduled or beyond.
	UPDATE [Action]
	SET ActionStateID = @InActionStateID,
	    FailureReason = @InFailureReason
	WHERE JobUID = @Uid
	  AND ActionStateID = 2
GO

PRINT 'Creating procedure for distribution groups'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'FactoryDistributionGroupCreate')
	DROP PROCEDURE FactoryDistributionGroupCreate
GO
CREATE PROCEDURE FactoryDistributionGroupCreate
@p_GroupName 	nvarchar(128),
@p_GroupGuid 	binary(16)
AS
	IF NOT EXISTS(
		SELECT * FROM DistributionGroup
			WHERE GroupName = @p_GroupName
	)
	BEGIN
		INSERT INTO DistributionGroup (GroupUID, GroupName)
			VALUES (@p_GroupGuid, @p_GroupName)

		INSERT INTO DistributionGroupMember (GroupUID, MemberID, MemberType)
			SELECT	@p_GroupGuid,
				ServerUID,
				11
			FROM DistributionServer
				WHERE ServerType = 0
	END
GO

PRINT 'Creating procedure to retrieve the list of policy quarantined distribution locations'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'GetQuarantinedLocations'
)
	DROP PROCEDURE GetQuarantinedLocations
GO
CREATE PROCEDURE GetQuarantinedLocations
AS
	SELECT	ServerUID
	FROM	DistributionServer
	WHERE	PolicyQuarantined = 1
GO

PRINT 'Creating procedure to set the quarantined state of a distribution location'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'SetQuarantinedFlag'
)
	DROP PROCEDURE SetQuarantinedFlag
GO
CREATE PROCEDURE SetQuarantinedFlag
	@Uid binary(16),
	@State bit
AS
	UPDATE	DistributionServer
	SET	PolicyQuarantined = @State
	WHERE	ServerUID = @Uid
GO

PRINT 'Creating procedure to signal the completion of a policy rollback'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'PolicyRollback_Complete'
)
	DROP PROCEDURE PolicyRollback_Complete
GO
CREATE PROCEDURE PolicyRollback_Complete
	@Uid binary(16),
	@ObjectId nvarchar(256),
	@paramConfirmedState nvarchar(16),
	@paramLastConfirmedUpdate datetime,
	@paramLastConfirmedVersion nvarchar(32)
AS
	DECLARE @OldPackageVersionID AS INT
	SELECT @OldPackageVersionID =
			ISNULL(dp.ConfirmedVersionID, dp.RequestedVersionID)
		FROM DistributedPackage AS dp,
		     PackageVersion AS pv,
		     PackagePath AS pp
		WHERE dp.ServerUID = @Uid
		  AND pv.PackageVersionID =
			ISNULL(dp.ConfirmedVersionID, dp.RequestedVersionID)
		  AND pv.PackagePathID = pp.PackagePathID
		  AND pp.PackageFullName = @ObjectId

	DECLARE @NewPackageVersionID AS INT
	SELECT @NewPackageVersionID = pv.PackageVersionID
		FROM PackageVersion AS pv,
		     PackagePath AS pp
		WHERE pp.PackageFullName = @ObjectID
		  AND pv.PackagePathID = pp.PackagePathID
		  AND pv.Version = @paramLastConfirmedVersion

	IF @OldPackageVersionID IS NOT NULL
	BEGIN
		-- do the update here
		UPDATE [DistributedPackage]
		SET ConfirmedVersionID = @NewPackageVersionID,
		    ConfirmedState = @paramConfirmedState,
		    ConfirmedDate = @paramLastConfirmedUpdate,
		    ConfirmedReason = '',
		    RequestState = 'empty'
		WHERE ServerUID = @Uid
		  AND ISNULL(ConfirmedVersionID, RequestedVersionID) =
				@OldPackageVersionID
	END
	ELSE
	BEGIN
		-- do the insert here
		INSERT INTO [DistributedPackage]
		(ServerUID, RequestedVersionID, RequestDate,
		 ConfirmedVersionID, ConfirmedState, ConfirmedDate,
		 ConfirmedReason, RequestState)
		VALUES
		(@Uid, @NewPackageVersionID, @paramLastConfirmedUpdate,
		 @NewPackageVersionID, @paramConfirmedState,
		 @paramLastConfirmedUpdate, '', 'empty')
	END
GO

/* 
 * $Id: PackageVersionList.sql 48466 2003-07-10 06:50:53Z chrish $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: PackageVersionList
 *	Input:
 *	- @pkgName: Package Name. - All Packages (default) /Specific Package Name
 *
 *	Returns:
 *	- PackageName, Version, PackageFullName
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'PackageVersionList' AND xtype = 'P'
)
        DROP PROCEDURE PackageVersionList 
GO

CREATE PROCEDURE [PackageVersionList]
	@pkgName VARCHAR(128)='%'  --Match on specific PackageName (default: all software)
AS
BEGIN
	IF @pkgName = '%'   -- Get ALL packages
		SELECT	PackageName, Version, PackageFullName
		FROM	PackageVersion AS v,
			MediaContainsPackageVersion AS mcp,
			PackagePath AS p,
			PackageFamily AS f
		WHERE	v.PackageVersionID = mcp.PackageVersionID
		  AND	v.PackagePathID = p.PackagePathID
		  AND	v.PackageFamilyID = f.PackageFamilyID
		  AND	mcp.MediaID = 1
		  AND	p.PackageFullName NOT LIKE 'PolicyArchive%'
		ORDER BY PackageName

	ELSE	-- Filter on the specified package name
		SELECT	PackageName, Version, PackageFullName
		FROM	PackageVersion AS v,
			MediaContainsPackageVersion AS mcp,
			PackagePath AS p,
			PackageFamily AS f
		WHERE	v.PackageVersionID = mcp.PackageVersionID
		  AND	v.PackagePathID = p.PackagePathID
		  AND	v.PackageFamilyID = f.PackageFamilyID
		  AND	mcp.MediaID = 1
		  AND	p.PackageFullName NOT LIKE 'PolicyArchive%'
		  AND	f.PackageName LIKE @pkgName
		ORDER BY PackageName

END
GO

/*
 * $Id: OrganizationDomain.sql 84480 2007-07-24 06:34:27Z pca $
 *
 * Stored procedures to produce reports on Organization info.
 */

/*
 * Calculate the set of Organizations.
 * The #Organization temporary table must exist.
 */

-- USE ManageSoft
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'OrganizationIdentifyDescendentsByDomainRDN')
	DROP PROCEDURE OrganizationIdentifyDescendentsByDomainRDN
GO
CREATE PROCEDURE OrganizationIdentifyDescendentsByDomainRDN
	@RDN NVARCHAR(800)='%',
	@DomainDN NVARCHAR(800)='%',
	@RDNMatch BIT=1, --Match on OUs include sub-OUs [True=1|False=0]
	@DomainDNMatch BIT=1 --Match on DNs include child-DNs [True=1|False=0]
AS
BEGIN
	IF (@RDN IS NULL)
		SET @RDN = '<NULL>'
	
	IF (@DomainDN = '%' OR
		(@DomainDN IS NULL AND (@RDN = '' OR (@RDN = '%' AND @RDNMatch = 1))))
		INSERT #Organization
			SELECT o.OrganizationID
			FROM Organization AS o, Domain AS d
			WHERE o.DomainID = d.OrganizationID
				AND d.DN IS NULL
	
	IF (@DomainDN = '%' OR @DomainDNMatch = 1)
		INSERT #Organization
			SELECT o.OrganizationID
			FROM Organization AS o, Domain AS d
			WHERE o.DomainID = d.OrganizationID
				AND d.DN LIKE '%' + @DomainDN
	ELSE
	BEGIN
		IF (@RDN = '<NULL>' OR (@RDN = '%' AND @RDNMatch = 1))
			INSERT #Organization
				SELECT o.OrganizationID
				FROM Organization AS o, Domain AS d
				WHERE o.DomainID = d.OrganizationID
					AND o.RDN IS NULL
					AND d.DN = @DomainDN
		
		IF (@RDNMatch = 1)
			INSERT #Organization
				SELECT o.OrganizationID
				FROM Organization AS o, Domain AS d
				WHERE o.DomainID = d.OrganizationID
					AND o.RDN LIKE '%' + @RDN
					AND d.DN = @DomainDN
		ELSE
			INSERT #Organization
				SELECT o.OrganizationID
				FROM Organization AS o, Domain AS d
				WHERE o.DomainID = d.OrganizationID
					AND o.RDN = @RDN
					AND d.DN = @DomainDN
	END
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'OrganizationIdentifyDescendentsByOUDN')
	DROP PROCEDURE OrganizationIdentifyDescendentsByOUDN
GO
CREATE PROCEDURE OrganizationIdentifyDescendentsByOUDN
	@OUDN NVARCHAR(800)='%',
	@RDNMatch BIT=1, --Match on OUs include sub-OUs [True=1|False=0]
	@DomainDNMatch BIT=1 --Match on DNs include child-DNs [True=1|False=0]
AS
BEGIN
	/*** Calculate the OURDN and the DomainDN ***/
	DECLARE @RDN NVARCHAR(800)
	DECLARE @DomainDN NVARCHAR(800)
	EXEC OUDN_to_RDNandDomainDN @OUDN, @RDN OUTPUT, @DomainDN OUTPUT
	/********************************************/
	
	EXEC OrganizationIdentifyDescendentsByDomainRDN @RDN, @DomainDN, @RDNMatch, @DomainDNMatch
END
GO
/*
 * $Id: SoftwarePackageInstallationDetail.sql 84480 2007-07-24 06:34:27Z pca $
 *
 * Stored procedures to report all succeeded/failed TargetedPackage (RSOP)
 * Installations
 */

/*
 * Enumerate the successful/failed applications of Policy
 * for packages which are selected in #Packages matching @pkgVer
 * on computers in an OU matching oudn
 *
 * TargetTypeID must be the value for 'Computer'
 */
IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE name = 'SoftwarePackageInstallationDetailComputerMatchOU' AND xtype = 'P'
)
	DROP PROCEDURE SoftwarePackageInstallationDetailComputerMatchOU
GO
CREATE PROCEDURE SoftwarePackageInstallationDetailComputerMatchOU
	@pkgName	VARCHAR(128) = '%',
	@pkgVer		VARCHAR(32) = '%',
	@pkgFName	VARCHAR(256) = '%',
	@installPolicy	VARCHAR(16) = NULL,
	@Status		VARCHAR(16) = 'success',
	@actionMatch	VARCHAR(10) = NULL
AS
	-- see comments for SoftwarePackageInstallationDetailComputerExactOU
	DECLARE @TargetTypeID	INT		-- TargetTypeId of 'Computer'
	SET @TargetTypeID =
		(SELECT TargetTypeID FROM TargetType
		 WHERE TargetTypeName = 'Computer')

	SELECT	pp.PackageFullName		-- CHANGED
		,pf.PackageName			-- CHANGED
		,pv.Version
		,case
			when ntt.[Action] is null then 'Null'
			else ntt.[Action]
		end as [InstallPolicy]
		,UserOU = dbo.OUName(c_ou.OUID)
		,UserCN = 'SYSTEM'
		,ComputerOU = dbo.OUName(c_ou.OUID)
		,ComputerCN = c.ComputerCN
		,i.Reported
		,r.ReasonText AS FailReason
		,InstallationAction = i.[Action]
		,ntt.PostponeNoLaterThan
		,ntt.PostponeNoLaterThanIsLocal
		,ntt.PostponePeriod
		,ntt.PostponePeriodStart
		,ntt.PostponeLatest
	FROM
		PackageVersion AS pv-- CHANGED
		INNER JOIN PackageFamily AS pf-- CHANGED
			ON pf.PackageFamilyID = pv.PackageFamilyID-- CHANGED
		INNER JOIN PackagePath AS pp-- CHANGED
			ON pp.PackagePathID = pv.PackagePathID-- CHANGED
		INNER JOIN Installation AS i-- CHANGED
			ON i.PackageVersionID = pv.PackageVersionID-- CHANGED
		LEFT OUTER JOIN Reason AS r
			ON i.FailReasonID = r.ReasonID
		INNER JOIN Computer as c
			ON	i.ComputerID = c.ComputerID	-- on this computer
			AND	i.OrganizationID = c.ComputerOUID -- in this OU
		INNER JOIN #Organization as c_ou
			ON	c.ComputerOUID = c_ou.OUID
		LEFT OUTER JOIN (
			SELECT	DISTINCT ppath.PackageFullName
				,ppath.PackagePathID
				,pversion.PackageVersionID-- CHANGED
				,pfamily.PackageFamilyID
				,ad.Action
				,pa.TargetID
				,pa.TargetOUID
				,ad.PostponeNoLaterThan
				,ad.PostponeNoLaterThanIsLocal
				,ad.PostponePeriod
				,ip.PostponePeriodStart
				,ad.PostponeLatest
			FROM	PackageApplies AS pa
			INNER JOIN AllocationDetails AS ad
				ON pa.AllocationDetailsID = ad.AllocationDetailsID
			INNER JOIN PackagePath AS ppath
				ON ppath.PackagePathID = pa.PackagePathID
			INNER JOIN PackageVersion AS pversion
				ON pversion.PackagePathID = pa.PackagePathID
			INNER JOIN PackageFamily AS pfamily
				ON pfamily.PackageFamilyID = pversion.PackageFamilyID
			LEFT OUTER JOIN InstallationPostponement AS ip
				ON ip.TargetTypeID = @TargetTypeID
				AND ip.TargetID = pa.TargetID
				AND ip.PackagePathID = ppath.PackagePathID
				AND ip.PolicyGUID = pa.PolicyGUID
			WHERE	pa.TargetTypeID = @TargetTypeID

			UNION

			SELECT	DISTINCT ppath.PackageFullName
				,ppath.PackagePathID
				,pversion.PackageVersionID-- CHANGED
				,pfamily.PackageFamilyID
				,ad.Action
				,m.TargetID
				,comp.ComputerOUID AS TargetOUID
				,ad.PostponeNoLaterThan
				,ad.PostponeNoLaterThanIsLocal
				,ad.PostponePeriod
				,ip.PostponePeriodStart
				,ad.PostponeLatest
			FROM	PackageApplies AS pa
			INNER JOIN Member AS m
				ON m.GroupID = pa.TargetID
				AND m.TargetTypeID = @TargetTypeID
			INNER JOIN Computer AS comp
				ON comp.ComputerID = m.TargetID
			INNER JOIN AllocationDetails AS ad
				ON pa.AllocationDetailsID = ad.AllocationDetailsID
			INNER JOIN PackagePath AS ppath
				ON ppath.PackagePathID = pa.PackagePathID
			INNER JOIN PackageVersion AS pversion
				ON pversion.PackagePathID = pa.PackagePathID
			INNER JOIN PackageFamily AS pfamily
				ON pfamily.PackageFamilyID = pversion.PackageFamilyID
			LEFT OUTER JOIN InstallationPostponement AS ip
				ON ip.TargetTypeID = @TargetTypeID
				AND ip.TargetID = m.TargetID
				AND ip.PackagePathID = ppath.PackagePathID
				AND ip.PolicyGUID = pa.PolicyGUID
			WHERE	pa.TargetTypeID = 3
		) AS ntt ON ntt.PackageVersionID = pv.PackageVersionID-- CHANGED
			AND ntt.TargetID = i.ComputerID
			AND ntt.TargetOUID = i.OrganizationID-- CHANGED
	WHERE	pf.PackageName LIKE @pkgName		-- desired package
	  AND	pp.PackageFullName LIKE @pkgFName	-- desired path
	  AND	pv.Version LIKE @pkgVer			-- desired version
	  AND	i.UserID = 1				-- Computer install
	  AND	i.Result = @Status			-- only this status
	  AND	(
		@actionMatch IS NULL
		OR i.[Action] = @actionMatch
		OR (@actionMatch = 'install'
		   AND LEFT(i.[Action], 7) = 'install'
		   AND ntt.TargetID IS NOT NULL)	-- Disregard if pending redundant
	  )
	  AND	(
		@installPolicy IS NULL
		OR (	@installPolicy = 'install'	-- Look at installs
			AND ntt.Action = 'install'	-- where policy says install
		)
		OR (	@installPolicy = 'alwaysupdate'
			AND ntt.Action = 'alwaysupdate'
			AND i.Result <> 'success'
			AND EXISTS (
				SELECT	*
				FROM	Installation i2
					INNER JOIN PackageVersion pv2
						ON i2.PackageVersionID = pv2.PackageVersionID
				WHERE i2.Result = 'success'
				AND pv2.PackageFamilyID = ntt.PackageFamilyID
				AND pv2.PackagePathID <> ntt.PackagePathID
				AND i2.ComputerID = i.ComputerID
				AND i2.UserID = i.UserID
				AND i2.OrganizationID = i.OrganizationID-- CHANGED
			)
		)
		OR (	@installPolicy = 'choose'
			AND (	ntt.Action = 'choose'
				OR (	ntt.Action = 'alwaysupdate'
					AND (	i.Result = 'success'
						OR NOT EXISTS (
							SELECT	*
							FROM	Installation i2
								INNER JOIN PackageVersion pv2
									ON i2.PackageVersionID = pv2.PackageVersionID
							WHERE i2.Result = 'success'
							AND pv2.PackageFamilyID = ntt.PackageFamilyID
							AND pv2.PackagePathID <> ntt.PackagePathID
							AND i2.ComputerID = i.ComputerID
							AND i2.UserID = i.UserID
							AND i2.OrganizationID = i.OrganizationID-- CHANGED
						)
					)
				)
			)
		)
	    )
	ORDER BY pp.PackageFullName, pv.Version, dbo.OUName(c_ou.OUID), ComputerCN

GO

/*
 * Enumerate the successful applications of Policy
 * for packages which are selected in #Packages matching @pkgVer
 * by users in an OU matching oudn
 */
IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE name = 'SoftwarePackageInstallationDetailUserMatchOU' AND xtype = 'P'
)
	DROP PROCEDURE SoftwarePackageInstallationDetailUserMatchOU
GO

CREATE PROCEDURE SoftwarePackageInstallationDetailUserMatchOU
	@pkgName	VARCHAR(128) = '%',
	@pkgVer		VARCHAR(32) = '%',
	@pkgFName	VARCHAR(256) = '%',
	@installPolicy	VARCHAR(16) = NULL,
	@Status		VARCHAR(16) = 'success',
	@actionMatch	VARCHAR(10) = NULL
AS
	-- see comments for SoftwarePackageInstallationDetailComputerExactOU
	DECLARE @TargetTypeID	INT		-- TargetTypeId 'User'
	SET @TargetTypeID =
		(SELECT TargetTypeID FROM TargetType
		 WHERE TargetTypeName = 'User')

	SELECT	pp.PackageFullName
		,pf.PackageName
		,pv.Version
		,case
			when ntt.[Action] is null then 'Null'
			else ntt.[Action]
		end as [InstallPolicy]
		,UserOU = dbo.OUName(u_ou.OUID)
		,UserCN = u.UserCN
		,ComputerOU = dbo.OUName(c.ComputerOUID)
		,ComputerCN = c.ComputerCN
		,i.Reported
		,r.ReasonText AS FailReason
		,InstallationAction = i.[Action]
		,ntt.PostponeNoLaterThan
		,ntt.PostponeNoLaterThanIsLocal
		,ntt.PostponePeriod
		,ntt.PostponePeriodStart
		,ntt.PostponeLatest
	FROM
		PackageVersion AS pv
		INNER JOIN PackageFamily AS pf
			ON pf.PackageFamilyID = pv.PackageFamilyID
		INNER JOIN PackagePath AS pp
			ON pp.PackagePathID = pv.PackagePathID
		INNER JOIN Installation AS i
			ON i.PackageVersionID = pv.PackageVersionID
		LEFT OUTER JOIN Reason AS r
			ON i.FailReasonID = r.ReasonID
		INNER JOIN [User] as u
			ON	i.UserID = u.UserID		-- installing user
			AND	i.OrganizationID = u.UserOUID		-- in this OU
		INNER JOIN #Organization as u_ou
			ON	u.UserOUID = u_ou.OUID
		INNER JOIN Computer as c
			ON	i.ComputerID = c.ComputerID	-- on this computer
		LEFT OUTER JOIN (
			SELECT	DISTINCT ppath.PackageFullName
				,ppath.PackagePathID
				,pversion.PackageVersionID-- CHANGED
				,pfamily.PackageFamilyID
				,ad.Action
				,pa.TargetID
				,pa.TargetOUID
				,ad.PostponeNoLaterThan
				,ad.PostponeNoLaterThanIsLocal
				,ad.PostponePeriod
				,ip.PostponePeriodStart
				,ad.PostponeLatest
			FROM	PackageApplies AS pa
			INNER JOIN AllocationDetails AS ad
				ON pa.AllocationDetailsID = ad.AllocationDetailsID
			INNER JOIN PackagePath AS ppath
				ON ppath.PackagePathID = pa.PackagePathID
			INNER JOIN PackageVersion AS pversion
				ON pversion.PackagePathID = pa.PackagePathID
			INNER JOIN PackageFamily AS pfamily
				ON pfamily.PackageFamilyID = pversion.PackageFamilyID
			LEFT OUTER JOIN InstallationPostponement AS ip
				ON ip.TargetTypeID = @TargetTypeID
				AND ip.TargetID = pa.TargetID
				AND ip.PackagePathID = ppath.PackagePathID
				AND ip.PolicyGUID = pa.PolicyGUID
			WHERE	pa.TargetTypeID = @TargetTypeID

			UNION

			SELECT	DISTINCT ppath.PackageFullName
				,ppath.PackagePathID
				,pversion.PackageVersionID-- CHANGED
				,pfamily.PackageFamilyID
				,ad.Action
				,m.TargetID
				,[user].UserOUID AS TargetOUID
				,ad.PostponeNoLaterThan
				,ad.PostponeNoLaterThanIsLocal
				,ad.PostponePeriod
				,ip.PostponePeriodStart
				,ad.PostponeLatest
			FROM	PackageApplies AS pa
			INNER JOIN Member AS m
				ON m.GroupID = pa.TargetID
				AND m.TargetTypeID = @TargetTypeID
			INNER JOIN [User] AS [user]
				ON [user].UserID = m.TargetID
			INNER JOIN AllocationDetails AS ad
				ON pa.AllocationDetailsID = ad.AllocationDetailsID
			INNER JOIN PackagePath AS ppath
				ON ppath.PackagePathID = pa.PackagePathID
			INNER JOIN PackageVersion AS pversion
				ON pversion.PackagePathID = pa.PackagePathID
			INNER JOIN PackageFamily AS pfamily
				ON pfamily.PackageFamilyID = pversion.PackageFamilyID
			LEFT OUTER JOIN InstallationPostponement AS ip
				ON ip.TargetTypeID = @TargetTypeID
				AND ip.TargetID = m.TargetID
				AND ip.PackagePathID = ppath.PackagePathID
				AND ip.PolicyGUID = pa.PolicyGUID
			WHERE	pa.TargetTypeID = 3
		) AS ntt ON ntt.PackageVersionID = pv.PackageVersionID
			AND ntt.TargetID = i.UserID
			AND ntt.TargetOUID = i.OrganizationID
	WHERE	pf.PackageName LIKE @pkgName		-- desired package
	  AND	pp.PackageFullName LIKE @pkgFName	-- desired path
	  AND	pv.Version LIKE @pkgVer			-- desired version
	  AND	i.Result = @Status			-- only this status
	  AND	i.UserID <> 1				-- User install
	  AND	(
		@actionMatch IS NULL
		OR i.[Action] = @actionMatch
		OR (@actionMatch = 'install'
		   AND LEFT(i.[Action], 7) = 'install'
		   AND ntt.TargetID IS NOT NULL)	-- Disregard if pending redundant
	  )
	  AND	(
		@installPolicy IS NULL
		OR (	@installPolicy = 'install'
			AND ntt.Action = 'install'
		)
		OR (	@installPolicy = 'alwaysupdate'
			AND ntt.Action = 'alwaysupdate'
			AND i.Result <> 'success'
			AND EXISTS (
				SELECT	*
				FROM	Installation i2
					INNER JOIN PackageVersion pv2
						ON i2.PackageVersionID = pv2.PackageVersionID
				WHERE i2.Result = 'success'
				AND pv2.PackageFamilyID = ntt.PackageFamilyID
				AND pv2.PackagePathID <> ntt.PackagePathID
				AND i2.ComputerID = i.ComputerID
				AND i2.UserID = i.UserID
				AND i2.OrganizationID = i.OrganizationID
			)
		)
		OR (	@installPolicy = 'choose'
			AND (	ntt.Action = 'choose'
				OR (	ntt.Action = 'alwaysupdate'
					AND (	i.Result = 'success'
						OR NOT EXISTS (
							SELECT	*
							FROM	Installation i2
								INNER JOIN PackageVersion pv2
									ON i2.PackageVersionID = pv2.PackageVersionID
							WHERE i2.Result = 'success'
							AND pv2.PackageFamilyID = ntt.PackageFamilyID
							AND pv2.PackagePathID <> ntt.PackagePathID
							AND i2.ComputerID = i.ComputerID
							AND i2.UserID = i.UserID
							AND i2.OrganizationID = i.OrganizationID
						)
					)
				)
			)
		)
	    )
	ORDER BY pp.PackageFullName, pv.Version,
		dbo.OUName(u_ou.OUID), UserCN,
		dbo.OUName(c.ComputerOUID), ComputerCN

GO

/*
 * Enumerate the successful/failed non-Policy installs
 * for packages which are selected in #Packages matching @pkgVer
 * on computers in an OU matching oudn
 *
 * TargetTypeID must be the value for 'Computer'
 */
IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE name = 'SoftwarePackageInstallationNonPolicyComputerMatchOU' AND xtype = 'P'
)
	DROP PROCEDURE SoftwarePackageInstallationNonPolicyComputerMatchOU
GO

CREATE PROCEDURE SoftwarePackageInstallationNonPolicyComputerMatchOU
	@pkgName	VARCHAR(128) = '%',
	@pkgVer		VARCHAR(32) = '%',
	@pkgFName	VARCHAR(256) = '%',
	@Status		VARCHAR(16) = 'success',
	@actionMatch VARCHAR(10) = NULL
AS
	DECLARE @TargetTypeID	INT		-- TargetTypeId of 'Computer'
	SET @TargetTypeID =
		(SELECT TargetTypeID FROM TargetType
		 WHERE TargetTypeName = 'Computer')

	SELECT	pp.PackageFullName
		,pf.PackageName
		,pv.Version
		,'Null' as InstallPolicy
		,UserOU = dbo.OUName(c_ou.OUID)
		,UserCN = 'SYSTEM'
		,ComputerOU = dbo.OUName(c_ou.OUID)
		,ComputerCN = c.ComputerCN
		,i.Reported
		,r.ReasonText AS FailReason
		,InstallationAction = i.[Action]
		,NULL AS PostponeNoLaterThan
		,NULL AS PostponeNoLaterThanIsLocal
		,NULL AS PostponePeriod
		,NULL AS PostponePeriodStart
		,NULL AS PostponeLatest
	FROM
		PackageFamily as pf,
		PackageVersion as pv,
		PackagePath as pp,
		Installation as i
		LEFT OUTER JOIN Reason AS r
			ON i.FailReasonID = r.ReasonID,
		Computer as c,
		#Organization as c_ou
	WHERE	pf.PackageName LIKE @pkgName		-- desired family
	  AND	pp.PackageFullName LIKE @pkgFName	-- desired path
	  AND	pf.PackageFamilyID = pv.PackageFamilyID -- any version
	  AND	pv.PackagePathID = pp.PackagePathID
	  AND	pv.Version LIKE @pkgVer			-- having this version
	  AND	pv.PackageVersionID = i.PackageVersionID-- ... matches installed
	  AND	1 = i.UserID				-- Computer install
	  AND	@Status = i.Result			-- only this status
	  AND	i.ComputerID = c.ComputerID		-- On this computer
	  AND	c.ComputerOUID = c_ou.OUID		-- which is this OU
	  AND NOT EXISTS(				-- no policy for install
		SELECT *
		FROM	PackageApplies AS pa
		WHERE	pa.TargetTypeID = @TargetTypeID -- Computer policy type
		  AND	pa.TargetOUID = i.OrganizationID -- for this OU
		  AND	pa.TargetID = i.ComputerID	-- Installing computer
		  AND	pa.PackagePathID = pp.PackagePathID
	    )
	  AND NOT EXISTS(				-- no policy for install
		SELECT *
		FROM	PackageApplies AS pa,
			Member AS m,
			Computer AS c
		WHERE	pa.TargetTypeID = 3 -- RSOP Group
		  AND	m.GroupID = pa.TargetID -- Member of group
		  AND	m.TargetTypeID = @TargetTypeID -- Computer policy type
		  AND	m.TargetID = i.ComputerID	-- Installing computer
		  AND	pa.PackagePathID = pp.PackagePathID
		  AND	c.ComputerOUID = i.OrganizationID -- for this OU
	    )
	  AND	(
		@actionMatch IS NULL
		OR i.[Action] = @actionMatch
		OR (@actionMatch = 'install'
		   AND LEFT(i.[Action], 7) = 'install')
		OR (@actionMatch = 'redundant'
		   AND i.[Action] = 'installex')
	  )
	ORDER BY pp.PackageFullName, pv.Version, dbo.OUName(c_ou.OUID), ComputerCN
GO

/*
 * Enumerate the successful/failed non-Policy installs
 * for packages which are selected in #Packages matching @pkgVer
 * by users in an OU matching oudn
 */
IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE name = 'SoftwarePackageInstallationNonPolicyUserMatchOU' AND xtype = 'P'
)
	DROP PROCEDURE SoftwarePackageInstallationNonPolicyUserMatchOU
GO

CREATE PROCEDURE SoftwarePackageInstallationNonPolicyUserMatchOU
	@pkgName	VARCHAR(128) = '%',
	@pkgVer		VARCHAR(32) = '%',
	@pkgFName	VARCHAR(256) = '%',
	@Status		VARCHAR(16) = 'success',
	@actionMatch	VARCHAR(10) = NULL
AS
	DECLARE @TargetTypeID	INT		-- TargetTypeId 'User'
	SET @TargetTypeID =
		(SELECT TargetTypeID FROM TargetType
		 WHERE TargetTypeName = 'User')

	SELECT	pp.PackageFullName
		,pf.PackageName
		,pv.Version
		,'Null' as InstallPolicy
		,UserOU = dbo.OUName(u_ou.OUID)
		,UserCN = u.UserCN
		,ComputerOU = dbo.OUName(c.ComputerOUID)
		,ComputerCN = c.ComputerCN
		,i.Reported
		,r.ReasonText AS FailReason
		,InstallationAction = i.[Action]
		,NULL AS PostponeNoLaterThan
		,NULL AS PostponeNoLaterThanIsLocal
		,NULL AS PostponePeriod
		,NULL AS PostponePeriodStart
		,NULL AS PostponeLatest
	FROM
		PackageFamily as pf,
		PackageVersion as pv,
		PackagePath as pp,
		Installation AS i
		LEFT OUTER JOIN Reason AS r
			ON i.FailReasonID = r.ReasonID,
		[User] as u,
		#Organization as u_ou,
		Computer as c
	WHERE	pf.PackageName LIKE @pkgName		-- desired family
	  AND	pp.PackageFullName LIKE @pkgFName	-- desired path
	  AND	pf.PackageFamilyID = pv.PackageFamilyID	-- any version
	  AND	pv.Version LIKE @pkgVer			-- desired version
	  AND	pv.PackagePathID = pp.PackagePathID
	  AND	pv.PackageVersionID = i.PackageVersionID-- ... matches installed
	  AND	@Status = i.Result			-- only this status
	  AND	1 <> i.UserID				-- User install
	  AND	i.UserID = u.UserID			-- installing user
	  AND	u.UserOUID = u_ou.OUID			-- who is in this OU
	  AND	i.ComputerID = c.ComputerID		-- Installing computer
	  AND NOT EXISTS(				-- no policy for install
		SELECT *
		FROM	PackageApplies AS pa
		WHERE	pa.TargetTypeID = @TargetTypeID -- User policy type
		  AND	pa.TargetOUID = i.OrganizationID -- for this OU
		  AND	pa.TargetID = i.UserID	-- Installing user
		  AND	pa.PackagePathID = pp.PackagePathID
	    )
	  AND NOT EXISTS(				-- no policy for install
		SELECT *
		FROM	PackageApplies AS pa,
			Member AS m,
			[User] AS u
		WHERE	pa.TargetTypeID = 3 -- RSOP Group
		  AND	m.GroupID = pa.TargetID -- Member of group
		  AND	m.TargetTypeID = @TargetTypeID -- User policy type
		  AND	m.TargetID = i.UserID	-- Installing user
		  AND	pa.PackagePathID = pp.PackagePathID
		  AND	u.UserOUID = i.OrganizationID -- for this OU
	    )
	  AND	(
		@actionMatch IS NULL
		OR i.[Action] = @actionMatch
		OR (@actionMatch = 'install'
		   AND LEFT(i.[Action], 7) = 'install')
		OR (@actionMatch = 'redundant'
		   AND i.[Action] = 'installex')
	  )
	ORDER BY pp.PackageFullName, pv.Version,
		dbo.OUName(u_ou.OUID), UserCN,
		dbo.OUName(c.ComputerOUID), ComputerCN
GO

/*
 * Enumerate Successful Policy-applications/out-of-policy-installs in OU
 *
 * TargetTypeName must be 'Computer' or 'User' (or any other value
 * which may have been inserted into the TargetTypes table).
 *
 * oudn is one of the OU field values from the SDOU table, or a wildcard:
 *
 * ouMatch is non-zero if the oudn string is to be matched with wildcards,
 * then any wild-card characters must be escaped to be matched normally.
 *
 * PackageName and Version are the short-name and version of the package(s) to
 * be matched. Wildcards are allowed.
 *
 * The returned ResultSet contains ...
 */
IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE name = 'SoftwarePackageInstallationSuccess' AND xtype = 'P'
)
	DROP PROCEDURE SoftwarePackageInstallationSuccess
GO

CREATE PROCEDURE SoftwarePackageInstallationSuccess
	@TargetTypeName VARCHAR(256),
	@oudn		VARCHAR(800),
	@ouMatch	INT = 0,		-- actually boolean
	@pkgName	VARCHAR(128) = '%',
	@pkgVer		VARCHAR(32)= '%',
	@pkgFName	VARCHAR(256) = '%',
	@installPolicy	VARCHAR(16) = NULL,
	@actionMatch	VARCHAR(10) = NULL
AS
BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

    IF (@installPolicy IS NULL	-- see SoftwarePackageInstallationSummary
     OR @installPolicy <> 'out of policy')
    BEGIN
	    IF (@TargetTypeName = 'Computer')
		EXECUTE SoftwarePackageInstallationDetailComputerMatchOU
				@pkgName,
				@pkgVer,
				@pkgFName,
				@installPolicy,
				'success',
				@actionMatch
	    ELSE
		EXECUTE SoftwarePackageInstallationDetailUserMatchOU
				@pkgName,
				@pkgVer,
				@pkgFName,
				@installPolicy,
				'success',
				@actionMatch
    END
    ELSE
    BEGIN
	    IF (@TargetTypeName = 'Computer')
		EXECUTE SoftwarePackageInstallationNonPolicyComputerMatchOU
				@pkgName,
				@pkgVer,
				@pkgFName,
				'success',
				@actionMatch
	    ELSE
		EXECUTE SoftwarePackageInstallationNonPolicyUserMatchOU
				@pkgName,
				@pkgVer,
				@pkgFName,
				'success',
				@actionMatch
    END
END

GO

/*
 * Enumerate Failed Policy-applications/out-of-policy-installs in OU
 *
 * TargetTypeName must be 'Computer' or 'User' (or any other value
 * which may have been inserted into the TargetTypes table).
 *
 * oudn is one of the OU field values from the SDOU table, or a wildcard:
 *
 * ouMatch is non-zero if the oudn string is to be matched with wildcards,
 * then any wild-card characters must be escaped to be matched normally.
 *
 * PackageName and Version are the short-name and version of the package(s) to
 * be matched. Wildcards are allowed.
 *
 * This stored procedure services the following data manager:
 *	o SoftwarePackageInstallationPostponed
 *	o SoftwarePackageInstallationFailure
 *
 * The returned ResultSet contains ...
 */
IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE name = 'SoftwarePackageInstallationDetails' AND xtype = 'P'
)
	DROP PROCEDURE SoftwarePackageInstallationDetails
GO

CREATE PROCEDURE SoftwarePackageInstallationDetails
	@TargetTypeName VARCHAR(256),
	@oudn		VARCHAR(800),
	@ouMatch	BIT = 0,		-- actually boolean
	@pkgName	VARCHAR(128) = '%',
	@pkgVer		VARCHAR(32)= '%',
	@pkgFName	VARCHAR(256) = '%',
	@installPolicy	VARCHAR(16) = NULL,
	@status		VARCHAR(16) = 'failure'
AS
BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

    IF (@installPolicy IS NULL	-- see SoftwarePackageInstallationSummary
     OR @installPolicy <> 'out of policy')
    BEGIN
	    IF (@TargetTypeName = 'Computer')
		EXECUTE SoftwarePackageInstallationDetailComputerMatchOU
				@pkgName,
				@pkgVer,
				@pkgFName,
				@installPolicy,
				@status
	    ELSE
		EXECUTE SoftwarePackageInstallationDetailUserMatchOU
				@pkgName,
				@pkgVer,
				@pkgFName,
				@installPolicy,
				@status
    END
    ELSE
    BEGIN
	    IF (@TargetTypeName = 'Computer')
		EXECUTE SoftwarePackageInstallationNonPolicyComputerMatchOU
				@pkgName,
				@pkgVer,
				@pkgFName,
				@status
	    ELSE
		EXECUTE SoftwarePackageInstallationNonPolicyUserMatchOU
				@pkgName,
				@pkgVer,
				@pkgFName,
				@status
    END
END

GO
/*
 * $Id: SoftwarePackageInstallationPending.sql 84480 2007-07-24 06:34:27Z pca $
 *
 * Stored procedures to report all pending TargetedPackage (RSOP)
 * Installations
 */

/*
 * DROP PROCEDURE SoftwarePackageInstallationPendingComputerMatchOU
 * DROP PROCEDURE SoftwarePackageInstallationPendingUserMatchOU
 * DROP PROCEDURE SoftwarePackageInstallationPending
 */

/*
 * Enumerate the pending applications of Policy
 * for packages which are selected in #Packages matching @pkgVer
 * on computers in an OU matching oudn
 *
 * TargetTypeID must be the value for 'Computer'
 */
IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE name = 'SoftwarePackageInstallationPendingComputerMatchOU' AND xtype = 'P'
)
	DROP PROCEDURE SoftwarePackageInstallationPendingComputerMatchOU
GO

CREATE PROCEDURE SoftwarePackageInstallationPendingComputerMatchOU
	@pkgName	VARCHAR(128) = '%',
	@pkgVer		VARCHAR(32) = '%',
	@pkgFName	VARCHAR(256) = '%',
	@installPolicy	VARCHAR(16) = ''
AS 
	DECLARE @TargetTypeID	INT		-- TargetTypeId of 'Computer'
	SET @TargetTypeID =
		(SELECT TargetTypeID FROM TargetType
		 WHERE TargetTypeName = 'Computer')

	SELECT	pp.PackageFullName,
		pf.PackageName,
		pv.Version,
		case
			when ad.[Action] is null then 'Null'
			else ad.[Action]
		end as [InstallPolicy],
		dbo.OUName(c_ou.OUID) AS UserOU,
		'SYSTEM' AS UserCN,
		dbo.OUName(c_ou.OUID) AS ComputerOU,
		c.ComputerCN AS ComputerCN,
		ad.EffectiveFrom,
		ad.EffectiveFromIsLocal
	FROM	PackageApplies AS pa,
		AllocationDetails AS ad,
		PackagePath AS pp,
		PackageFamily AS pf,
		PackageVersion AS pv,
		Computer AS c,
		#Organization AS c_ou
	WHERE 	pa.TargetTypeID = @TargetTypeID		-- Computer policy type
	  AND	pa.TargetOUID = c.ComputerOUID		-- Computer OU
	  AND	c.ComputerOUID = c_ou.OUID
	  AND	pa.TargetID = c.ComputerID		-- Target computer
	  AND	pa.AllocationDetailsID = ad.AllocationDetailsID
	  AND	pa.PackagePathID = pp.PackagePathID	-- Package in policy
	  AND	pp.PackagePathID = pv.PackagePathID	-- Package in policy
	  AND	pf.PackageFamilyID = pv.PackageFamilyID	-- in this family
	  AND	pf.PackageName LIKE @pkgName		-- desired package
	  AND	pp.PackageFullName LIKE @pkgFName	-- desired path
	  AND	pv.Version LIKE @pkgVer			-- desired version
	  AND NOT EXISTS(
	    	SELECT * FROM Installation AS i
		WHERE	pa.TargetOUID = i.OrganizationID-- Matching installed OU
		  AND	pa.TargetID = i.ComputerID	-- Installing computer
		  AND	pv.PackageVersionID = i.PackageVersionID
		  AND	i.UserID = 1			-- Computer install
	    )
	  AND	(
	  	@installPolicy IS NULL
		OR (	@installPolicy = 'install'
			AND ad.Action = 'install'
		)
		OR (	@installPolicy = 'choose'
			AND (	ad.Action = 'choose'
				OR (	ad.Action = 'alwaysupdate'
					AND NOT EXISTS (
						SELECT	*
						FROM	Installation i
							INNER JOIN PackageVersion pv2
								ON i.PackageVersionID = pv2.PackageVersionID
						WHERE i.Result = 'success'
						AND pv2.PackageFamilyID = pf.PackageFamilyID
						AND pv2.PackagePathID <> pa.PackagePathID
						AND i.ComputerID = c.ComputerID
						AND i.UserID = 1
						AND i.OrganizationID = c.ComputerOUID
					)
				)
			)
		)
		OR (	@installPolicy = 'alwaysupdate'
			AND ad.Action = 'alwaysupdate'
			AND EXISTS (
				SELECT	*
				FROM	Installation i
					INNER JOIN PackageVersion pv2
						ON i.PackageVersionID = pv2.PackageVersionID
				WHERE i.Result = 'success'
				AND pv2.PackageFamilyID = pf.PackageFamilyID
				AND pv2.PackagePathID <> pa.PackagePathID
				AND i.ComputerID = c.ComputerID
				AND i.UserID = 1
				AND i.OrganizationID = c.ComputerOUID
			)
		)
	  )

	UNION

	SELECT	pp.PackageFullName,
		pf.PackageName,
		pv.Version,
		case
			when ad.[Action] is null then 'Null'
			else ad.[Action]
		end as [InstallPolicy],
		dbo.OUName(c_ou.OUID) AS UserOU,
		'SYSTEM' AS UserCN,
		dbo.OUName(c_ou.OUID) AS ComputerOU,
		c.ComputerCN AS ComputerCN,
		ad.EffectiveFrom,
		ad.EffectiveFromIsLocal
	FROM	PackageApplies AS pa,
		Member AS m,
		AllocationDetails AS ad,
		PackagePath AS pp,
		PackageFamily AS pf,
		PackageVersion AS pv,
		Computer AS c,
		#Organization AS c_ou
	WHERE 	pa.TargetTypeID = 3			-- RSOP Group
	  AND	m.GroupID = pa.TargetID			-- Member of RSOP Group
	  AND	m.TargetTypeID = @TargetTypeID		-- Computer policy type
	  AND	m.TargetID = c.ComputerID		-- Target computer
	  AND	c.ComputerOUID = c_ou.OUID		-- This OU
	  AND	pa.AllocationDetailsID = ad.AllocationDetailsID
	  AND	pa.PackagePathID = pp.PackagePathID	-- Package in policy
	  AND	pp.PackagePathID = pv.PackagePathID	-- Package in policy
	  AND	pf.PackageFamilyID = pv.PackageFamilyID	-- in this family
	  AND	pf.PackageName LIKE @pkgName		-- desired package
	  AND	pp.PackageFullName LIKE @pkgFName	-- desired path
	  AND	pv.Version LIKE @pkgVer			-- desired version
	  AND NOT EXISTS(
	    	SELECT * FROM Installation AS i
		WHERE	c.ComputerOUID = i.OrganizationID-- Matching installed OU
		  AND	m.TargetID = i.ComputerID	-- Installing computer
		  AND	pv.PackageVersionID = i.PackageVersionID
		  AND	i.UserID = 1			-- Computer install
	    )
	  AND	(
	  	@installPolicy IS NULL
		OR (	@installPolicy = 'install'
			AND ad.Action = 'install'
		)
		OR (	@installPolicy = 'choose'
			AND (	ad.Action = 'choose'
				OR (	ad.Action = 'alwaysupdate'
					AND NOT EXISTS (
						SELECT	*
						FROM	Installation i
							INNER JOIN PackageVersion pv2
								ON i.PackageVersionID = pv2.PackageVersionID
						WHERE i.Result = 'success'
						AND pv2.PackageFamilyID = pf.PackageFamilyID
						AND pv2.PackagePathID <> pa.PackagePathID
						AND i.ComputerID = c.ComputerID
						AND i.UserID = 1
						AND i.OrganizationID = c.ComputerOUID
					)
				)
			)
		)
		OR (	@installPolicy = 'alwaysupdate'
			AND ad.Action = 'alwaysupdate'
			AND EXISTS (
				SELECT	*
				FROM	Installation i
					INNER JOIN PackageVersion pv2
						ON i.PackageVersionID = pv2.PackageVersionID
				WHERE i.Result = 'success'
				AND pv2.PackageFamilyID = pf.PackageFamilyID
				AND pv2.PackagePathID <> pa.PackagePathID
				AND i.ComputerID = c.ComputerID
				AND i.UserID = 1
				AND i.OrganizationID = c.ComputerOUID
			)
		)
	  )
	ORDER BY pp.PackageFullName, pv.Version, dbo.OUName(c_ou.OUID), ComputerCN

GO

/*
 * Enumerate the pending applications of Policy
 * for packages which are selected in #Packages matching @pkgVer
 * by users in an OU matching oudn
 */
IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE name = 'SoftwarePackageInstallationPendingUserMatchOU' AND xtype = 'P'
)
	DROP PROCEDURE SoftwarePackageInstallationPendingUserMatchOU
GO

CREATE PROCEDURE SoftwarePackageInstallationPendingUserMatchOU
	@pkgName	VARCHAR(128) = '%',
	@pkgVer		VARCHAR(32) = '%',
	@pkgFName	VARCHAR(256) = '%',
	@installPolicy	VARCHAR(16) = ''
AS 
	DECLARE @TargetTypeID	INT		-- TargetTypeId 'User'
	SET @TargetTypeID =
		(SELECT TargetTypeID FROM TargetType
		 WHERE TargetTypeName = 'User')

	SELECT	pp.PackageFullName,
		pf.PackageName,
		pv.Version,
		case
			when ad.[Action] is null then 'Null'
			else ad.[Action]
		end as [InstallPolicy],
		dbo.OUName(u_ou.OUID) AS UserOU,
		u.UserCN AS UserCN,
		NULL AS ComputerOU,
		'Not Known' AS ComputerCN,
		ad.EffectiveFrom,
		ad.EffectiveFromIsLocal
	FROM	PackageApplies AS pa,
		AllocationDetails AS ad,
		PackagePath AS pp,
		PackageFamily AS pf,
		PackageVersion AS pv,
		[User] AS u,
		#Organization AS u_ou
	WHERE 	pa.TargetTypeID = @TargetTypeID		-- User policy type
	  AND	pa.AllocationDetailsID = ad.AllocationDetailsID
	  AND	pa.PackagePathID = pp.PackagePathID	-- Package in policy
	  AND	pp.PackagePathID = pv.PackagePathID	-- Package in policy
	  AND	pf.PackageFamilyID = pv.PackageFamilyID	-- in this family
	  AND	pf.PackageName LIKE @pkgName		-- desired package
	  AND	pp.PackageFullName LIKE @pkgFName	-- desired path
	  AND	pv.Version LIKE @pkgVer			-- desired version
	  AND	pa.TargetID = u.UserID			-- For this user
	  AND	u.UserOUID = u_ou.OUID			-- which is this
	  AND NOT EXISTS(
	    	SELECT * FROM Installation AS i
		WHERE	i.OrganizationID = u_ou.OUID	-- Installing User OU ID
		  AND	i.UserID = u.UserID		-- installing user
		  AND	i.PackageVersionID = pv.PackageVersionID
		)
	  AND	(
	  	@installPolicy IS NULL
		OR (	@installPolicy = 'install'
			AND ad.Action = 'install'
		)
		OR (	@installPolicy = 'choose'
			AND (	ad.Action = 'choose'
				OR (	ad.Action = 'alwaysupdate'
					AND NOT EXISTS (
						SELECT	*
						FROM	Installation i
							INNER JOIN PackageVersion pv2
								ON i.PackageVersionID = pv2.PackageVersionID
						WHERE i.Result = 'success'
						AND pv2.PackageFamilyID = pf.PackageFamilyID
						AND pv2.PackagePathID <> pa.PackagePathID
						AND i.UserID = u.UserID
						AND i.OrganizationID = u.UserOUID
					)
				)
			)
		)
		OR (	@installPolicy = 'alwaysupdate'
			AND ad.Action = 'alwaysupdate'
			AND EXISTS (
				SELECT	*
				FROM	Installation i
					INNER JOIN PackageVersion pv2
						ON i.PackageVersionID = pv2.PackageVersionID
				WHERE i.Result = 'success'
				AND pv2.PackageFamilyID = pf.PackageFamilyID
				AND pv2.PackagePathID <> pa.PackagePathID
				AND i.UserID = u.UserID
				AND i.OrganizationID = u.UserOUID
			)
		)
	  )

	UNION

	SELECT	pp.PackageFullName,
		pf.PackageName,
		pv.Version,
		case
			when ad.[Action] is null then 'Null'
			else ad.[Action]
		end as [InstallPolicy],
		dbo.OUName(u_ou.OUID) AS UserOU,
		u.UserCN AS UserCN,
		NULL AS ComputerOU,
		'Not Known' AS ComputerCN,
		ad.EffectiveFrom,
		ad.EffectiveFromIsLocal
	FROM	PackageApplies AS pa,
		Member AS m,
		AllocationDetails AS ad,
		PackagePath AS pp,
		PackageFamily AS pf,
		PackageVersion AS pv,
		[User] AS u,
		#Organization AS u_ou
	WHERE 	pa.TargetTypeID = 3
	  AND	m.GroupID = pa.TargetID
	  AND	m.TargetTypeID = @TargetTypeID		-- User policy type
	  AND	pa.AllocationDetailsID = ad.AllocationDetailsID
	  AND	pa.PackagePathID = pp.PackagePathID	-- Package in policy
	  AND	pp.PackagePathID = pv.PackagePathID	-- Package in policy
	  AND	pf.PackageFamilyID = pv.PackageFamilyID	-- in this family
	  AND	pf.PackageName LIKE @pkgName		-- desired package
	  AND	pp.PackageFullName LIKE @pkgFName	-- desired path
	  AND	pv.Version LIKE @pkgVer			-- desired version
	  AND	m.TargetID = u.UserID			-- For this user
	  AND	u.UserOUID = u_ou.OUID			-- which is this OU
	  AND NOT EXISTS(
	    	SELECT * FROM Installation AS i
		WHERE	i.OrganizationID = u_ou.OUID	-- Installing User OU ID
		  AND	i.UserID = u.UserID		-- installing user
		  AND	i.PackageVersionID = pv.PackageVersionID
		)
	  AND	(
	  	@installPolicy IS NULL
		OR (	@installPolicy = 'install'
			AND ad.Action = 'install'
		)
		OR (	@installPolicy = 'choose'
			AND (	ad.Action = 'choose'
				OR (	ad.Action = 'alwaysupdate'
					AND NOT EXISTS (
						SELECT	*
						FROM	Installation i
							INNER JOIN PackageVersion pv2
								ON i.PackageVersionID = pv2.PackageVersionID
						WHERE i.Result = 'success'
						AND pv2.PackageFamilyID = pf.PackageFamilyID
						AND pv2.PackagePathID <> pa.PackagePathID
						AND i.UserID = u.UserID
						AND i.OrganizationID = u.UserOUID
					)
				)
			)
		)
		OR (	@installPolicy = 'alwaysupdate'
			AND ad.Action = 'alwaysupdate'
			AND EXISTS (
				SELECT	*
				FROM	Installation i
					INNER JOIN PackageVersion pv2
						ON i.PackageVersionID = pv2.PackageVersionID
				WHERE i.Result = 'success'
				AND pv2.PackageFamilyID = pf.PackageFamilyID
				AND pv2.PackagePathID <> pa.PackagePathID
				AND i.UserID = u.UserID
				AND i.OrganizationID = u.UserOUID
			)
		)
	  )
	ORDER BY pp.PackageFullName, pv.Version,
		dbo.OUName(u_ou.OUID), UserCN

GO

/*
 * Enumerate Pending Policy applications in OU
 *
 * TargetTypeName must be 'Computer' or 'User' (or any other value
 * which may have been inserted into the TargetTypes table).
 *
 * oudn is one of the OU field values from the SDOU table, or a wildcard:
 *
 * ouMatch is non-zero if the oudn string is to be matched with wildcards,
 * then any wild-card characters must be escaped to be matched normally.
 *
 * PackageName and Version are the short-name and version of the package(s) to
 * be matched. Wildcards are allowed.
 *
 * The returned ResultSet contains ...
 */
IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE name = 'SoftwarePackageInstallationPending' AND xtype = 'P'
)
	DROP PROCEDURE SoftwarePackageInstallationPending
GO

CREATE PROCEDURE SoftwarePackageInstallationPending
	@TargetTypeName	VARCHAR(256),
	@oudn		VARCHAR(800),
	@ouMatch	INT = 0,		-- actually boolean
	@pkgName	VARCHAR(128) = '%',
	@pkgVer		VARCHAR(32)= '%',
	@pkgFName	VARCHAR(256) = '%',
	@installPolicy	VARCHAR(16) = NULL
AS 
	BEGIN
		CREATE TABLE #Organization(OUID int PRIMARY KEY)
		EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

	    IF (@TargetTypeName = 'Computer')
		EXECUTE SoftwarePackageInstallationPendingComputerMatchOU
				@pkgName,
				@pkgVer,
				@pkgFName,
				@installPolicy
	    ELSE
		EXECUTE SoftwarePackageInstallationPendingUserMatchOU
				@pkgName,
				@pkgVer,
				@pkgFName,
				@installPolicy
	END
GO
/*
 * $Id: SoftwarePackageInstallationSummary.sql 87010 2008-03-25 23:49:16Z rlowery $
 *
 * Stored procedures to reconcile TargetedPackage (RSOP) with Installation
 *
 * The main procedure at the bottom creates and destroys the temporary table
 * #Packages
 */

/*
 * DROP PROCEDURE SoftwarePackageInstallationSummary
 * GO
 */

/*
 * Reconcile the TargetedPackage (RSOP) table with Installation.
 *
 * TargetTypeName must be 'Computer' or 'User' (or any other value
 * which may have been inserted into the TargetTypes table).
 *
 * PackageName and Version are the short-name and version of the package(s) to
 * be matched. Wildcards are allowed.
 *
 * The returned ResultSet contains clusters of rows each with matching
 * PackageFullName, PackageName, and Version fields but varying by:
 * - PolicyAction ('install', 'optional', etc, or '' for out-of-policy)
 * - Result, one of ('success', 'failure' or 'pending')
 * - Count of the number of occurrences of this Result
 * A single package can thus return eight rows (3+3+2).
 */
IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE name = 'SoftwarePackageInstallationSummary' AND xtype = 'P'
)
	DROP PROCEDURE SoftwarePackageInstallationSummary
GO

CREATE PROCEDURE SoftwarePackageInstallationSummary
	@TargetTypeName	VARCHAR(256),
	@oudn		VARCHAR(800),
	@ouMatch	INT = 0,		-- actually boolean
	@pkgName	VARCHAR(128) = '%', -- (size=64*2 --to take into acct encoded chars)
	@pkgVer		VARCHAR(32)= '%',
	@pkgFName	VARCHAR(256) = '%'
AS 

declare @TargetTypeID int

select @TargetTypeID = TargetTypeID
from dbo.TargetType
where TargetTypeName = @TargetTypeName

if @TargetTypeID is null
	begin
		set @TargetTypeID = 1	-- Default to Computers
	end

CREATE TABLE #Organization(OUID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

create table #Packages
(
	PackageFullName nvarchar(256),
	PackageVersionID INT,
	PackageFamilyID INT,
	PackageName nvarchar(64),
	Version nvarchar(32)
)

INSERT INTO #Packages
SELECT pp.PackageFullName, pv.PackageVersionID, pf.PackageFamilyID, pf.PackageName, pv.Version
FROM PackageFamily pf
	INNER JOIN PackageVersion pv
		ON pf.PackageFamilyID = pv.PackageFamilyID
	INNER JOIN PackagePath pp
		ON pp.PackagePathID = pv.PackagePathID
WHERE pf.PackageName LIKE @pkgName
	AND pp.PackageFullName LIKE @pkgFName
	AND pv.Version LIKE @pkgVer
	AND NOT EXISTS(
	      -- Only where there isn't another Warehouse version of this pkg
	      SELECT *
	      FROM	PackageVersion AS alt_pv,
		      MediaContainsPackageVersion AS mcp
	      WHERE	pv.PackagePathID = alt_pv.PackagePathID	-- Same path
		AND	pv.PackageVersionID != alt_pv.PackageVersionID --Not same
		AND	alt_pv.PackageVersionID = mcp.PackageVersionID
		AND	mcp.MediaID = 1				-- In Warehouse
      )

IF @TargetTypeID = 1	-- Computers
BEGIN
select	pkg.PackageName as PackageName,
	pkg.Version,
	'' as PolicyAction,
	'' as InstallPolicy,
	'Computer' as TargetTypeName,
	summary.Success,
	summary.Pending,
	summary.Postponed,
	summary.NotRequired,
	summary.Failure,
	summary.Scheduled,
	summary.[Removal Pending],
	summary.[Reboot Pending],
	summary.Staged,
	summary.Total,
	pkg.PackageFullName
from
(
	select 	isnull(pkginfo.PackageVersionID, installinfo.PackageVersionID) as PackageVersionID,
		isnull(installinfo.Success, 0) as Success,
		isnull(pkginfo.Pending, 0) as Pending,
		isnull(installinfo.Postponed, 0) as Postponed,
		isnull(installinfo.NotRequired, 0) as NotRequired,
		isnull(installinfo.Failure, 0) as Failure,
		isnull(pkginfo.Scheduled, 0) as Scheduled,
		isnull(installinfo.[Removal Pending], 0) as [Removal Pending],
		isnull(installinfo.[Reboot Pending], 0) as [Reboot Pending],
		isnull(installinfo.Staged, 0) as Staged,
		(isnull(installinfo.Total, 0) + isnull(pkginfo.Pending, 0) + isnull(pkginfo.Scheduled, 0)) as Total

	from	(
			select pv.PackageVersionID,
				sum(case when (ad.EffectiveFrom is null) or (ad.EffectiveFrom <= (case when ad.EffectiveFromIsLocal = 1 then dateadd(hour, -12, getutcdate()) else getutcdate() end)) then 1 else 0 end) as Pending,
				sum(case when (ad.EffectiveFrom is not null) and (ad.EffectiveFrom > (case when ad.EffectiveFromIsLocal = 1 then dateadd(hour, -12, getutcdate()) else getutcdate() end)) then 1 else 0 end) as Scheduled
			from 	PackageApplies as pa
				join PackageVersion as pv on pv.PackagePathID = pa.PackagePathID
				left outer join Member as memb
					on pa.TargetTypeID = 3 and memb.GroupID = pa.TargetID
					and memb.TargetTypeID = 1
				join AllocationDetails ad on ad.AllocationDetailsID = pa.AllocationDetailsID
			where	((
					(pa.TargetTypeID = 1) -- Computers
					and not exists(
							select	ComputerID
							from	installation as i
							where	UserID = 1	-- Computers
								and i.ComputerID = pa.TargetID
								and i.PackageVersionID = pv.PackageVersionID
							)
					and exists(select OUID from #Organization where OUID = pa.TargetOUID)
				)
				or (
					(pa.TargetTypeID = 3) -- RSOP
					and not exists (
							select	i.ComputerID
							from	installation as i
							where	i.UserID = 1	-- Computers
								and i.ComputerID = memb.TargetID
								and i.PackageVersionID = pv.PackageVersionID
							)
					and exists(select OUID from #Organization where OUID in (
							select	c.ComputerOUID
							from	Computer as c
							where	memb.TargetID = c.ComputerID
						)
					)
				))
				and exists(select PackageVersionID from #Packages where PackageVersionID = pv.PackageVersionID)
			group by pv.PackageVersionID
		) as pkginfo
		full outer join
		(
			select	b.PackageVersionID,
				sum(case when b.Result = 'success' AND b.InstallAction <> 'redundant' then b.Total else 0 end) as Success,
				sum(case when b.Result = 'postponed' AND b.InstallAction <> 'redundant' then b.Total else 0 end) as Postponed,
				sum(case when b.Result = 'notrequired' AND b.InstallAction <> 'redundant' then b.Total else 0 end) as NotRequired, 
			      	sum(case when b.Result = 'failure' AND b.InstallAction <> 'redundant' then b.Total else 0 end) as Failure,
				sum(case when b.InstallAction = 'redundant' then b.Total else 0 end) as [Removal Pending], 
			      	sum(case when b.Result = 'rebootrequired' AND b.InstallAction <> 'redundant' then b.Total else 0 end) as [Reboot Pending], 
			     	sum(case when b.Result = 'staged' AND b.InstallAction <> 'redundant' then b.Total else 0 end) as Staged,
				sum(b.Total) as Total
			from
			(
				select	i.PackageVersionID,
					i.[Action] as InstallAction,
					i.Result,
					count(*) as Total
				from	#Organization as o join installation as i on i.OrganizationID = o.OUID
				where (i.UserID = 1) 		-- Computers
					and exists(select PackageVersionID from #Packages where PackageVersionID = i.PackageVersionID)
				group by i.PackageVersionID, i.[Action], i.Result
			) as b
			group by b.PackageVersionID
		) as installinfo on installinfo.PackageVersionID = pkginfo.PackageVersionID
) as summary
left outer join #Packages as pkg on pkg.PackageVersionID = summary.PackageVersionID 

order by pkg.PackageName, pkg.Version, pkg.PackageFullName

END ELSE BEGIN	-- @TargetType = 2 (users)

select	pkg.PackageName as PackageName,
	pkg.Version,
	'' as PolicyAction,
	'' as InstallPolicy,
	'User' as TargetTypeName,
	summary.Success,
	summary.Pending,
	summary.Postponed,
	summary.NotRequired,
	summary.Failure,
	summary.Scheduled,
	summary.[Removal Pending],
	summary.[Reboot Pending],
	summary.Staged,
	summary.Total,
	pkg.PackageFullName
from
(
	select 	isnull(pkginfo.PackageVersionID, installinfo.PackageVersionID) as PackageVersionID,
		isnull(installinfo.Success, 0) as Success,
		isnull(pkginfo.Pending, 0) as Pending,
		isnull(installinfo.Postponed, 0) as Postponed,
		isnull(installinfo.NotRequired, 0) as NotRequired,
		isnull(installinfo.Failure, 0) as Failure,
		isnull(pkginfo.Scheduled, 0) as Scheduled,
		isnull(installinfo.[Removal Pending], 0) as [Removal Pending],
		isnull(installinfo.[Reboot Pending], 0) as [Reboot Pending],
		isnull(installinfo.Staged, 0) as Staged,
		(isnull(installinfo.Total, 0) + isnull(pkginfo.Pending, 0) + isnull(pkginfo.Scheduled, 0)) as Total
		
	from	(
			select pv.PackageVersionID,
				sum(case when (ad.EffectiveFrom is null) or (ad.EffectiveFrom <= (case when ad.EffectiveFromIsLocal = 1 then dateadd(hour, -12, getutcdate()) else getutcdate() end)) then 1 else 0 end) as Pending,
				sum(case when (ad.EffectiveFrom is not null) and (ad.EffectiveFrom > (case when ad.EffectiveFromIsLocal = 1 then dateadd(hour, -12, getutcdate()) else getutcdate() end)) then 1 else 0 end) as Scheduled
			from 	PackageApplies as pa
				join PackageVersion as pv on pv.PackagePathID = pa.PackagePathID
				left outer join Member as memb
					on pa.TargetTypeID = 3 and memb.GroupID = pa.TargetID
					and memb.TargetTypeID = 2
				join AllocationDetails ad on ad.AllocationDetailsID = pa.AllocationDetailsID
			where	((
					(pa.TargetTypeID = 2) -- Users
					and not exists(
							select	UserID
							from	installation as i
							where	UserID <> 1	-- Users
								and i.UserID = pa.TargetID
								and i.PackageVersionID = pv.PackageVersionID
							)
					and exists(select OUID from #Organization where OUID = pa.TargetOUID)
				)
				or (
					(pa.TargetTypeID = 3) -- RSOP
					and not exists (
							select	i.UserID
							from	installation as i
							where	i.UserID <> 1	-- Computers
								and i.UserID = memb.TargetID
								and i.PackageVersionID = pv.PackageVersionID
							)
					and exists(select OUID from #Organization where OUID in (
							select	u.UserOUID
							from	[User] as u
							where	memb.TargetID = u.UserID
						)
					)
				))
				and exists(select PackageVersionID from #Packages where PackageVersionID = pv.PackageVersionID)
			group by pv.PackageVersionID
		) as pkginfo
		full outer join
		(
			select	b.PackageVersionID,
				sum(case when b.Result = 'success' AND b.InstallAction <> 'redundant' then b.Total else 0 end) as Success,
				sum(case when b.Result = 'postponed' AND b.InstallAction <> 'redundant' then b.Total else 0 end) as Postponed,
				sum(case when b.Result = 'notrequired' AND b.InstallAction <> 'redundant' then b.Total else 0 end) as NotRequired, 
			      	sum(case when b.Result = 'failure' AND b.InstallAction <> 'redundant' then b.Total else 0 end) as Failure,
				sum(case when b.InstallAction = 'redundant' then b.Total else 0 end) as [Removal Pending], 
			      	sum(case when b.Result = 'rebootrequired' AND b.InstallAction <> 'redundant' then b.Total else 0 end) as [Reboot Pending], 
			     	sum(case when b.Result = 'staged' AND b.InstallAction <> 'redundant' then b.Total else 0 end) as Staged,
				sum(b.Total) as Total
			from
			(
				select	i.PackageVersionID,
					i.[Action] as InstallAction,
					i.Result,
					count(*) as Total
				from	#Organization as o join installation as i on i.OrganizationID = o.OUID
					join [User] as u on u.UserID = i.UserID and u.UserOUID = i.OrganizationID
				where (i.UserID <> 1) 		-- Users
					and exists(select PackageVersionID from #Packages where PackageVersionID = i.PackageVersionID)
				group by i.PackageVersionID, i.[Action], i.Result
			) as b
			group by b.PackageVersionID
		) as installinfo on installinfo.PackageVersionID = pkginfo.PackageVersionID
) as summary
left outer join #Packages as pkg on pkg.PackageVersionID = summary.PackageVersionID

order by pkg.PackageName, pkg.Version, pkg.PackageFullName
END

GO
/* 
 * $Id: mgsAgedManagedDevices.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsAgedManagedDevices  
 *	Input:
 * 	- @oudn: selected OU-DN name.  default is all OUs
 *	- @ouMatch: Include sub-OUs: [True=1|False=0] (default True)
 *
 *	Returns:
 *	- ComputerID, ComputerCN, OUID, OU
 *	- LastInstallDate, LastInventoryDate
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'mgsAgedManagedDevices' AND xtype = 'P'
)
	DROP PROCEDURE mgsAgedManagedDevices
GO

CREATE PROCEDURE [mgsAgedManagedDevices]
	@oudn VARCHAR(800)='%', --OUs
	@ouMatch BIT=1, --Match on OUs include sub-OUs [True=1|False=0]
	@compCN Varchar(128)='%' -- computer name (size=64*2 --to take into acct encoded chars)
AS
BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

	SELECT
	c.ComputerID,
	c.ComputerCN,
	c.ComputerOUID,
	dbo.OUName(s.OUID) AS OU,
	(SELECT	MAX(Reported) 
	 FROM	Installation AS ins1
	 WHERE	ins1.OrganizationID = s.OUID
	   AND	ins1.ComputerID = c.ComputerID
	) AS LastInstallDate,
	LastInventoryDate =
		CASE 
			WHEN ( ISNULL(sub.swdate, 01/01/1900) >= ISNULL(sub.hwdate, 01/01/1900) ) 
				AND ( ISNULL(sub.swdate, 01/01/1900) >= ISNULL(sub.filesdate, 01/01/1900) )
				THEN sub.swdate
		
			WHEN ( ISNULL(sub.hwdate, 01/01/1900) >= ISNULL(sub.swdate, 01/01/1900) ) 
				AND ( isnull(sub.hwdate, 01/01/1900) >= ISNULL(sub.filesdate, 01/01/1900) )
				THEN sub.hwdate
		
			WHEN  ( ISNULL(sub.filesdate, 01/01/1900) >= ISNULL(sub.swdate, 01/01/1900) ) 
				AND ( ISNULL(sub.filesdate, 01/01/1900) >= ISNULL(sub.hwdate, 01/01/1900) )
				THEN sub.filesdate
		END 	

	FROM
	#Organization AS s INNER JOIN 
		Computer AS c LEFT OUTER JOIN
		
		( SELECT DISTINCT
			ir1.ComputerID,
			c1.ComputerOUID, 
			MAX(SWDate) AS SWDate,
			MAX(HWDate) AS HWDate,
			MAX(FilesDate) AS FilesDate
		
			FROM InventoryReport ir1 , Computer c1, #Organization s1
			
			WHERE c1.ComputerOUID = s1.OUID
				AND ir1.ComputerID = c1.ComputerID 
			GROUP BY ir1.ComputerID, c1.ComputerOUID
		) AS sub

		ON c.ComputerID = sub.ComputerID 
	ON s.OUID = c.ComputerOUID

	WHERE c.ComputerCN LIKE @compCN -- match on ComputerCN (contains % - sql wildcard)
			
	ORDER BY c.ComputerOUID, c.ComputerCN

END
/* 
 * $Id: DistributionDetails.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedures:
 *	DistributionDetails
 *	mgsDSDistributionDetails
 *	mgsDLDistributionDetails
 *
 *	Input:
 *
 * 	- @dstype 0=DL, 1=DS (DistributionDetails only)
 * 	- @distID (i.e. ServerUID of DS). 
 *	- @state (i.e. Distribution State). Default value is ALL
 *		Values: 'all', 'available', 'pending', 'removing', 'unavailable'
 *	Returns:
 *	- details of a pending/completed distributions for a single DS/DL
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'DistributionDetails' AND xtype = 'P'
)
        DROP PROCEDURE DistributionDetails
GO
CREATE PROCEDURE DistributionDetails
	@dstype	int = 1,		-- Active DS (0 = DL)
	@distID binary (16),		-- Retrieve Data for a specific DS/DL
	@state	varchar(15) = 'all'
AS
BEGIN

	IF (@distID IS NULL)
		RETURN

	SELECT	pp.PackageFullName,
		pf.PackageName, 
		pv.Version, 
		CASE
		WHEN dp.RequestState = 'empty'
			THEN dp.ConfirmedState	-- 'available' or 'unavailable'
			ELSE dp.RequestState
		END AS [Status], 
		CASE
		WHEN dp.RequestState = 'empty'
			THEN dp.ConfirmedDate
			ELSE dp.RequestDate
		END AS [Date-Time], 
		dp.ConfirmedReason AS [Failure Reason],
		CASE
		WHEN pp.PackageFullName LIKE 'Package%'
			THEN 'Software'
		WHEN pp.PackageFullName LIKE 'Policy%'
			THEN 'Policy'
		WHEN pp.PackageFullName LIKE 'Schedule%'
			THEN 'Schedule'
		WHEN pp.PackageFullName LIKE 'OSMigration/OSImage%'
			THEN 'OSImage'
		WHEN pp.PackageFullName LIKE 'OSMigration/ComputerNameMapping%'
			THEN 'ComputerNameMapping'
		WHEN pp.PackageFullName LIKE 'OSMigration/RolloutConfiguration%'
			THEN 'RolloutConfiguration'
			ELSE 'Other' -- default
		END as Type	

	FROM	DistributionServer AS ds,
		DistributedPackage dp,
		PackageVersion pv,
		PackageFamily AS pf,
		PackagePath AS pp

	WHERE	ds.ServerUID = @distID		-- This DL
	  AND	ds.ServerType = @dstype
	  AND	ds.ServerUID = dp.ServerUID
	  AND (	@state = 'all'			-- Any ConfirmedState
	     OR	@state = 'pending'
	     OR	@state = 'removing'
	     OR dp.ConfirmedState = @state	-- or just the given state
	     OR (
			@state = 'available' AND dp.ConfirmedState = 'quarantined'
		)
	     OR (
			@state = 'available' AND dp.ConfirmedState = 'rolled back'
		)
	      )
	  AND (	@state = 'all'			-- Any RequestState
	     OR dp.RequestState
	     	= CASE	WHEN @state = 'available'
			  OR @state = 'unavailable'
			THEN 'empty'		-- RequestState must be empty
			WHEN @state = 'removing' -- RequestState must match
			  OR @state = 'pending' -- RequestState must match
			THEN @state
	     	END
	      )
	  AND	dp.RequestedVersionID = pv.PackageVersionID
	  AND	pv.PackagePathID = pp.PackagePathID
	  AND	pv.PackageFamilyID = pf.PackageFamilyID
	ORDER BY pp.PackageFullName
END
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsDSDistributionDetails' AND xtype = 'P'
)
        DROP PROCEDURE mgsDSDistributionDetails
GO
CREATE PROCEDURE [mgsDSDistributionDetails] 
	@distID	binary(16),		-- Retrieve Data for a specific DS
	@state	varchar(15) = 'all'	-- Values {'all', 'available', 'pending', 'removing', 'unavailable'}	 
AS
	EXEC DistributionDetails 1, @distID, @state
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsDLDistributionDetails' AND xtype = 'P'
)
        DROP PROCEDURE mgsDLDistributionDetails
GO
CREATE PROCEDURE [mgsDLDistributionDetails] 
	@distID	binary(16),  -- Retrieve Data for a specific DL
	@state	varchar(15) = 'all'
AS
	EXEC DistributionDetails 0, @distID, @state
GO
/*
 * $Id: DistributionSummary.sql 93531 2009-08-26 04:03:32Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsDLDistributionSummary
 *	Input:
 * 	- @distID (i.e. ServerUID of DL). of a single DL
 *	Returns:
 *	- summary of a single DL if passed in the ID of only a single DL -OR-
 *	- summary of all DLs if no DL ID is passed in
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'DistributionSummary' AND xtype = 'P'
)
        DROP PROCEDURE DistributionSummary
GO
CREATE PROCEDURE DistributionSummary
	@serverType	int,
	@distID  	binary(16)
AS
	SELECT	ds.ServerName AS [ServerName],
		ds.ServerUID AS [ServerUID],
		SUM(CASE WHEN (
				dp.ConfirmedState = 'available' OR
				dp.ConfirmedState = 'quarantined' OR
				dp.ConfirmedState = 'rolled back'
			 )
			  AND dp.RequestState = 'empty'
			 THEN 1 ELSE 0 END
		) AS Available,
		SUM(CASE WHEN dp.RequestState = 'pending'
			 THEN 1 ELSE 0 END
		) AS Pending,
		SUM(CASE WHEN dp.ConfirmedState = 'unavailable'
			  AND dp.RequestState = 'empty'
			 THEN 1 ELSE 0 END
		) AS Unavailable,
		SUM(CASE WHEN dp.RequestState = 'removing'
			 THEN 1 ELSE 0 END
		) AS Removing,
		COUNT(dp.ServerUID) AS Total
	FROM	DistributionServer AS ds
		LEFT OUTER JOIN
		DistributedPackage AS dp
		ON ds.ServerUID = dp.ServerUID
			AND (
				EXISTS(
					SELECT	PackageVersionID
					FROM	PackageVersion
					WHERE	PackageVersionID = dp.RequestedVersionID
					  OR	PackageVersionID = dp.ConfirmedVersionID
				)
			)
	WHERE	(@distID IS NULL OR ds.ServerUID = @distID)
	  AND	ds.ServerType = @serverType
	GROUP BY
		ds.PrimaryParentUID,	-- This should have no effect...?
		ds.ServerName,
		ds.ServerUID
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsDLDistributionSummary' AND xtype = 'P'
)
        DROP PROCEDURE mgsDLDistributionSummary
GO
CREATE PROCEDURE mgsDLDistributionSummary
	@distID  BINARY(16)
AS
	EXEC DistributionSummary 0, @distID
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsDSDistributionSummary' AND xtype = 'P'
)
        DROP PROCEDURE mgsDSDistributionSummary
GO
CREATE PROCEDURE mgsDSDistributionSummary
	@distID  BINARY(16)
AS
	EXEC DistributionSummary 1, @distID
GO
/*
 * $Id: DistributionSummaryList.sql 93531 2009-08-26 04:03:32Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: DistributionSummaryList
 *	Input:
 * 	- @distID (i.e. ServerUID of DS/DL). Default value is all DS/DLs.
 *	Returns:
 *	- summary of a single DS/DL if passed in the ID of only a single DS/DL
 *	- summary of all DS/DLs if no DS/DL ID is passed in
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'DistributionSummaryList' AND xtype = 'P'
)
        DROP PROCEDURE DistributionSummaryList
GO
CREATE PROCEDURE DistributionSummaryList
	@serverType	int,
	@distribName	varchar(128) = '%'
AS
	SELECT	dsp.ServerFullName,
		CASE
		WHEN dsp.PrimaryParentUID IS NULL
			THEN ''
			ELSE ISNULL(dsp.ParentName, 'Warehouse')
		END AS ServerParentName,
		dsp.ServerName AS ServerName,
		dsp.ServerUID AS ServerUID,
		CASE
		WHEN dsp.ConfigState = ''
			OR dsp.ConfigState IS NULL
			THEN 'NotConfigured'
		WHEN dsp.ConfigState <> 'Configured'
			THEN dsp.ConfigState
		WHEN MAX(dss.ReportedDate) < DATEADD(Day, -1, GETDATE())
			THEN 'Offline'
		WHEN SUM(dss.DelayedCount) > 0
			THEN 'Delayed'
		WHEN SUM(dss.[Count]) > 0
			THEN 'Working'
		ELSE 'Ready'
		END AS ServerAvailable,
		dsp.LastConfigStart AS ConfigDateTime,
		CAST(dsp.ConfigFailReason AS VARCHAR)
			AS ConfigFailReason,
		SUM(CASE WHEN (
				dp.ConfirmedState = 'available' OR
				dp.ConfirmedState = 'quarantined' OR
				dp.ConfirmedState = 'rolled back'
			 )
			  AND dp.RequestState = 'empty'
			 THEN 1 ELSE 0 END
		) AS Available,
		SUM(CASE WHEN dp.RequestState = 'pending'
			 THEN 1 ELSE 0 END
		) AS Pending,
		SUM(CASE WHEN dp.ConfirmedState = 'unavailable'
			  AND dp.RequestState = 'empty'
			 THEN 1 ELSE 0 END
		) AS Unavailable,
		SUM(CASE WHEN dp.RequestState = 'removing'
			 THEN 1 ELSE 0 END
		) AS Removing,
		COUNT(dp.ServerUID) AS Total

	FROM	(SELECT parent.ServerName AS ParentName,
			ISNULL(parent.ServerName +' / ', '') + ds.ServerName
				AS ServerFullName,
			ds.*
		FROM	DistributionServer AS ds
			LEFT OUTER JOIN
			DistributionServer AS parent
			ON ds.PrimaryParentUID = parent.ServerUID
		WHERE	ds.ServerType = @serverType
		  AND	NOT ds.ServerUID = 0x00000000000000000000000000000000
		  AND	ds.ServerName LIKE @distribName
		) AS dsp		-- DistributionServer with parent info
		LEFT OUTER JOIN
		DistributedPackage AS dp
		ON dsp.ServerUID = dp.ServerUID
			AND (
				EXISTS(
					SELECT	PackageVersionID
					FROM	PackageVersion
					WHERE	PackageVersionID = dp.RequestedVersionID
					  OR	PackageVersionID = dp.ConfirmedVersionID
				)
			)
		LEFT OUTER JOIN (
			SELECT	DISTINCT dss1.ServerUID,
				MIN(dss1.ReportedDate) AS ReportedDate,
				SUM(dss1.[Count]) AS Count,
				SUM(dss1.DelayedCount) AS DelayedCount
			FROM	DistributionServerStatus AS dss1
			GROUP BY dss1.ServerUID
		) AS dss
		ON dsp.ServerUID = dss.ServerUID

	GROUP BY dsp.PrimaryParentUID, dsp.ServerName, dsp.ServerUID,
		dsp.ConfigState, dsp.LastConfigStart,
		CAST(dsp.ConfigFailReason AS VARCHAR),
		dsp.ServerFullName, dsp.ParentName

	ORDER BY ServerFullName
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsDLDistributionSummaryList' AND xtype = 'P'
)
        DROP PROCEDURE mgsDLDistributionSummaryList
GO
CREATE PROCEDURE mgsDLDistributionSummaryList
	@distribName  VARCHAR(128) = '%'
AS
	EXEC DistributionSummaryList 0, @distribName
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsDSDistributionSummaryList' AND xtype = 'P'
)
        DROP PROCEDURE mgsDSDistributionSummaryList
GO
CREATE PROCEDURE mgsDSDistributionSummaryList
	@distribName  VARCHAR(128) = '%'
AS
	EXEC DistributionSummaryList 1, @distribName
GO
/*
 * $Id: DSDistributionStatus.sql 92365 2009-05-27 00:49:05Z rlowery $
 * $Locker$
 *
 * DESCRIPTION: Stored procedures for DS status reporting
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'DistributionServerStatusDetails' AND xtype = 'P'
)
        DROP PROCEDURE DistributionServerStatusDetails
GO
CREATE PROCEDURE DistributionServerStatusDetails
	@distID	BINARY(16),
	@state varchar(128) = '%'
AS
	DECLARE	@HoursBeforeDSOffline AS int

	IF (
		EXISTS(
			SELECT * FROM DatabaseConfiguration
			WHERE	Property = 'HoursBeforeDSOffline'
		)
	)
	BEGIN
		SELECT	@HoursBeforeDSOffline = 0 - CONVERT(int, Value)
		FROM	DatabaseConfiguration
		WHERE	Property = 'HoursBeforeDSOffline'
	END
	ELSE
		SET @HoursBeforeDSOffline = 0 - 24

	SELECT	*
	FROM	(
		SELECT	dsp.ServerFullName,
			CASE
			WHEN dsp.PrimaryParentUID IS NULL
				THEN ''
				ELSE ISNULL(dsp.ParentName, 'Warehouse')
			END AS ServerParentName,
			dsp.ServerName AS ServerName,
			dsp.ServerUID AS ServerUID,
			CASE
			WHEN (dsp.ConfigState = ''
				OR dsp.ConfigState IS NULL)
				AND dsp.ServerUID <> 0x00000000000000000000000000000000
				THEN 'NotConfigured'
			WHEN dsp.ConfigState <> 'Configured'
				THEN dsp.ConfigState
			WHEN 	(dsj.JobReported IS NOT NULL
				AND dsj.JobReported < DATEADD(Hour, @HoursBeforeDSOffline, GETUTCDATE()))
				OR (dsl.LogReported IS NOT NULL
				AND dsl.LogReported < DATEADD(Hour, @HoursBeforeDSOffline, GETUTCDATE()))
				THEN 'Offline'
			WHEN dsj.JobDelayedCount > 0
				OR dsl.LogDelayedCount > 0
				THEN 'Delayed'
			WHEN dsj.JobCount > 0
				OR dsl.LogCount > 0
				THEN 'Working'
			ELSE 'Ready'
			END AS ServerStatus,
			CASE
			WHEN (dsp.ConfigState = ''
				OR dsp.ConfigState IS NULL
				OR dsp.ConfigState = 'Pending')
				AND dsp.ServerUID <> 0x00000000000000000000000000000000
				THEN 'NotConfigured'
			WHEN dsp.ConfigState = 'Failed'
				THEN 'FailedConfigure'
			WHEN 	(dsj.JobReported IS NOT NULL
				AND dsj.JobReported < DATEADD(Hour, @HoursBeforeDSOffline, GETUTCDATE()))
				OR (dsl.LogReported IS NOT NULL
				AND dsl.LogReported < DATEADD(Hour, @HoursBeforeDSOffline, GETUTCDATE()))
				THEN 'Offline'
			WHEN dsj.JobDelayedCount > 0
				OR dsl.LogDelayedCount > 0
				THEN 'Delayed'
			WHEN dsj.JobCount > 0
				OR dsl.LogCount > 0
				OR dsp.ConfigState = 'Synchronizing'
				THEN 'Working'
			ELSE 'Ready'
			END AS ServerSummaryStatus,
			dsp.LastConfigStart AS ConfigDateTime,
			CASE
			WHEN dsj.JobReported < dsl.LogReported
				THEN DATEADD(minute, DATEDIFF(minute, GETUTCDATE(), GETDATE()), dsj.JobReported)
				ELSE DATEADD(minute, DATEDIFF(minute, GETUTCDATE(), GETDATE()), dsl.LogReported)
			END AS Reported,
			dsj.JobCount AS JobCount,
			dsj.JobDelayedCount AS JobDelayedCount,
			dsl.LogCount AS LogCount,
			dsl.LogDelayedCount AS LogDelayedCount
	
		FROM	(SELECT parent.ServerName AS ParentName,
				ISNULL(parent.ServerName +' / ', '') + ds.ServerName
					AS ServerFullName,
				ds.*
			FROM	DistributionServer AS ds
				LEFT OUTER JOIN
				DistributionServer AS parent
				ON ds.PrimaryParentUID = parent.ServerUID
			WHERE	ds.ServerType = 1
			  AND	(ds.ServerUID = @distID OR @distID IS NULL)
			) AS dsp		-- DistributionServer with parent info
		LEFT OUTER JOIN
		(
			SELECT	DISTINCT(dss.ServerUID) AS ServerUID,
				MAX(dss.ReportedDate) AS JobReported,
				SUM(dss.[Count]) AS JobCount,
				SUM(dss.DelayedCount) AS JobDelayedCount
			FROM	DistributionServerStatus AS dss
			WHERE	dss.Type = 'Job'
			GROUP BY dss.ServerUID
		) AS dsj
		ON dsj.ServerUID = dsp.ServerUID
		LEFT OUTER JOIN
		(
			SELECT	DISTINCT(dss.ServerUID) AS ServerUID,
				MAX(dss.ReportedDate) AS LogReported,
				SUM(dss.[Count]) AS LogCount,
				SUM(dss.DelayedCount) AS LogDelayedCount
			FROM	DistributionServerStatus AS dss
			WHERE	dss.Type = 'Log'
			GROUP BY dss.ServerUID
		) AS dsl
		ON dsp.ServerUID = dsl.ServerUID
	) AS dssd
	WHERE	dssd.ServerSummaryStatus LIKE @state
	   OR	(@state = 'Unhealthy' AND dssd.ServerSummaryStatus NOT IN ('Ready', 'Working'))
	ORDER BY dssd.ServerFullName
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'DistributionServerStatusSummary' AND xtype = 'P'
)
        DROP PROCEDURE DistributionServerStatusSummary
GO

CREATE PROCEDURE DistributionServerStatusSummary
AS
	DECLARE	@HoursBeforeDSOffline AS int

	IF (
		EXISTS(
			SELECT * FROM DatabaseConfiguration
			WHERE	Property = 'HoursBeforeDSOffline'
		)
	)
	BEGIN
		SELECT	@HoursBeforeDSOffline = 0 - CONVERT(int, Value)
		FROM	DatabaseConfiguration
		WHERE	Property = 'HoursBeforeDSOffline'
	END
	ELSE
		SET @HoursBeforeDSOffline = 0 - 24

	SELECT	COUNT(ds.ServerName) AS Total,
		SUM(CASE WHEN (ds.ConfigState = ''
			OR ds.ConfigState IS NULL
			OR ds.ConfigState = 'Pending')
			AND ds.ServerUID <> 0x00000000000000000000000000000000
			THEN 1 ELSE 0 END
		) AS NotConfigured,
		SUM(CASE WHEN ds.ConfigState = 'Failed'
			THEN 1 ELSE 0 END
		) AS FailedConfigure,
		SUM(CASE WHEN (ds.ConfigState IN ('Configured', 'Synchronized') OR ds.ServerUID = 0x00000000000000000000000000000000)
			AND (
				(dsj.JobReported IS NOT NULL AND dsj.JobReported < DATEADD(Hour, @HoursBeforeDSOffline, GETUTCDATE()))
				OR (dsl.LogReported IS NOT NULL AND dsl.LogReported < DATEADD(Hour, @HoursBeforeDSOffline, GETUTCDATE()))
			)
			THEN 1 ELSE 0 END
		) AS Offline,
		SUM(CASE WHEN ISNULL(dsj.JobDelayedCount, 0) + ISNULL(dsl.LogDelayedCount, 0) > 0
			AND (ds.ConfigState IN ('Configured', 'Synchronized') OR ds.ServerUID = 0x00000000000000000000000000000000)
			AND (
				(dsj.JobReported IS NOT NULL AND NOT dsj.JobReported < DATEADD(Hour, @HoursBeforeDSOffline, GETUTCDATE()))
				OR (dsl.LogReported IS NOT NULL AND NOT dsl.LogReported < DATEADD(Hour, @HoursBeforeDSOffline, GETUTCDATE()))
			)
			THEN 1 ELSE 0 END
		) AS Delayed,
		SUM(CASE WHEN ds.ConfigState = 'Synchronizing' OR
			(
				(ds.ConfigState IN ('Configured', 'Synchronized') OR ds.ServerUID = 0x00000000000000000000000000000000)
				AND (
					(dsj.JobReported IS NOT NULL AND NOT dsj.JobReported < DATEADD(Hour, @HoursBeforeDSOffline, GETUTCDATE()))
					OR (dsl.LogReported IS NOT NULL AND NOT dsl.LogReported < DATEADD(Hour, @HoursBeforeDSOffline, GETUTCDATE()))
				)
				AND ISNULL(dsj.JobDelayedCount, 0) + ISNULL(dsl.LogDelayedCount, 0) = 0
				AND ISNULL(dsj.JobCount, 0) + ISNULL(dsl.LogCount, 0) > 0
			)
			THEN 1 ELSE 0 END
		) AS Working,
		SUM(CASE WHEN (ds.ConfigState IN ('Configured', 'Synchronized') OR ds.ServerUID = 0x00000000000000000000000000000000)
			AND ISNULL(dsj.JobDelayedCount, 0) + ISNULL(dsl.LogDelayedCount, 0) +
				ISNULL(dsj.JobCount, 0) + ISNULL(dsl.LogCount, 0) = 0
			AND (dsj.JobReported IS NULL OR dsj.JobReported >= DATEADD(Hour, @HoursBeforeDSOffline, GETUTCDATE()))
			AND (dsl.LogReported IS NULL OR dsl.LogReported >= DATEADD(Hour, @HoursBeforeDSOffline, GETUTCDATE()))
			THEN 1 ELSE 0 END
		) AS Ready
	FROM	DistributionServer AS ds
	LEFT OUTER JOIN
	(
		SELECT	DISTINCT(dss.ServerUID) AS ServerUID,
			MAX(dss.ReportedDate) AS JobReported,
			SUM(dss.[Count]) AS JobCount,
			SUM(dss.DelayedCount) AS JobDelayedCount
		FROM	DistributionServerStatus AS dss
		WHERE	dss.Type = 'Job'
		GROUP BY dss.ServerUID
	) AS dsj
	ON dsj.ServerUID = ds.ServerUID
	LEFT OUTER JOIN
	(
		SELECT	DISTINCT(dss.ServerUID) AS ServerUID,
			MAX(dss.ReportedDate) AS LogReported,
			SUM(dss.[Count]) AS LogCount,
			SUM(dss.DelayedCount) AS LogDelayedCount
		FROM	DistributionServerStatus AS dss
		WHERE	dss.Type = 'Log'
		GROUP BY dss.ServerUID
	) AS dsl
	ON ds.ServerUID = dsl.ServerUID
	WHERE	ds.ServerType = 1
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'DistributionServerStatusCounts' AND xtype = 'P'
)
        DROP PROCEDURE DistributionServerStatusCounts
GO

CREATE PROCEDURE DistributionServerStatusCounts
	@distID		binary(16),
	@statusType	varchar(32),
	@delayedOnly	bit = 0
AS
	SELECT	dss.[Name] AS [Name],
		DATEADD(minute, DATEDIFF(minute, GETUTCDATE(), GETDATE()), dss.ReportedDate) AS Reported,
		dss.[Count] AS [Count],
		dss.DelayedCount AS DelayedCount
	FROM	DistributionServerStatus AS dss
	WHERE	dss.ServerUID = @distID
	  AND	dss.Type = @statusType
	  AND	(@delayedOnly = 0 OR dss.DelayedCount > 0)
	ORDER BY dss.[Name]
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'DistributionServerUploadSummaryList' AND xtype = 'P'
)
        DROP PROCEDURE DistributionServerUploadSummaryList
GO

CREATE PROCEDURE DistributionServerUploadSummaryList
AS
	SELECT	DISTINCT(dss.Name) AS Name,
		SUM(dss.[Count]) AS [Count],
		SUM(dss.[DelayedCount]) AS DelayedCount
	FROM	DistributionServerStatus AS dss
	WHERE	dss.Type = 'Log'
	GROUP BY dss.Name
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'DistributionServerUploadSummary' AND xtype = 'P'
)
        DROP PROCEDURE DistributionServerUploadSummary
GO

CREATE PROCEDURE DistributionServerUploadSummary
AS
	SELECT	DISTINCT(dss.[Name]) AS Type,
		SUM(dss.[Count]) AS Numbers
	FROM	DistributionServerStatus AS dss
	WHERE	dss.Type = 'Log'
	GROUP BY dss.[Name]
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'DistributionServerUploadDetails' AND xtype = 'P'
)
        DROP PROCEDURE DistributionServerUploadDetails
GO

CREATE PROCEDURE DistributionServerUploadDetails
	@logName	varchar(64),
	@delayedOnly	bit = 0
AS
	SELECT	ds.ServerName AS ServerName,
		DATEADD(minute, DATEDIFF(minute, GETUTCDATE(), GETDATE()), dss.ReportedDate) AS Reported,
		dss.[Count] AS [Count],
		dss.DelayedCount AS DelayedCount
	FROM	DistributionServer AS ds,
		DistributionServerStatus AS dss
	WHERE	dss.ServerUID = ds.ServerUID
	  AND	dss.Type = 'Log'
	  AND	dss.[Name] = @logName
	  AND	(@delayedOnly = 0 OR dss.DelayedCount > 0)
	  AND	dss.[Count] > 0
	ORDER BY ds.ServerName
GO
/* 
 * $Id: mgsDSDistributionConfig.sql 44422 2002-09-20 01:54:59Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsDSDistributionConfig
 *	Input:
 * 	- @distID (i.e. ServerUID of DS). 
 *
 *	Returns:
 *	- details of a single DS if passed in the ID of only a single DS -OR-
 *	- details of related DSs if a DS ID along with SQL Wildcard (%) is passed in
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsDSDistributionConfig' AND xtype = 'P'
)
        DROP PROCEDURE mgsDSDistributionConfig
GO

CREATE PROCEDURE [mgsDSDistributionConfig] 
	@distID BINARY (16)  -- Retrieve Data for a specific DS
AS
BEGIN

IF ( @distID IS NULL )
BEGIN
	RETURN
END

SELECT 
ds.ServerName AS ServerName,
ds.ConfigState, 
ds.LastConfigStart, 
ds.ConfigFailReason 
FROM 
DistributionServer ds
WHERE  
(ds.ServerUID = @distID) AND (ds.ServerType = 1)     

ORDER BY ServerName

END --end of begin loop

RETURN
GO
/* 
 * $Id: mgsHWClassManagedDevicesSummaryList.sql 95576 2010-01-21 02:54:16Z rlowery $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsHWClassManagedDevicesSummaryList
 * Show all Computers that contain a specific HW-Class.
 *	Input:
 * 	- @oudn: selected OU Name. - All OUs/ Specific OU  
 *	- @ouMatch: match on child OUs as well
 *	- @hwClass: Hardware Class
 *
 *	Returns:
 *	- ComputerID, ComputerCN, 
 *	- ComputerOUID, OUDN
 *	- HardwareName, Occurance
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsHWClassManagedDevicesSummaryList' AND xtype = 'P'
)
        DROP PROCEDURE mgsHWClassManagedDevicesSummaryList
GO

CREATE PROCEDURE mgsHWClassManagedDevicesSummaryList
	@oudn Varchar(800)='%',
	@ouMatch Bit=1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@hwClass Varchar(256), --WMI Hardware Class
	@compCN varchar(128)='%' --computer name (size=64*2 --to take into acct encoded chars)
AS
BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

	SELECT	ho.ComputerID,
		c.ComputerCN,
		c.ComputerOUID,
		dbo.OUName(s.OUID) AS OU, 
		ho.HardwareName,
		ho.Occurrence
	FROM	HardwareObject AS ho,
		HardwareClass AS hc,
		Computer AS c,
		#Organization AS s
	WHERE	ho.ComputerID = c.ComputerID
	  AND	c.ComputerOUID = s.OUID
	  AND	ho.HardwareClassID = hc.HardwareClassID
	  AND	hc.Class = @hwClass
	  AND	c.ComputerCN LIKE @compCN	-- match on computerCN

	ORDER BY c.ComputerCN, dbo.OUName(s.OUID), ho.Occurrence, ho.HardwareName
END
RETURN
GO
/*
 * $Id: mgsHWClassesInventorySummaryList.sql 95576 2010-01-21 02:54:16Z rlowery $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsHWClassesInventorySummaryList
 * Show all Hardware Classes with Computer Count
 *	Input:
 * 	- @oudn: selected OU Name. - All OUs/ Specific OU
 *	- @ouMatch: match on child OUs as well
 *
 *	Returns:
 *	- CLass, Count of Computers and Instances
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsHWClassesInventorySummaryList' AND xtype = 'P'
)
        DROP PROCEDURE mgsHWClassesInventorySummaryList
GO

CREATE PROCEDURE mgsHWClassesInventorySummaryList
	@oudn Varchar(800)='%',
	@ouMatch Bit=1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@hwClass Varchar(512)='%' --WMI Hardware Class (size=256*2 --to take into acct encoded chars)
AS

BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

	SELECT	hc.Class,
		COUNT(DISTINCT ho.ComputerID) as Computers,
		COUNT(ho.HardwareName) as Instances
	FROM	HardwareClass AS hc,
		HardwareObject AS ho,
		Computer AS c,
		#Organization AS s
	WHERE	hc.Class LIKE @hwClass	-- match on WMI Hardware Class
	  AND	hc.HardwareClassID = ho.HardwareClassID
	  AND	ho.ComputerID = c.ComputerID
	  AND	c.ComputerOUID = s.OUID
	GROUP BY hc.Class
	ORDER BY hc.Class
END

RETURN
GO
/* 
 * $Id: mgsManagedDeviceHWClassDetails.sql 51776 2003-12-10 00:35:41Z chrish $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsManagedDeviceHWClassDetails
 * (A Hardware Win32 Class is matched by HardwareName and Occurrence)
 *	Input:
 * 	- @compID
 *	- @hwName - HardwareName for a Class 
 *	- @hwOccurrence - Occurrence for a Class
 *
 *	Returns:
 *	- Property, Value
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsManagedDeviceHWClassDetails' AND xtype = 'P'
)
        DROP PROCEDURE mgsManagedDeviceHWClassDetails
GO

CREATE PROCEDURE mgsManagedDeviceHWClassDetails
	@compID as int,
	@hwName as Varchar(256),
	@hwOcc as int  
AS
	SELECT	hp.Property,
		hv.Value
	FROM	HardwareValue AS hv,
		HardwareProperty AS hp,
		HardwareObject AS ho
	WHERE	hv.HardwareObjectID = ho.HardwareObjectID
	  AND	hv.HardwarePropertyID = hp.HardwarePropertyID
	  AND	ho.ComputerID = @compID
	  AND	ho.HardwareName = ISNULL(@hwName, '')
	  AND	ho.Occurrence = @hwOcc	
GO
/* 
 * $Id: mgsManagedDeviceHWClassesSummaryList.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsManagedDeviceHWClassesSummaryList
 *	Input:
 * 	- @compID
 *
 *	Returns:
 *	- Class, HardwareName, Occurrence
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsManagedDeviceHWClassesSummaryList' AND xtype = 'P'
)
        DROP PROCEDURE mgsManagedDeviceHWClassesSummaryList
GO

CREATE PROCEDURE mgsManagedDeviceHWClassesSummaryList
	@compID as int
AS
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN

	SELECT	ho.ComputerID,
		c.ComputerCN,
		c.ComputerOUID,
		dbo.OUName(s.OUID) as OU, 
		hc.Class,
		ho.HardwareName, 
		ho.Occurrence 
	FROM	HardwareObject as ho,
	    	HardwareClass as hc,
		Computer as c,
		#Organization as s
	WHERE	ho.HardwareClassID = hc.HardwareClassID
	  AND	ho.ComputerID = c.ComputerID
	  AND	c.ComputerID = @compID
	  AND	c.ComputerOUID = s.OUID	
GO
/* 
 * $Id: mgsManagedDeviceSWInventoryDetails.sql 95576 2010-01-21 02:54:16Z rlowery $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsManagedDeviceSWInventoryDetails
 *	Input:
 * 	- @compID: ComputerID
 *
 *	Returns:
 *	- ComputerCN, OUDN 
 *  - SoftwareNameandVersion, Evidence
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsManagedDeviceSWInventoryDetails ' AND xtype = 'P'
)
        DROP PROCEDURE mgsManagedDeviceSWInventoryDetails 
GO

CREATE PROCEDURE mgsManagedDeviceSWInventoryDetails
	@compID int,
	@dllhdr_filter Varchar(32)='' -- Optional: Filter out these evidence rows
AS
	SELECT
		sv.SoftwareName + ' ' + sv.Version AS SoftwareNameAndVersion,
		so.Evidence		
	FROM	SoftwareOccurrence AS so,
		SoftwareVersion AS sv
	WHERE	so.SoftwareID = sv.SoftwareID		
	  AND	so.ComputerID = @compID
	  AND	so.UserID = 1 --Profile "All Users" or installed for System
	  AND	so.Evidence NOT LIKE @dllhdr_filter
	ORDER BY SoftwareNameAndVersion, Evidence
GO
/* 
 * $Id: mgsManagedDeviceSWInventoryDetailsFull.sql 95576 2010-01-21 02:54:16Z rlowery $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsManagedDeviceSWInventoryDetailsFull
 *	Input:
 * 	- @compID: ComputerID
 *
 *	Returns:
 *	- ComputerCN, OUDN 
 *  - SoftwareNameandVersion, Evidence
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsManagedDeviceSWInventoryDetailsFull' AND xtype = 'P'
)
        DROP PROCEDURE mgsManagedDeviceSWInventoryDetailsFull 
GO

CREATE PROCEDURE mgsManagedDeviceSWInventoryDetailsFull
	@ComputerID int,
	@dllhdr_filter Varchar(32)='' -- Optional: Filter out these evidence rows
AS
	SELECT     
		sv.SoftwareName + ' ' + sv.Version AS SoftwareNameAndVersion,
		svProductCode.[Value] AS ProductCode, 
		svActivationKey.[Value] AS ActivationKey, 
		svInstalledKey.[Value] AS InstalledKey, 
		so.Evidence
	FROM    SoftwareOccurrence AS so
		INNER JOIN Computer AS c ON so.ComputerID = c.ComputerID
		INNER JOIN SoftwareVersion AS sv ON so.SoftwareID = sv.SoftwareID
		LEFT OUTER JOIN SoftwareProperty AS spProductCode
			ON spProductCode.Property = 'ProductCode'
		LEFT OUTER LOOP JOIN SoftwareValue AS svProductCode
			ON so.SoftwareOccurrenceID = svProductCode.SoftwareOccurrenceID
			AND svProductCode.SoftwarePropertyID = spProductCode.SoftwarePropertyID
		LEFT OUTER JOIN SoftwareProperty AS spActivationKey
			ON spActivationKey.Property = 'ActivationKey'
		LEFT OUTER LOOP JOIN SoftwareValue AS svActivationKey
			ON so.SoftwareOccurrenceID = svActivationKey.SoftwareOccurrenceID
			AND svActivationKey.SoftwarePropertyID = spActivationKey.SoftwarePropertyID
		LEFT OUTER JOIN SoftwareProperty AS spInstalledKey
			ON spInstalledKey.Property = 'InstalledKey'
		LEFT OUTER LOOP JOIN SoftwareValue AS svInstalledKey
			ON so.SoftwareOccurrenceID = svInstalledKey.SoftwareOccurrenceID
			AND svInstalledKey.SoftwarePropertyID = spInstalledKey.SoftwarePropertyID
	WHERE   so.UserID = 1 --Profile "All Users" or installed for System
		AND so.Evidence NOT LIKE 'ExeHdr'
		AND so.Evidence NOT LIKE 'DllHdr'
		AND so.Evidence NOT LIKE @dllhdr_filter
	       	AND c.ComputerID = @ComputerID
	ORDER BY SoftwareNameAndVersion, so.Evidence

GO
/* 
 * $Id: mgsManagedDevicesInventorySummaryList.sql 90554 2008-12-02 04:49:18Z vcolquho $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsManagedDevicesInventorySummaryList
 *	Input:
 * 	- @oudn: selected OU Name. - All OUs/ Specific OU  
 *	- @ouMatch: match on child OUs as well
 *	- @allTargets: match on whether inventory present or not
 *	- @compCN: match on computer name. Default = all computers
 *
 *	Returns:
 *	- ComputerID, ComputerCN, OUDN 
 *	- LastSoftwareReportDate, LastHardwareReportDate
 *	- LastFilesReportDate, LastServicesReportDate
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsManagedDevicesInventorySummaryList' AND xtype = 'P'
)
        DROP PROCEDURE mgsManagedDevicesInventorySummaryList
GO


CREATE PROCEDURE mgsManagedDevicesInventorySummaryList
	@oudn Varchar(800)='%', 
	@ouMatch Bit=1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@allTargets Int=0, --Values:[0=only targets that have reported inventory | 1=all targets  | 2: Not Inventoried ]
	@compCN Varchar(128)='%' --computer name (size=64*2 --to take into acct encoded chars)

AS

BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0
END

IF @allTargets < 2 -- ALL items or Inventoried items
BEGIN 
		SELECT 
			c.ComputerID,
			c.ComputerCN AS [ComputerName],
			dbo.OUName(s.OUID) AS [OUDN],
			ir.SWDate AS [LastSoftwareReportDate],	
			ir.HWDate AS [LastHardwareReportDate],
			ir.FilesDate AS [LastFilesReportDate],
			ir.ServicesDate AS [LastServicesReportDate]

		FROM Computer AS c
			INNER JOIN #Organization AS s ON c.ComputerOUID = s.OUID
			LEFT OUTER JOIN InventoryReport AS ir
				ON c.ComputerID = ir.ComputerID AND ir.UserID = 1
				   --reported "System" User i.e. All Users on Computer
		WHERE
			(	@allTargets = 1
				OR SWDate IS NOT NULL
				OR HWDate IS NOT NULL
				OR FilesDate IS NOT NULL
				OR ServicesDate IS NOT NULL
			)
			AND c.ComputerCN LIKE @compCN -- match on ComputerCN (contains % - sql wildcard)

		ORDER BY dbo.OUName(s.OUID), c.ComputerCN
END
ELSE ---Only Not Inventoried items
BEGIN
		SELECT 
			c.ComputerID,
			c.ComputerCN AS [ComputerName],
			dbo.OUName(s.OUID) AS [OUDN],
			ir.SWDate AS [LastSoftwareReportDate],	
			ir.HWDate AS [LastHardwareReportDate],
			ir.FilesDate AS [LastFilesReportDate],
			ir.ServicesDate AS [LastServicesReportDate]

		FROM Computer AS c
			INNER JOIN #Organization AS s ON c.ComputerOUID = s.OUID
			LEFT OUTER JOIN InventoryReport AS ir
				ON c.ComputerID = ir.ComputerID AND ir.UserID = 1
				   --reported "System" User i.e. All Users on Computer
		WHERE
			(	SWDate IS NULL
				AND HWDate IS NULL
				AND FilesDate IS NULL
				AND ServicesDate IS NULL
			) -- All Dates are NULL
			AND c.ComputerCN LIKE @compCN -- match on ComputerCN (contains % - sql wildcard)

		ORDER BY dbo.OUName(s.OUID), c.ComputerCN
END

RETURN
GO
/* 
 * $Id: mgsManagedDeviceFilesInventoryDetails.sql 93496 2009-08-21 02:02:52Z esholl $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsManagedDeviceFilesInventoryDetails
 *				Returns file data for a specified computer (@compID)
 *
 *	Input:
 * 	- @compID: ComputerID
 *
 *	Returns:
 *	- FileName, FilePath
 *  - ProductName, ProductVersion
 *  - FileVersion, Company
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsManagedDeviceFilesInventoryDetails' AND xtype = 'P'
)
        DROP PROCEDURE mgsManagedDeviceFilesInventoryDetails 
GO

CREATE PROCEDURE mgsManagedDeviceFilesInventoryDetails
	@compID int
AS
	(SELECT
		sfn.Name AS FileName,
		sfp.Path AS FilePath,
		sv.SoftwareName AS ProductName,
		sv.Version AS ProductVersion,
		sf.FileVersion,
		sf.CompanyName AS Company
	FROM
		SoftwareFile AS sf
		JOIN SoftwareFileName AS sfn ON sfn.SoftwareFileNameID = sf.SoftwareFileNameID
		JOIN SoftwareFilePath AS sfp ON sfp.SoftwareFilePathID = sf.SoftwareFilePathID
		LEFT OUTER JOIN SoftwareVersion AS sv ON sv.SoftwareID = sf.SoftwareID
	WHERE 
		sf.ComputerID = @compID

	)
	ORDER BY 
		FileName, 
		ProductName, 
		ProductVersion, 
		FileVersion, 
		Company
GO
/* 
 * $Id: mgsManagedDeviceServicesInventoryDetails.sql 90554 2008-12-02 04:49:18Z vcolquho $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsManagedDeviceServicesInventoryDetails
 *				Returns service data for a specified computer (@compID)
 *
 *	Input:
 * 	- @compID: ComputerID
 *
 *	Returns:
 *	- Provider, Component
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsManagedDeviceServicesInventoryDetails' AND xtype = 'P'
)
        DROP PROCEDURE mgsManagedDeviceServicesInventoryDetails 
GO

CREATE PROCEDURE mgsManagedDeviceServicesInventoryDetails
	@compID int
AS
	SELECT
		spn.Name AS Provider,
		sc.Name AS Component
	FROM
		ServiceProvider AS sp
		JOIN ServiceProviderName AS spn ON spn.ServiceProviderNameID = sp.ServiceProviderNameID
		JOIN ServiceProviderComponent AS spc ON spc.ServiceProviderID = sp.ServiceProviderID
		JOIN ServiceComponent AS sc ON sc.ServiceComponentID = spc.ServiceComponentID
	WHERE sp.ComputerID = @compID
	ORDER BY spn.Name, sc.Name
GO
/* 
 * $Id: mgsOSBreakdown.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsOSBreakdown  
 *	Input:
 * 	- @oudn: selected OU-DN name.  default is all OUs
 *
 *	Returns:
 *	- OperatingSystem, Total
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsOSBreakdown' AND xtype = 'P'
)
        DROP PROCEDURE mgsOSBreakdown 
GO

CREATE PROCEDURE [mgsOSBreakdown]
	@oudn VARCHAR(800) = '%', --Default: For all OUs
	@ouMatch BIT=1 --Include sub-OUs (default: True i.e. 1)
AS 

BEGIN
	CREATE TABLE #Organization(OrganizationID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

	SELECT	os.OperatingSystemName
			AS [Operating System],
		COUNT(c.ComputerID) AS Total
	FROM	#Organization AS o,
		Computer AS c
		INNER JOIN
		(
			SELECT os2.OperatingSystemID, os2.OperatingSystemName
			FROM OperatingSystem AS os2
			UNION ALL
			SELECT OperatingSystemID = NULL, OperatingSystemName = 'Unknown'
		) AS os
		ON (c.OperatingSystemID = os.OperatingSystemID OR (c.OperatingSystemID IS NULL AND os.OperatingSystemID IS NULL))
	WHERE	o.OrganizationID = c.ComputerOUID

	GROUP BY os.OperatingSystemName
	ORDER BY os.OperatingSystemName
END

GO
/*
 * $Id: mgsPkgDistributionDetails.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsPkgDistributionDetails
 *	Input:
 * 	- @pkgFName, PackageFullName i.e. ID.
 * 	- @state (i.e. Distribution State). Default value is ALL.
 *
 *	Returns:
 *	- Package Name,
 *	- Version,
 *	- Package Fullname,
 *	- Location ID
 *	- Location Name (DL or DS)
 *	- Status (if showing all Distribution states)
 *	- Status Date-Time
 *	- Failure Reason
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsPkgDistributionDetails' AND xtype = 'P'
)
        DROP PROCEDURE mgsPkgDistributionDetails
GO

CREATE PROCEDURE mgsPkgDistributionDetails
	@pkgFName VARCHAR(256),
	-- States {'all', 'available', 'pending', 'removing', 'unavailable'}
	@state VARCHAR(15) = 'all',
	@pkgVer VARCHAR(32) = '%'
AS
	DECLARE @distType SMALLINT	-- Distribution type i.e. DS or DL
	SET @distType = 0	 	-- Set to DL=0

	-- Show ALL Distribution state for specified package
	SELECT	dsp.ServerFullName,
		CASE WHEN dp.RequestState = 'empty'
			THEN dp.ConfirmedState
			ELSE dp.RequestState
		END AS [Status],
		CASE WHEN dp.RequestState = 'empty'
			THEN dp.ConfirmedDate
			ELSE dp.RequestDate
		END AS [Date-Time],
		dp.ConfirmedReason AS [Failure Reason]

	FROM	PackagePath AS pp,
		PackageVersion AS pv,
	--	MediaContainsPackageVersion AS mcpv,
		DistributedPackage AS dp,
		(SELECT	ISNULL(parent.ServerName +' / ', '') + ds.ServerName
				AS ServerFullName,
			parent.ServerName AS ParentName,
			ds.*
		FROM	DistributionServer AS ds
			LEFT OUTER JOIN
			DistributionServer AS parent
			ON ds.PrimaryParentUID = parent.ServerUID
		WHERE	ds.ServerType = @distType
		) AS dsp		-- DistributionServer with parent info

	WHERE	pp.PackageFullName = @pkgFName		-- Specified package
	  AND	pp.PackagePathID = pv.PackagePathID	-- has a Version...
	--AND	pv.PackageVersionID = mcpv.PackageVersionID
	--AND	mcpv.MediaID = 1			-- ... in Warehouse
	  AND	pv.PackageVersionID = dp.RequestedVersionID -- ...distributed
	  AND	pv.Version LIKE @pkgVer
	  AND	dp.ServerUID = dsp.ServerUID	-- to this DistributionServer
	  AND (	@state = 'all'			-- Any ConfirmedState ok
	     OR @state = 'pending'
	     OR @state = 'removing'
	     OR dp.ConfirmedState = @state	-- or just the given state
	     OR (
			@state = 'available' AND dp.ConfirmedState = 'quarantined'
		)
	     OR (
			@state = 'available' AND dp.ConfirmedState = 'rolled back'
		)
	      )
	  AND (	@state = 'all'			-- Any RequestState
	     OR dp.RequestState
		= CASE	WHEN @state = 'available' -- RequestState must be empty
			  OR @state = 'unavailable'
			THEN 'empty'
			WHEN @state = 'removing' -- RequestState must match
			  OR @state = 'pending' -- RequestState must match
			THEN @state
		END
	      )

GO
/*
 * $Id: mgsPkgsDistributionSummary.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsPkgsDistributionSummary
 *	Note: Can only do summary of a package (not of like packages)
 *
 *	Input:
 *	- @pkgFName, PackageFullName i.e. ID.
 *
 *	Returns:
 *	- PackageName, Version, PackageFullName,
 *	- COUNT of pending, Count of available, Count of failed distributions and Total
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'PackageDistributionSummary' AND xtype = 'P'
)
        DROP PROCEDURE PackageDistributionSummary
GO
CREATE PROCEDURE PackageDistributionSummary
	@serverType	int,
	@pkgFName	varchar(256),
	@pkgVer		varchar(32) = '%'
AS
	SELECT	pf.PackageName,
		pv.Version,
		pp.PackageFullName,
		SUM(CASE WHEN (
				dp.ConfirmedState = 'available' OR
				dp.ConfirmedState = 'quarantined' OR
				dp.ConfirmedState = 'rolled back'
			 )
			  AND dp.RequestState = 'empty'
			 THEN 1 ELSE 0 END
		) AS Available,
		SUM(CASE WHEN dp.RequestState = 'pending'
			 THEN 1 ELSE 0 END
		) AS Pending,
		SUM(CASE WHEN dp.ConfirmedState = 'unavailable'
			  AND dp.RequestState = 'empty'
			 THEN 1 ELSE 0 END
		) AS Unavailable,
		SUM(CASE WHEN dp.RequestState = 'removing'
			 THEN 1 ELSE 0 END
		) AS Removing,
		COUNT(DISTINCT(ds.ServerUID)) AS Total

	FROM	DistributedPackage AS dp,
		DistributionServer AS ds,
		PackageVersion AS pv,
		PackagePath AS pp,
		PackageFamily AS pf

	WHERE	dp.ServerUID = ds.ServerUID		-- On which server?
	  AND	ds.ServerType = @serverType		-- Of this type
	  AND	dp.RequestedVersionID = pv.PackageVersionID -- Which package ver
	  AND	pv.PackagePathID = pp.PackagePathID	-- Which has a path
	  AND	pp.PackageFullName = @pkgFName		-- as requested
	  AND	pv.Version LIKE @pkgVer
	  AND	pv.PackageFamilyID = pf.PackageFamilyID

	GROUP BY pf.PackageName, pv.Version, pp.PackageFullName
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsPkgsDistributionSummary' AND xtype = 'P'
)
        DROP PROCEDURE mgsPkgsDistributionSummary
GO
CREATE PROCEDURE [mgsPkgsDistributionSummary]
	@pkgFName	VARCHAR(256),
	@pkgVer		VARCHAR(32) = '%'
AS
	EXEC PackageDistributionSummary 0, @pkgFName, @pkgVer
GO
/*
 * $Id: mgsPkgsDistributionSummaryList.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsPkgsDistributionSummaryList
 *	Input:
 *	- @pkgName, PackageName.  Default value is any/all packages
 *	- @pkgVer, Version.  Default value is any/all package Versions.
 *
 *	Returns:
 *	- PackageName, Version, PackageFullName,
 *	- COUNT of pending, Count of available, Count of failed distributions.
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'PackageDistributionSummaryList' AND xtype = 'P'
)
        DROP PROCEDURE PackageDistributionSummaryList
GO
CREATE PROCEDURE PackageDistributionSummaryList
	@serverType	int,
	@pkgName VARCHAR(128) = '%',
	@pkgVer VARCHAR(32)= '%'
AS
	SELECT	pp.PackageFullName,
		pf.PackageName,
		pv.Version,
		CASE
		WHEN pp.PackageFullName LIKE 'Package%'
			THEN 'Software'
		WHEN pp.PackageFullName LIKE 'Policy%'
			THEN 'Policy'
		WHEN pp.PackageFullName LIKE 'Schedule%'
			THEN 'Schedule'
		WHEN pp.PackageFullName LIKE 'OSMigration/OSImage%'
			THEN 'OSImage'
		WHEN pp.PackageFullName LIKE 'OSMigration/ComputerNameMapping%'
			THEN 'ComputerNameMapping'
		WHEN pp.PackageFullName LIKE 'OSMigration/RolloutConfiguration%'
			THEN 'RolloutConfiguration'
		ELSE	'Other' -- default
		END as Type,
		SUM(CASE WHEN (
				dp.ConfirmedState = 'available' OR
				dp.ConfirmedState = 'quarantined' OR
				dp.ConfirmedState = 'rolled back'
			 )
			  AND dp.RequestState = 'empty'
			 THEN 1 ELSE 0 END
		) AS Available,
		SUM(CASE WHEN dp.RequestState = 'pending'
			 THEN 1 ELSE 0 END
		) AS Pending,
		SUM(CASE WHEN dp.ConfirmedState = 'unavailable'
			  AND dp.RequestState = 'empty'
			 THEN 1 ELSE 0 END
		) AS Unavailable,
		SUM(CASE WHEN dp.RequestState = 'removing'
			 THEN 1 ELSE 0 END
		) AS Removing,
		COUNT(DISTINCT(ds.ServerUID)) AS Total

	FROM	DistributedPackage AS dp,
		DistributionServer AS ds,
		PackageVersion AS pv,
		PackagePath AS pp,
		PackageFamily AS pf

	WHERE	dp.ServerUID = ds.ServerUID		-- On which server?
	  AND	ds.ServerType = @serverType		-- Of this type
	  AND	dp.RequestedVersionID = pv.PackageVersionID -- Which package ver
	  AND	pv.PackagePathID = pp.PackagePathID	-- Which has a path
	  AND	pv.Version LIKE @pkgVer
	  AND	pv.PackageFamilyID = pf.PackageFamilyID
	  AND	pf.PackageName LIKE @pkgName

	GROUP BY pp.PackageFullName, pf.PackageName, pv.Version
	ORDER BY pp.PackageFullName
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsPkgsDistributionSummaryList' AND xtype = 'P'
)
        DROP PROCEDURE mgsPkgsDistributionSummaryList
GO
CREATE PROCEDURE mgsPkgsDistributionSummaryList
	@pkgName VARCHAR(128) = '%',
	@pkgVer VARCHAR(32)= '%'
AS
	EXEC PackageDistributionSummaryList 0, @pkgName, @pkgVer
GO
/*
 * $Id: mgsSWInventoryDetails.sql 95576 2010-01-21 02:54:16Z rlowery $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsSWInventoryDetails
 *	Input:
 * 	- @oudn: selected OU Name. - All OUs (default) / Specific OU
 *	- @ouMatch: match on child OUs as well (default)
 *	- @TargetTypeName: show results for 'computer' or 'user' or 'all'
 *	- @swName: Software Name. - All Softwares (default) /Specific Software
 *	- @swVer: Software Version. - All Versions (default) /Specific Version
 *
 *	Returns:
 *	- Computer and/or User, OU,
 *	- Version, Evidence
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsSWInventoryDetails' AND xtype = 'P'
)
        DROP PROCEDURE mgsSWInventoryDetails
GO

CREATE PROCEDURE [mgsSWInventoryDetails]
	@oudn VARCHAR(800) = '%',
	@ouMatch BIT=1, --Include sub-Ous 1=True, 0=False
	@TargetTypeName VARCHAR(10)='all', --Show only 'computer' or 'user' or 'all'
	@swName VARCHAR(128)='%', --Match on specific Software
	@swVer VARCHAR(32)='%', --Optional: A Version of Software (default: all versions)
	@dllhdr_filter Varchar(32)='' --Optional: Filter out these evidence rows
AS
BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

	IF @TargetTypeName = 'computer'
	begin

		SELECT
		c.ComputerCN as Computer,
		dbo.OUName(s.OUID) as OU,
		--so.SoftwareID, sv.SoftwareName,
		sv.Version,
		so.Evidence

		FROM SoftwareOccurrence so, SoftwareVersion sv, #Organization s, Computer c

		WHERE
			so.SoftwareID = sv.SoftwareID
			AND so.ComputerID = c.ComputerID
			AND so.UserID = 1 --User is 'System' or 'All Users'
			AND c.ComputerOUID = s.OUID --match only Computer OU
			AND sv.SoftwareName LIKE @swName --SoftwareName
			AND sv.Version LIKE @swVer --SoftwareVersion
			AND so.Evidence NOT LIKE @dllhdr_filter

		ORDER BY dbo.OUName(s.OUID), c.ComputerCN
	end

	ELSE IF @TargetTypeName = 'user'
	begin
		SELECT
		u.UserCN as [User],
		dbo.OUName(s.OUID) as OU,
		--so.SoftwareID, sv.SoftwareName,
		sv.Version,
		so.Evidence

		FROM SoftwareOccurrence so, SoftwareVersion sv, #Organization s, [User] u

		WHERE
			so.SoftwareID = sv.SoftwareID
			AND so.UserID = u.UserID
			AND so.UserID <> 1 --User is NOT 'System' or 'All Users'
			AND u.UserOUID = s.OUID --match only User OU
			AND sv.SoftwareName LIKE @swName --SoftwareName
			AND sv.Version LIKE @swVer --SoftwareVersion
			AND so.Evidence NOT LIKE @dllhdr_filter

		ORDER BY dbo.OUName(s.OUID), u.UserCN
	end

	ELSE IF @TargetTypeName = 'all'
	begin
		SELECT
		c.ComputerCN as Computer,

		[User] =
			CASE u.UserCN
				WHEN 'SYSTEM' THEN 'All Users'
				ELSE u.UserCN
			END,

		dbo.OUName(s.OUID) as OU,
		--so.SoftwareID, sv.SoftwareName,
		sv.Version,
		so.Evidence
		
		FROM SoftwareOccurrence so, SoftwareVersion sv, #Organization s, [User] u, Computer c

		WHERE
			so.SoftwareID = sv.SoftwareID
			AND so.ComputerID = c.ComputerID
			AND so.UserID = u.UserID
			AND s.OUID = (
				CASE u.UserID
					WHEN 1 THEN c.ComputerOUID
					ELSE u.UserOUID
				END
			)
			AND sv.SoftwareName LIKE @swName --SoftwareName
			AND sv.Version LIKE @swVer --SoftwareVersion
			AND so.Evidence NOT LIKE @dllhdr_filter

		ORDER BY dbo.OUName(s.OUID), c.ComputerCN, u.UserCN
	end
END --end of begin loop

RETURN
GO

/* 
 * $Id: mgsSWInventoryList.sql 46745 2003-03-12 23:06:13Z niteshk $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsSWInventoryList
 *	Input:
 *	- @swName: Software Name. - All Softwares (default) /Specific Software
 *
 *	Returns:
 *	- SoftwareName, VersionCount
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsSWInventoryList' AND xtype = 'P'
)
        DROP PROCEDURE mgsSWInventoryList 
GO

CREATE PROCEDURE [mgsSWInventoryList]
	@swName VARCHAR(128)='%'  --Match on specific Software (default: all software)
AS
BEGIN
	IF @swName = '%'   -- Get ALL software titles
	BEGIN
		SELECT SoftwareName, COUNT(DISTINCT Version) AS VersionCount 
		FROM   SoftwareVersion
		GROUP BY SoftwareName
		ORDER BY SoftwareName		
	END

	ELSE	-- Filter on the specified software titles(s)
	BEGIN
		SELECT SoftwareName, COUNT(DISTINCT Version) AS VersionCount 
		FROM   SoftwareVersion
		WHERE  SoftwareName LIKE @swName
		GROUP BY SoftwareName
		ORDER BY SoftwareName		
	END

END

RETURN

GO
/*
 * $Id: mgsSWInventorySummaryList.sql 95576 2010-01-21 02:54:16Z rlowery $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsSWInventorySummaryList
 *	Input:
 * 	- @oudn: selected OU Name. - All OUs (default) / Specific OU
 *	- @ouMatch: match on child OUs as well
 *
 *	Returns:
 *	- SoftwareName, VersionCount,
 *	- UsageByComp, UsageByUser
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsSWInventorySummaryList' AND xtype = 'P'
)
        DROP PROCEDURE mgsSWInventorySummaryList
GO

CREATE PROCEDURE [mgsSWInventorySummaryList]
	@oudn VARCHAR(800) = '%',
	@ouMatch BIT=1, --Include sub-Ous 1=True, 0=False
	@dllhdr_filter Varchar(32)='', --Optional: Filter out these evidence rows
	@swName Varchar(256)='%' --Software name (size=128*2 --to take into acct encoded chars)
AS
BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

	SELECT	sv.SoftwareName,
		COUNT(DISTINCT sv.Version) as VersionCount,
		COUNT(DISTINCT CASE WHEN so.UserID = 1 THEN so.ComputerID ELSE NULL END) AS UsageByComp,
		COUNT(DISTINCT CASE WHEN so.UserID <> 1 THEN so.UserID ELSE NULL END) AS UsageByUser
	FROM	SoftwareOccurrence so,
		SoftwareVersion sv,
		#Organization s,
		Computer c,
		[User] u
	WHERE	so.SoftwareID = sv.SoftwareID
	  AND so.UserID = u.UserID
	  AND so.ComputerID = c.ComputerID
	  AND s.OUID = (
		CASE u.UserID
			WHEN 1 THEN c.ComputerOUID
			ELSE u.UserOUID
		END
	  )
	  AND	so.Evidence NOT LIKE @dllhdr_filter
	  AND	sv.SoftwareName LIKE @swName --match on Software (contains % - sql wildcard)
	GROUP BY sv.SoftwareName
	ORDER BY sv.SoftwareName
END
GO
/*
 * $Id: mgsSWVersionsInventorySummaryList.sql 95576 2010-01-21 02:54:16Z rlowery $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsSWVersionsInventorySummaryList
 *	Input:
 * 	- @oudn: selected OU Name. - All OUs (default) / Specific OU
 *	- @ouMatch: match on child OUs as well
 *	- @swName: Software Name. - All Softwares (default) /Specific Software
 *
 *	Returns:
 *	- SoftwareName, Version,
 *	- UsageByComp, UsageByUser
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsSWVersionsInventorySummaryList' AND xtype = 'P'
)
        DROP PROCEDURE mgsSWVersionsInventorySummaryList
GO

CREATE PROCEDURE [mgsSWVersionsInventorySummaryList]
	@oudn VARCHAR(800) = '%',
	@ouMatch BIT=1, --Include sub-Ous 1=True, 0=False
	@swName VARCHAR(128)='%', --Do ALL Softwares OR Match on specific software
	@dllhdr_filter Varchar(32)='' --Optional: Filter out these evidence rows
AS
BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

	SELECT 	sv.SoftwareName,
		sv.Version,
		SUM(CASE WHEN so.UserID = 1 THEN 1 ELSE 0 END) AS UsageByComp,
		SUM(CASE WHEN so.UserID <> 1 THEN 1 ELSE 0 END) AS UsageByUser
	FROM 	SoftwareVersion sv
	LEFT OUTER JOIN SoftwareOccurrence AS so ON
		sv.SoftwareID = so.SoftwareID
		AND so.Evidence NOT LIKE @dllhdr_filter
	INNER JOIN Computer AS c ON
		so.ComputerID = c.ComputerID
	INNER JOIN [User] AS u ON
		so.UserID = u.UserID
	INNER JOIN #Organization AS s ON
		(
			CASE u.UserID
				WHEN 1 THEN c.ComputerOUID
				ELSE u.UserOUID
			END
		) = s.OUID
	WHERE sv.SoftwareName LIKE @swName --SoftwareName
	GROUP BY sv.SoftwareName, sv.Version, so.SoftwareID
	ORDER BY sv.SoftwareName, sv.Version	
END --end of begin loop

RETURN
GO

/* 
 * $Id: mgsSoftwareProductAllocationSummary.sql 95576 2010-01-21 02:54:16Z rlowery $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsSoftwareProductAllocationSummary
 *	Input:
 * 	- @ouid: selected OUID.  (for a OUDN)
 * 	- @allocationId : AllocationID (for an Allocation for a Software Product and OUDN)
 *
 *	Returns:
 *	- AllocationID, OUID, OU, 
 *	- SoftwareProductID, ProductName, Publisher, 
 *	- Expiry, UnitsAllocated, TargetType, 
 *	- UsageByComp, UsageByUser
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsSoftwareProductAllocationSummary' AND xtype = 'P'
)
        DROP PROCEDURE mgsSoftwareProductAllocationSummary 
GO

CREATE PROCEDURE mgsSoftwareProductAllocationSummary
	@ouid int,
	@allocationId int 
AS	
BEGIN

CREATE TABLE #summaryTbl
(	
	AllocationID INT,
	OUID INT , 
	OU VARCHAR(800) COLLATE database_default, 
	SoftwareProductID INT, 
	ProductName VARCHAR(256) COLLATE database_default, 
	PublisherID INT,
	Expiry DATETIME,
	UnitsAllocated INT, 
	TargetType VARCHAR(256) COLLATE database_default, 
	UsageByComp INT, 
	UsageByUser  INT
)

declare @ou Varchar(800)
set @ou = dbo.OUName(@ouid)

--Go ahead if OU has any any Allocation against it
IF ( @ou IS NOT NULL)
begin	
	DECLARE @ouTmp Varchar(800)
	DECLARE @ouChild Varchar(800)
	
	SET @ouChild = ('%,' + @ou)   
	
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @ouChild, 1, 0

	--Get the details about Software Product for a AllocationID 
	DECLARE sprod_pubList_cursor CURSOR FOR 
		SELECT	sp.SoftwareProductID,
			sp.ProductName,
			sp.PublisherID,
			sp.TrackedByID
		FROM	SoftwareProduct AS sp,
			LicenseAllocation AS la
		WHERE	la.SoftwareProductID = sp.SoftwareProductID
		  AND	la.allocationID = @allocationId

	DECLARE @sprodID int
	DECLARE @prodTmp VARCHAR(256)
	DECLARE @pubTmp int
	DECLARE @targetTypeID int

	OPEN sprod_pubList_cursor
	FETCH NEXT FROM sprod_pubList_cursor INTO @sprodID, @prodTmp, @pubTmp, @targetTypeID	
	IF @@FETCH_STATUS =0
	begin
		IF 
		(	
			( Select COUNT (DISTINCT AllocationID )
				from LicenseAllocation
				where AllocationID = @allocationId  
			) 
			> 0
		)
		begin
			-- Get ALL SUB-OUs with Allocation for a SoftwareProductID
			-- Can return EMPTY values, if:
			-- 	- there is no Allocation allotment on sub-ous
			--	- does not contain any sub-ous
			DECLARE allocation_ouList_cursor CURSOR FOR 
				SELECT dbo.OUName(s.OUID)
				FROM #Organization AS s, LicenseAllocation AS la, SoftwareProduct AS sp
				WHERE 
				(	s.OUID = la.OrganizationID
					AND la.SoftwareProductID = sp.SoftwareProductID					
					AND sp.SoftwareProductID = @sprodID 			
				)
		
			-- Get all SUB-OUs without any Allocation for a SoftwareProductID
			SELECT DISTINCT #Organization.OUID, dbo.OUName(OUID) AS OU
			INTO #childrenTbl
			FROM #Organization AS s
				LEFT OUTER JOIN 
				(
					LicenseAllocation AS la
					INNER JOIN SoftwareProduct AS sp 
					ON la.SoftwareProductID = sp.SoftwareProductID
				)
				ON s.OUID = la.OrganizationID
			WHERE (sp.SoftwareProductID <> @sprodID OR sp.SoftwareProductID IS NULL)
		
			--Insert Parent OU with Allocation
			--	-Note: Will contain only parent if there are no children
			INSERT INTO #childrenTbl Select OUID, dbo.OUName(OUID) AS OU  from #Organization where dbo.OUName(OUID) = @ou 	
		
			OPEN allocation_ouList_cursor
			FETCH NEXT FROM allocation_ouList_cursor INTO @ouTmp	    
		
			WHILE @@FETCH_STATUS = 0
			begin
				-- Delete that are children of other sub-ou with Product Allocation
				-- therefore, resultant set is parent OU with Allocation and its children
				-- without Allocation and inherit the same from its parent OU
				DELETE from #childrenTbl where RIGHT(OU, LEN(@ouTmp)) = @ouTmp	
				FETCH NEXT FROM allocation_ouList_cursor INTO @ouTmp
			end
			CLOSE allocation_ouList_cursor
			DEALLOCATE allocation_ouList_cursor			
								
			INSERT INTO #summaryTbl
			SELECT 
				@allocationID as AllocationID, 
				@ouid as OUID, 
				@ou as OU ,
				@sprodID as SoftwareProductID, 
				ISNULL(sp.ProductName, @prodTmp), 
				ISNULL(sp.PublisherID, @pubTmp),
				
				Expiry = 
					( SELECT DISTINCT Expiry 
						from LicenseAllocation
						where AllocationID = @allocationID 
					),

				UnitsAllocated = 
					( SELECT DISTINCT UnitsAllocated 
						from LicenseAllocation 
						where AllocationID = @allocationID 
					),						
	
				TargetType = 
					( SELECT TargetTypeName 
						from TargetType 
						where TargetTypeID = @targetTypeID
					), 


				/* 
				 * NOTE: VJ: 12/12/2001
				 * Usage by Computer = License Count of computers on which Software is installed
				 * irrespective of whether it is installed for All Users or specific Users
				 */

				(
					SELECT COUNT(DISTINCT so1.ComputerID)
						from SoftwareOccurrence as so1, SoftwareVersion as sv1, ProductContainsSoftware as pcs1, Computer as c
						where ( /* so1.UserID = 1 AND  */ --See above noted comment
							so1.ComputerID = c.ComputerOUID AND
							c.ComputerOUID = ct.OUID AND 								
							so1.SoftwareID = sv1.SoftwareID AND 
							sv1.SoftwareID = pcs1.SoftwareVersionID AND
							pcs1.SoftwareProductID = @sprodID
						) 
				) AS UsageByComp, 	


				/* 
				 * NOTE: VJ: 12/12/2001
				 * Usage by User = License Count of Users for whom Software is installed
				 * irrespective of whether it is installed on one computer or different computers.
				 * However, this does not include Software installed for All Users on any computer.
				 */

				(
					SELECT COUNT(DISTINCT so1.UserID)
						from SoftwareOccurrence as so1, SoftwareVersion as sv1, ProductContainsSoftware as pcs1
						where ( so1.UserID <> 1 AND 
							so1.UserOUID = ct.OUID AND 
							so1.SoftwareID = sv1.SoftwareID AND 
							sv1.SoftwareID = pcs1.SoftwareVersionID AND
							pcs1.SoftwareProductID = @sprodID 
						)
				) AS UsageByUser 

				FROM 
				#childrenTbl as ct 
				LEFT OUTER JOIN LicenseAllocation as la
					INNER JOIN SoftwareProduct as sp						
					ON 
					(
						la.SoftwareProductID = sp.SoftwareProductID 
						AND la.AllocationID = @allocationID
					)			 
				ON ct.OUID = la.OUID	
														
				GROUP BY ct.OUID, OU, UnitsAllocated, sp.ProductName, sp.PublisherID, 
						sp.Trackedby, la.AllocationID, Expiry		

			DROP TABLE #childrenTbl		

		END	
		
	END
	CLOSE sprod_pubList_cursor
	DEALLOCATE sprod_pubList_cursor
end

 
SELECT 
	AllocationID,
	OUID, 
	OU, 
	SoftwareProductID, 
	ProductName, 
	spub.Name AS [Publisher], 
	Expiry,
	UnitsAllocated, 
	TargetType, 
	SUM(UsageByComp) as UsageByComp, 
	SUM(UsageByUser) as UsageByUser

	FROM #summaryTbl AS stbl, SoftwarePublisher AS spub
	WHERE stbl.PublisherID = spub.PublisherID
	GROUP BY AllocationID, OUID, OU, SoftwareProductID, ProductName, spub.Name, UnitsAllocated, TargetType, Expiry
	ORDER BY Expiry DESC
	
DROP TABLE #summaryTbl

END

GO
/*
 * $Id: mgsUserSWInventoryDetails.sql 95576 2010-01-21 02:54:16Z rlowery $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsUserSoftwareInventoryDetails
 *	Input:
 * 	- @userID: UserID
 *
 *	Returns:
 *	- UserCN, OUDN
 *  - SoftwareNameandVersion, Evidence
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsUserSWInventoryDetails' AND xtype = 'P'
)
        DROP PROCEDURE mgsUserSWInventoryDetails
GO

CREATE PROCEDURE mgsUserSWInventoryDetails
	@userID int,
	@dllhdr_filter Varchar(32)='' --Optional: Filter out these evidence rows
AS
	SELECT	c.ComputerCN as [Computer],
		sv.SoftwareName + ' ' + sv.Version
			AS [Software Name and Version],
		so.Evidence,
		dbo.OUName(c.ComputerOUID) AS [Computer OU]
	FROM	SoftwareOccurrence AS so,
		SoftwareVersion AS sv,
		Computer AS c
	WHERE	so.SoftwareID = sv.SoftwareID
	  AND	so.UserID = @userID
	  AND	so.UserID <> 1		-- Should not be "All Users" or SYSTEM
	  AND	so.ComputerID = c.ComputerID
	  AND	so.Evidence NOT LIKE @dllhdr_filter
	ORDER BY [Computer OU], c.ComputerCN, sv.SoftwareName, sv.Version, Evidence
GO
/* 
 * $Id: mgsUsersSWInventorySummaryList.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsUsersSWInventorySummaryList
 *	Input:
 * 	- @oudn: selected OU Name. - All OUs/ Specific OU  
 *	- @ouMatch: match on child OUs as well
 *
 *	Returns:
 *	- UserID, UserCN, OUDN 
 *	- LastReportDate 
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsUsersSWInventorySummaryList' AND xtype = 'P'
)
        DROP PROCEDURE mgsUsersSWInventorySummaryList 
GO

CREATE PROCEDURE mgsUsersSWInventorySummaryList
	@oudn Varchar(800)='%', 
	@ouMatch Bit=1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@userCN Varchar(128)='%' --User name (size=64*2 -- to take into acct encoded chars)
AS

BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

	Select 
	ir.UserID,
	u.UserCN as [UserName],
	dbo.OUName(s.OUID) as [OUDN],
	MAX(ir.SWDate) as [LastReportDate] -- Required for Roaming User

	from InventoryReport as ir, [User] as u, #Organization as s

	where 
		ir.UserID = u.UserID
		AND u.UserOUID = s.OUID
		AND ir.UserID <> 1 --not reported "System" User i.e. not All Users profile
		AND u.UserCN LIKE @userCN --match on userCN (contains % - sql wildcard)
		
	group by ir.UserID, u.UserCN, dbo.OUName(s.OUID)
	
	order by dbo.OUName(s.OUID), u.UserCN
END

RETURN
GO
/*
 * $Id: mgsDistServerNameAndUIDByServerType.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: mgsDistServerNameAndUIDByServerType
 * Input:
 * - @pServerType. - Input param
 * - @ServerName, @ServerUID. - Output param
 *
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'mgsDistServerNameAndUIDByServerType' AND xtype = 'P'
)
        DROP PROCEDURE mgsDistServerNameAndUIDByServerType
GO

CREATE PROCEDURE [mgsDistServerNameAndUIDByServerType]
	@pServerType int = 0
AS
BEGIN
	SELECT ServerName, ServerUID
	FROM   DistributionServer
	WHERE  ServerType = @pServerType
END
GO
/*
 * DROP PROCEDURE AUSummary
 * GO
 */

-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'AUSummary' AND xtype = 'P'
)
	DROP PROCEDURE AUSummary
GO

CREATE PROCEDURE AUSummary
	@fromDate AS DATETIME=NULL,
	@tillDate AS DATETIME=NULL,	--
	@swName AS VARCHAR(256)='%',	--SoftwareName, for filter purposes. Software name 
					--(size=128*2 --to take into acct encoded chars)
	@oudn AS VARCHAR(800)=NULL, 	--DN of the selected OU
	@ouMatch AS BIT=0,		--0 if we traverse down to sub OUs, 1 otherwise
	@spId AS INTEGER=NULL		-- License we care about if any
AS 
BEGIN

IF(
	(@fromDate IS NOT NULL)
	AND (@tillDate IS NOT NULL)
	AND (@swName IS NOT NULL)
	AND (DATEDIFF(Day,@fromDate,@tillDate) >= 4)
)
BEGIN


-- The StartOfWeek represents the start of the week in which usage has been reported 
-- and NOT the day the usage has been reported. 
-- Thus we need to do some processing to map the date ranges (from and till date) back
-- to the start of the week
DECLARE @l_fromDate AS DATETIME
DECLARE @l_tillDate AS DATETIME
SET @l_fromDate = dbo.GetStartOfWeekForDate(@fromDate)
SET @l_tillDate = dbo.GetStartOfWeekForDate(@tillDate)

--Local variables
DECLARE @l_period AS INTEGER
-- + 6 days to bring the period to the end of the week.
-- Same reason we set the tillDate to 11:59:59 pm.
SET @l_period = DATEDIFF(DAY,@l_fromDate,@l_tillDate) + 6

CREATE TABLE #Organization(OUID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

SELECT au.SoftwareID AS SoftwareID,
	sv.SoftwareName AS SoftwareName,
	sv.Version AS Version,
	au.Never AS Never,
	au.Occasional AS Occasional,
	au.Frequent AS Frequent,
	au.Continual AS Continual,
	SUM(au.Never + au.Occasional + au.Frequent + au.Continual) AS Total
FROM (
	--Rotate field values of w.frequency into columns
	SELECT SoftwareID,
		sum(CASE WHEN Used = 'never' THEN NumComps
		ELSE 0 END) AS Never,
		sum(CASE WHEN Used = 'occasional' THEN NumComps
		ELSE 0 END) AS Occasional,
		sum(CASE WHEN Used = 'frequent' THEN NumComps
		ELSE 0 END) AS Frequent,
		sum(CASE WHEN Used = 'continual' THEN NumComps
		ELSE 0 END) AS Continual
	FROM (
		SELECT ul.SoftwareID AS SoftwareID,
			ul.Used AS Used,
			COUNT(ul.ComputerID) AS NumComps
		FROM (
			--List of computers that have reported usage, regardless of whether
			--the the software was known to be installed
			SELECT DISTINCT uc.ComputerID AS ComputerID,
				uc.SoftwareID AS SoftwareID,
				(
					CASE
					WHEN SUM(uc.Days) = 0 THEN 'Never'
					WHEN SUM(uc.Days) <= @l_period/4 THEN 'Occasional'
					WHEN SUM(uc.Days) > @l_period/4 AND SUM(uc.Days) <= @l_period/2 THEN 'Frequent'
					ELSE 'Continual' END
				) AS Used
				--List of usage information matching the list of computers
				--and is within our interested date range.
			FROM (
				--List of usage information where usage days are summed.
				SELECT d.ComputerID AS ComputerID,
					d.SoftwareID AS SoftwareID,
					(
						CASE
						WHEN d.StartOfWeek < @l_fromDate
						THEN 0
						ELSE d.Days END
					) AS Days
				FROM (
					SELECT sUsage.ComputerID AS ComputerID,
						sUsage.SoftwareID AS SoftwareID,
						sUsage.Days AS Days,
						sUsage.StartOfWeek AS StartOfWeek
					FROM (
						--List of relevent computers
						SELECT c.ComputerID AS ComputerID,
							c.ComputerCN AS ComputerCN
						FROM Computer c, #Organization s 
						WHERE c.ComputerOUID = s.OUID
					) AS fc, SoftwareUsagePerWeek AS sUsage
					WHERE fc.ComputerID = sUsage.ComputerID
					  AND sUsage.StartOfWeek <= @l_tillDate
				) AS d
			) AS uc
			GROUP BY ComputerID, SoftwareID
			UNION
			--List of computers with software installed but never used them
			SELECT i.ComputerID AS ComputerID,
				i.SoftwareID AS SoftwareID,
				'Never' AS Used
			FROM (
			--List of computers with software installed, and the ids of
				--those software.
				SELECT DISTINCT o.ComputerID AS ComputerID,
					o.SoftwareID AS SoftwareID
				FROM (
					--List of relevent computers
					SELECT c.ComputerID AS ComputerID,
						c.ComputerCN AS ComputerCN
					FROM Computer c, #Organization s 
					WHERE c.ComputerOUID = s.OUID
				) AS rc, SoftwareOccurrence AS o
				WHERE rc.ComputerID = o.ComputerID
			) AS i
			WHERE NOT EXISTS(
				SELECT ComputerID, SoftwareID
				FROM SoftwareUsagePerWeek AS s
				WHERE i.ComputerID = s.ComputerID
				  AND i.SoftwareID = s.SoftwareID
			)
		) AS ul
		--Ingore usage summary that has errors.
		WHERE ul.Used <> 'Broken'
		GROUP BY ul.SoftwareID, ul.Used
	) AS h
	GROUP BY h.SoftwareID
) AS au, SoftwareVersion AS sv
WHERE au.SoftwareID = sv.SoftwareID
  AND sv.SoftwareName LIKE @swName
  AND (
		@spId IS NULL OR
		EXISTS (
			SELECT SoftwareProductID
			FROM ProductContainsSoftware
			WHERE SoftwareProductID = @spId AND
				SoftwareVersionId = au.SoftwareID
		)
	)

GROUP BY sv.Version,
	sv.SoftwareName,
	au.SoftwareID,
	au.Never,
	au.Occasional,
	au.Frequent,
	au.Continual

END /*Outer most IF*/
END /*Create procedure*/
GO

/*
 * DROP PROCEDURE AUSessionsSummary
 * GO
 */

-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'AUSessionsSummary' AND xtype = 'P'
)
	DROP PROCEDURE AUSessionsSummary
GO

CREATE PROCEDURE AUSessionsSummary
	@fromDate AS DATETIME=NULL,	--from and till must be at least 4 days apart!
	@tillDate AS DATETIME=NULL,	--
	@svId AS INTEGER=NULL,		--The software id
	@compCN AS VARCHAR(64)='%',	--Filter computer name
	@usageCat AS VARCHAR(16)='Never', -- Usage category. Supports the following values:
					-- Never, Occasional, Frequent, Continual, Total. If you
					-- change the values here, remember to change all
					-- other related procedures, data managers and reports.
	@oudn AS VARCHAR(800)=NULL, 	--DN of the selected OU
	@ouMatch AS BIT=0		--0 if we traverse down to sub OUs, 1 otherwise
AS 
BEGIN

--start
IF(
	(@compCN IS NOT NULL)
	AND (@fromDate IS NOT NULL)
	AND (@tillDate IS NOT NULL)
	AND (@svId IS NOT NULL)
	AND (@usageCat IS NOT NULL)
	AND (
		(UPPER(@usageCat) = 'NEVER')
		OR (UPPER(@usageCat) = 'OCCASIONAL')
		OR (UPPER(@usageCat) = 'FREQUENT')
		OR (UPPER(@usageCat) = 'CONTINUAL')
		OR (UPPER(@usageCat) = 'TOTAL')
	)
	AND (DATEDIFF(Day, @fromDate, @tillDate) >= 4)
)
BEGIN

-- The StartOfWeek represents the start of the week in which usage has been reported 
-- and NOT the day the usage has been reported. 
-- Thus we need to do some processing to map the date ranges (from and till date) back
-- to the start of the week
DECLARE @l_fromDate AS DATETIME
DECLARE @l_tillDate AS DATETIME
SET @l_fromDate = dbo.GetStartOfWeekForDate(@fromDate)
SET @l_tillDate = dbo.GetStartOfWeekForDate(@tillDate)

--Local variables
DECLARE @l_uUsageRange AS INTEGER --upper usage range, eg 50 days
DECLARE @l_lUsageRange AS INTEGER --lower usage range, eg 25 days
DECLARE @l_softwareName AS VARCHAR(128)
DECLARE @l_version AS VARCHAR(32) --version of software
DECLARE @l_period AS INTEGER

-- + 6 days to bring the period to the end of the week.
-- Same reason we set the tillDate to 11:59:59 pm.
SET @l_period = DATEDIFF(Day,@l_fromDate,@l_tillDate) + 6

SELECT @l_softwareName = sv.SoftwareName,
	@l_version = sv.Version
FROM SoftwareVersion AS sv
WHERE sv.SoftwareID = @svId

CREATE TABLE #Organization(OUID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

IF (UPPER(@usageCat) = 'TOTAL')
BEGIN


	--List of computers that have reported usage, regardless of whether
	--the the software was known to be installed
	SELECT DISTINCT uc.SoftwareID AS SoftwareID,
		@l_softwareName AS SoftwareName,
		@l_version AS Version,
		uc.ComputerID AS ComputerID,
		uc.ComputerCN AS ComputerCN,
		(
			CASE WHEN uc.Days = 0 THEN 0
			ELSE uc.Sessions END
		) AS Sessions,
		(
			CASE WHEN uc.Days = 0 THEN 0
			ELSE uc.Weeks END
		)AS Weeks,
		(
			CASE WHEN uc.Days = 0 THEN 0
			ELSE uc.Duration END
		) AS RunTime,
		(
			CASE WHEN uc.Days = 0 THEN 0
			ELSE uc.ActiveTime END
		) AS ActiveTime
	FROM (
		--Everythings summed
		SELECT w.ComputerID AS ComputerID
			,w.ComputerCN AS ComputerCN
			,w.SoftwareID AS SoftwareID
			,SUM(w.Sessions) AS Sessions
			,SUM(w.Duration) AS Duration
			,SUM(w.ActiveTime) AS ActiveTime
			,SUM(w.Days) AS Days
			,SUM(w.Weeks) AS Weeks
		FROM (
			--Prepared weeks for summing
			SELECT s.ComputerID AS ComputerID,
				s.ComputerCN AS ComputerCN,
				s.SoftwareID AS SoftwareID,
				s.Sessions AS Sessions,
				(
					CASE
					WHEN s.StartOfWeek < @l_fromDate
					THEN 0
					ELSE 1 END
				) AS Weeks,
				s.Duration AS Duration,
				s.ActiveTime AS ActiveTime,
				s.Days AS Days
			FROM (
				--List of usage information where usage days are set
				--to 0.
				SELECT d.ComputerID AS ComputerID,
					d.ComputerCN AS ComputerCN,
					d.SoftwareID AS SoftwareID,
					d.StartOfWeek AS StartOfWeek,
					(
						CASE
						WHEN d.StartOfWeek < @l_fromDate
						THEN 0
						ELSE SUM(d.Sessions) END
					) AS Sessions,
					(
						CASE
						WHEN d.StartOfWeek < @l_fromDate
						THEN 0
						ELSE SUM(d.Duration) END
					) AS Duration,
					(
						CASE
						WHEN d.StartOfWeek < @l_fromDate
						THEN 0
						ELSE SUM(d.ActiveTime) END
					) AS ActiveTime,
					(
						CASE
						WHEN d.StartOfWeek < @l_fromDate
						THEN 0
						ELSE SUM(d.Days) END
					) AS Days
				FROM (
					--Usage information for list of target users
					SELECT sUsage.ComputerID AS ComputerID,
						fc.ComputerCN AS ComputerCN,
						sUsage.SoftwareID AS SoftwareID,
						sUsage.Days AS Days,
						sUsage.StartOfWeek AS StartOfWeek,
						sUsage.Sessions AS Sessions,
						sUsage.Duration AS Duration,
						sUsage.ActiveTime AS ActiveTime
					FROM (
						--List of relevent computers
						SELECT c.ComputerID AS ComputerID,
							c.ComputerCN AS ComputerCN
						FROM Computer c, #Organization s 
						WHERE c.ComputerOUID = s.OUID
					) AS fc, SoftwareUsagePerWeek AS sUsage
					WHERE fc.ComputerID = sUsage.ComputerID
					  AND sUsage.SoftwareID = @svId
					  AND sUsage.StartOfWeek <= @l_tillDate
				) AS d
				GROUP BY ComputerID, ComputerCN, SoftwareID, StartOfWeek
			) AS s
		) AS w
		GROUP BY ComputerID, ComputerCN, SoftwareID
	) AS uc
	WHERE uc.ComputerCN LIKE @compCN

	UNION
	--List of computers with software installed but never used them
	SELECT 	i.SoftwareID AS SoftwareID,
		@l_softwareName AS SoftwareName,
		@l_version AS Version,
		i.ComputerID AS ComputerID,
		i.ComputerCN AS ComputerCN,
		0 AS Sessions,
		0 AS Weeks,
		0 AS RunTime,
		0 AS ActiveTime
	FROM (
		--List of computers with software installed, and the ids of
		--those software.
		SELECT DISTINCT o.ComputerID AS ComputerID,
			rc.ComputerCN AS ComputerCN,
			o.SoftwareID AS SoftwareID
		FROM (
			--List of relevent computers
			SELECT c.ComputerID AS ComputerID,
				c.ComputerCN AS ComputerCN
			FROM Computer c, #Organization s 
			WHERE c.ComputerOUID = s.OUID
		) AS rc, SoftwareOccurrence AS o
		WHERE rc.ComputerID = o.ComputerID
		  AND o.SoftwareID = @svId
	) AS i
	WHERE NOT EXISTS(
		SELECT ComputerID, SoftwareID
		FROM SoftwareUsagePerWeek AS s
		WHERE i.ComputerID = s.ComputerID
		  AND i.SoftwareID = s.SoftwareID
		)
	  AND i.ComputerCN LIKE @compCN

END /* IF @usageCat = TOTAL */
ELSE IF (UPPER(@usageCat) = 'NEVER')
BEGIN
	--Dealing with the never category.

	--Final query
	SELECT uc.SoftwareID AS SoftwareID,
		@l_softwareName AS SoftwareName,
		@l_version AS Version,
		uc.ComputerID AS ComputerID,
		uc.ComputerCN AS ComputerCN,
		0 AS Sessions,
		0 AS Weeks,
		0 AS RunTime,
		0 AS ActiveTime
	FROM (
		SELECT s.ComputerID AS ComputerID,
			s.ComputerCN AS ComputerCN,
			s.SoftwareID AS SoftwareID,
			SUM(s.Days) AS Days
		FROM (
			--List of usage information where usage days are s.
			SELECT d.ComputerID AS ComputerID,
				d.ComputerCN AS ComputerCN,
				d.SoftwareID AS SoftwareID,
				(
					CASE
					WHEN d.StartOfWeek < @l_fromDate
					THEN 0
					ELSE d.Days END
				) AS Days
			FROM (
				--Usage information for list of target users
				SELECT sUsage.ComputerID AS ComputerID,
					fc.ComputerCN AS ComputerCN,
					sUsage.SoftwareID AS SoftwareID,
					sUsage.Days AS Days,
					sUsage.StartOfWeek AS StartOfWeek
				FROM (
					--List of relevent computers
					SELECT c.ComputerID AS ComputerID,
						c.ComputerCN AS ComputerCN
					FROM Computer c, #Organization s 
					WHERE c.ComputerOUID = s.OUID
				) AS fc, SoftwareUsagePerWeek AS sUsage
				WHERE fc.ComputerID = sUsage.ComputerID
				  AND sUsage.SoftwareID = @svId
				  AND sUsage.StartOfWeek <= @l_tillDate
			) AS d
		) AS s
		GROUP BY ComputerID, ComputerCN, SoftwareID
	) AS uc
	WHERE uc.Days = 0
	  AND uc.ComputerCN LIKE @compCN
	UNION
	--List of computers with software installed but never used them
	SELECT 	i.SoftwareID AS SoftwareID,
		@l_softwareName AS SoftwareName,
		@l_version AS Version,
		i.ComputerID AS ComputerID,
		i.ComputerCN AS ComputerCN,
		0 AS Sessions,
		0 AS Weeks,
		0 AS RunTime,
		0 AS ActiveTime
	FROM (
	--List of computers with software installed, and the ids of
		--those software.
		SELECT DISTINCT o.ComputerID AS ComputerID,
			rc.ComputerCN AS ComputerCN,
			o.SoftwareID AS SoftwareID
		FROM (
			--List of relevent computers
			SELECT c.ComputerID AS ComputerID,
				c.ComputerCN AS ComputerCN
			FROM Computer c, #Organization s 
			WHERE c.ComputerOUID = s.OUID
		) AS rc, SoftwareOccurrence AS o
		WHERE rc.ComputerID = o.ComputerID
		  AND o.SoftwareID = @svId
	) AS i
	WHERE NOT EXISTS(
		SELECT ComputerID, SoftwareID
		FROM SoftwareUsagePerWeek AS s
		WHERE i.ComputerID = s.ComputerID
		  AND i.SoftwareID = s.SoftwareID
		)
  	  AND i.ComputerCN LIKE @compCN
END /*IF @usageCat = NEVER */
ELSE /*all other ranges*/
BEGIN

	--Setup the usage range.
	IF UPPER(@usageCat) = 'OCCASIONAL'
	BEGIN
		SET @l_lUsageRange = 0
		SET @l_uUsageRange = @l_period/4
	END
	ELSE IF UPPER(@usageCat) = 'FREQUENT'
	BEGIN
		SET @l_lUsageRange = @l_period/4
		SET @l_uUsageRange = @l_period/2
	END
	ELSE IF UPPER(@usageCat) = 'CONTINUAL'
	BEGIN
		SET @l_lUsageRange = @l_period/2

		--The upper range for Continual should really
		--be infinity, though in this context, 20000
		--days is just as good
		SET @l_uUsageRange = 20000
	END

	SELECT final.ComputerID AS ComputerID,
		final.SoftwareID AS SoftwareID,
		@l_softwareName AS SoftwareName,
		@l_version AS Version,
		final.ComputerCN AS ComputerCN,
		final.Sessions AS Sessions,
		final.Weeks AS Weeks,
		final.RunTime AS RunTime,
		final.ActiveTime AS ActiveTime
	FROM (
		--List of computers that have reported usage, regardless of whether
		--the the software was known to be installed
		SELECT DISTINCT uc.ComputerID AS ComputerID,
			uc.SoftwareID AS SoftwareID,
			uc.ComputerCN AS ComputerCN,
			(
				CASE WHEN uc.Days = 0 THEN 0
				ELSE uc.Sessions END
			) AS Sessions,
			(
				CASE WHEN uc.Days = 0 THEN 0
				ELSE uc.Weeks END
			)AS Weeks,
			(
				CASE WHEN uc.Days = 0 THEN 0
				ELSE uc.Duration END
			) AS RunTime,
			(
				CASE WHEN uc.Days = 0 THEN 0
				ELSE uc.ActiveTime END
			) AS ActiveTime,
			uc.Days AS Days
		FROM (
			--Everything summed
			SELECT w.ComputerID AS ComputerID
				,w.ComputerCN AS ComputerCN
				,w.SoftwareID AS SoftwareID
				,SUM(w.Duration) AS Duration
				,SUM(w.ActiveTime) AS ActiveTime
				,SUM(w.Days) AS Days
				,SUM(w.Sessions) AS Sessions
				,SUM(w.Weeks) AS Weeks
			FROM (
				--Preparing weeks for summing
				SELECT s.ComputerID AS ComputerID,
					s.ComputerCN AS ComputerCN,
					s.SoftwareID AS SoftwareID,
					s.Sessions AS Sessions,
					(
						CASE
						WHEN s.StartOfWeek < @l_fromDate
						THEN 0
						ELSE 1 END
					) AS Weeks,
					s.Duration AS Duration,
					s.ActiveTime AS ActiveTime,
					s.Days AS Days
				FROM (
					--List of usage information where usage days are set
					--to 0.
					SELECT d.ComputerID AS ComputerID,
						d.ComputerCN AS ComputerCN,
						d.SoftwareID AS SoftwareID,
						d.StartOfWeek AS StartOfWeek,
						(
							CASE
							WHEN d.StartOfWeek < @l_fromDate
							THEN 0
							ELSE SUM(d.Sessions) END
						) AS Sessions,
						(
							CASE
							WHEN d.StartOfWeek < @l_fromDate
							THEN 0
							ELSE SUM(d.Duration) END
						) AS Duration,
						(
							CASE
							WHEN d.StartOfWeek < @l_fromDate
							THEN 0
							ELSE SUM(d.ActiveTime) END
						) AS ActiveTime,
						(
							CASE
							WHEN d.StartOfWeek < @l_fromDate
							THEN 0
							ELSE SUM(d.Days) END
						) AS Days
					FROM (
						--Usage information for list of target users
						SELECT sUsage.ComputerID AS ComputerID,
							fc.ComputerCN AS ComputerCN,
							sUsage.SoftwareID AS SoftwareID,
							sUsage.Days AS Days,
							sUsage.StartOfWeek AS StartOfWeek,
							sUsage.Sessions AS Sessions,
							sUsage.Duration AS Duration,
							sUsage.ActiveTime AS ActiveTime
						FROM (
							--List of relevent computers
							SELECT c.ComputerID AS ComputerID,
								c.ComputerCN AS ComputerCN
							FROM Computer c, #Organization s 
							WHERE c.ComputerOUID = s.OUID
						) AS fc, SoftwareUsagePerWeek AS sUsage
						WHERE fc.ComputerID = sUsage.ComputerID
						  AND sUsage.SoftwareID = @svId
						  AND sUsage.StartOfWeek <= @l_tillDate
					) AS d
					GROUP BY ComputerID, ComputerCN, SoftwareID, StartOfWeek
				) AS s
			) AS w
			GROUP BY ComputerID, ComputerCN, SoftwareID
		) AS uc
		WHERE uc.ComputerCN LIKE @compCN
	) AS final
	WHERE final.Days > @l_lUsageRange 
	  AND final.Days <= @l_uUsageRange

END /*IF @usageCat = occasional, frequent, continual */

END /*Outer most if*/
END /*Create Procedure*/

GO
/*
 * DROP PROCEDURE AUSessionsOnComp
 * GO
 */

-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'AUSessionsOnComp' AND xtype = 'P'
)
	DROP PROCEDURE AUSessionsOnComp
GO

CREATE PROCEDURE AUSessionsOnComp
	@fromDate AS DATETIME=NULL,	--from and till must be at least 4 days apart!
	@tillDate AS DATETIME=NULL,	--
	@swName AS VARCHAR(256)='%',	--Filter. 128 * 2 for sqlchar encoding
	@compID AS INTEGER=NULL
AS 
BEGIN

IF(
	(@compID IS NOT NULL)
	AND (@swName IS NOT NULL)
	AND (@fromDate IS NOT NULL)
	AND (@tillDate IS NOT NULL)
	AND (DATEDIFF(Day, @fromDate, @tillDate) >= 0)
)
BEGIN

-- The StartOfWeek represents the start of the week in which usage has been reported 
-- and NOT the day the usage has been reported. 
-- Thus we need to do some processing to map the date ranges (from and till date) back
-- to the start of the week
DECLARE @l_fromDate AS DATETIME
DECLARE @l_tillDate AS DATETIME
SET @l_fromDate = dbo.GetStartOfWeekForDate(@fromDate)
SET @l_tillDate = dbo.GetStartOfWeekForDate(@tillDate)

--Local variables
DECLARE @l_compCN AS VARCHAR(64)
SELECT @l_compCN = c.ComputerCN
FROM Computer AS c
WHERE c.ComputerID = @compID

	--Summed sessions for a day. Each day now has only 1 session
	--value
	SELECT uc.SoftwareName AS SoftwareName, 
		uc.Version AS Version,
		uc.SoftwareID AS SoftwareID,
		uc.[Filename] AS [Filename],
		uc.FileVersion AS FileVersion,
		@l_compCN AS ComputerCN,
		@compID AS ComputerID,
		SUM(uc.Sessions) AS Sessions,
		COUNT(DISTINCT uc.StartOfWeek) as Weeks,
		SUM(uc.Duration) AS RunTime,
		SUM(uc.ActiveTime) AS ActiveTime
	FROM (
		SELECT su.ComputerID AS ComputerID, 
			sv.SoftwareName AS SoftwareName, 
			sv.SoftwareID AS SoftwareID,
			sv.Version AS Version,
			(
				CASE
					WHEN su.SoftwareFileUsageID IS NULL
					THEN ''
					ELSE
					(
						SELECT	sn.[Name]
						FROM SoftwareFileName sn, SoftwareFileUsage sf
						WHERE sf.SoftwareFileUsageID = su.SoftwareFileUsageID
							AND sf.ComputerID = @compID
							AND sf.SoftwareFileNameID = sn.SoftwareFileNameID
					)
				END
			) AS [Filename],
			(
				CASE
					WHEN su.SoftwareFileUsageID IS NULL
					THEN ''
					ELSE
					(
						SELECT sf.Version
						FROM SoftwareFileName sn, SoftwareFileUsage sf
						WHERE sf.SoftwareFileUsageID = su.SoftwareFileUsageID
							AND sf.ComputerID = @compID
							AND sf.SoftwareFileNameID = sn.SoftwareFileNameID
					)
				END
			) AS FileVersion,
			su.StartOfWeek AS StartOfWeek,
			SUM(su.Duration) AS Duration, 
			SUM(su.ActiveTime) AS ActiveTime,
			SUM(su.Sessions) AS Sessions,
			SUM(su.Days) AS Days
		FROM SoftwareUsagePerWeek su, SoftwareVersion sv
		WHERE	su.ComputerID = @compID
			AND su.SoftwareID = sv.SoftwareID
			AND su.StartOfWeek >= @l_fromDate
			AND su.StartOfWeek <= @l_tillDate
		GROUP BY su.ComputerID
			,su.StartOfWeek
			,su.SoftwareFileUsageID
			,sv.SoftwareName
			,sv.SoftwareID
			,sv.Version
	) AS uc
	WHERE uc.SoftwareName LIKE @swName
	GROUP BY uc.SoftwareName, 
		uc.Version,
		uc.SoftwareID,
		uc.[Filename],
		uc.FileVersion

END /*Outer most IF*/
END /*Create procedure*/

GO
/*
 * DROP PROCEDURE AUCountDaysG
 * GO
 */

-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'AUCountDaysG' AND xtype = 'P'
)
	DROP PROCEDURE AUCountDaysG
GO

CREATE PROCEDURE AUCountDaysG
	@fromDate AS DATETIME=NULL,		--from and till must be at least 4 days apart!
	@tillDate AS DATETIME=NULL,		--
	@svId AS INTEGER=NULL,			--Software id
	@thisCompOnly AS BIT=0,			--if 1, match only the compID, ouMatch and oudn is ignored.
						--if 0, match all comp in the ou. ouMatch is used. 
						--compID is ingored.
	@compID AS INTEGER=0,
	@oudn AS VARCHAR(800)=NULL, 		--DN of the SELECTed OU
	@ouMatch AS BIT=0			--0 if we traverse down to sub OUs, 1 otherwise
AS 
BEGIN

--start
IF(
	(@fromDate IS NOT NULL)
	AND (@tillDate IS NOT NULL)
	AND (@svId IS NOT NULL)
	AND (DATEDIFF(Day, @fromDate, @tillDate) >= 0)
)
BEGIN

-- The StartOfWeek represents the start of the week in which usage has been reported 
-- and NOT the day the usage has been reported. 
-- Thus we need to do some processing to map the date ranges (from and till date) back
-- to the start of the week
DECLARE @l_fromDate AS DATETIME
DECLARE @l_tillDate AS DATETIME
SET @l_fromDate = dbo.GetStartOfWeekForDate(@fromDate)
SET @l_tillDate = dbo.GetStartOfWeekForDate(@tillDate)

DECLARE @l_numSeg AS INTEGER
DECLARE @l_counter AS INTEGER
DECLARE @l_segmentSize AS INTEGER

SET @l_segmentSize = 7

CREATE TABLE #TSegments(
	StartOfWeek DATETIME DEFAULT(NULL), -- Date of the start of that week 
	TimesUsed INTEGER		--Number of days used in that segment
);

DECLARE @l_tempFromDate AS DATETIME
SET @l_tempFromDate = @l_fromDate

WHILE (@l_tempFromDate <= @l_tillDate)
BEGIN
	INSERT INTO #TSegments VALUES(
		@l_tempFromDate,
		0
	)
	SET @l_tempFromDate = DATEADD(Week,1,@l_tempFromDate)
END

CREATE TABLE #Organization(OUID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

UPDATE #TSegments
	SET #TSegments.TimesUsed = s.TimesUsed + final.Days
	FROM (
		SELECT su.SoftwareID AS SoftwareID,
			su.StartOfWeek AS StartOfWeek,
			SUM(su.Days) AS Days
		FROM (
			SELECT u.ComputerID AS ComputerID,
				u.SoftwareID AS SoftwareID,
				u.Days AS Days,
				--We want this date so we can use the dates as names
				--and they match!
				s.StartOfWeek AS StartOfWeek
			FROM (
				--List of usage data for the list of computers, and 
				--are in the interested date range.
				SELECT DISTINCT
					sUsage.SoftwareID AS SoftwareID,
					sUsage.ComputerID AS ComputerID,
					sUsage.Days AS Days,
					sUsage.StartOfWeek AS StartOfWeek
				FROM (
					--List of relevent computers
					SELECT c.ComputerID AS ComputerID
					FROM Computer c, #Organization s 
					WHERE c.ComputerOUID = s.OUID
					  AND @thisCompOnly = 0
					UNION 
						SELECT @compID WHERE @thisCompOnly = 1
				) AS fc, 
					SoftwareUsagePerWeek AS sUsage
				WHERE fc.ComputerID = sUsage.ComputerID
				  AND @svId = sUsage.SoftwareID 
				  AND sUsage.StartOfWeek <= @l_tillDate
				  AND sUsage.StartOfWeek >= @l_fromDate
			) AS u, #TSegments AS s
			WHERE u.StartOfWeek = s.StartOfWeek
		) AS su
		GROUP BY su.StartOfWeek,
			su.SoftwareID
	) AS final, #TSegments AS s
	WHERE final.StartOfWeek = s.StartOfWeek


SELECT StartOfWeek AS StartOfWeek, TimesUsed as TimesUsed
FROM #TSegments

END /*Outer most if*/
END /*Create Procedure*/

GO
/*
 * DROP PROCEDURE AUCountMdG
 * GO
 */

-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'AUCountMdG' AND xtype = 'P'
)
	DROP PROCEDURE AUCountMdG
GO

CREATE PROCEDURE AUCountMdG
	@fromDate AS DATETIME=NULL,		--from and till must be at least 4 days apart!
	@tillDate AS DATETIME=NULL,		--
	@svId AS INTEGER=NULL,			--Software id
	@oudn AS VARCHAR(800)=NULL, 		--DN of the SELECTed OU
	@ouMatch AS BIT=0			--0 if we traverse down to sub OUs, 1 otherwise
AS 
BEGIN

--start
IF(
	(@fromDate IS NOT NULL)
	AND (@tillDate IS NOT NULL)
	AND (@svId IS NOT NULL)
	AND (DATEDIFF(Day, @fromDate, @tillDate) >= 0)
)
BEGIN

-- The StartOfWeek represents the start of the week in which usage has been reported 
-- and NOT the day the usage has been reported. 
-- Thus we need to do some processing to map the date ranges (from and till date) back
-- to the start of the week
DECLARE @l_fromDate AS DATETIME
DECLARE @l_tillDate AS DATETIME
SET @l_fromDate = dbo.GetStartOfWeekForDate(@fromDate)
SET @l_tillDate = dbo.GetStartOfWeekForDate(@tillDate)

DECLARE @l_numSeg AS INTEGER
DECLARE @l_counter AS INTEGER
DECLARE @l_segmentSize AS INTEGER

SET @l_segmentSize = 7

CREATE TABLE #TSegments(
	StartOfWeek DATETIME DEFAULT(NULL), -- Date of the start of that week 
	MDCount INTEGER		--Number of days used in that segment
);

DECLARE @l_tempFromDate AS DATETIME
SET @l_tempFromDate = @l_fromDate

WHILE (@l_tempFromDate <= @l_tillDate)
BEGIN
	INSERT INTO #TSegments VALUES(
		@l_tempFromDate,
		0
	)
	SET @l_tempFromDate = DATEADD(Week,1,@l_tempFromDate)
END

CREATE TABLE #Organization(OUID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

UPDATE #TSegments
	SET #TSegments.MDCount = s.MDCount + final.MDCount
	FROM (
		SELECT su.SoftwareID AS SoftwareID,
			su.StartOfWeek AS StartOfWeek,
			COUNT(su.ComputerID) AS MDCount
		FROM (
			SELECT u.ComputerID AS ComputerID,
				u.SoftwareID AS SoftwareID,
				--We want this date so we can use the dates as names
				--and they match!
				s.StartOfWeek AS StartOfWeek
			FROM (
				--List of usage data for the list of computers, and 
				--are in the interested date range.
				SELECT DISTINCT
					sUsage.SoftwareID AS SoftwareID,
					sUsage.ComputerID AS ComputerID,
					sUsage.Days AS Days,
					sUsage.StartOfWeek AS StartOfWeek
				FROM (
					--List of relevent computers
					SELECT c.ComputerID AS ComputerID
					FROM Computer c, #Organization s 
					WHERE c.ComputerOUID = s.OUID
				) AS fc, 
					SoftwareUsagePerWeek AS sUsage
				WHERE fc.ComputerID = sUsage.ComputerID
				  AND @svId = sUsage.SoftwareID 
				  AND sUsage.StartOfWeek <= @l_tillDate
				  AND sUsage.StartOfWeek >= @l_fromDate
			) AS u, #TSegments AS s
			WHERE u.StartOfWeek = s.StartOfWeek
		) AS su
		GROUP BY su.StartOfWeek,
			su.SoftwareID
	) AS final, #TSegments AS s
	WHERE final.StartOfWeek = s.StartOfWeek


SELECT StartOfWeek AS StartOfWeek, MDCount as MDCount
FROM #TSegments

END /*Outer most if*/
END /*Create Procedure*/

GO
/*
 * DROP PROCEDURE CompUsage
 * GO
 */

-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'CompUsage' AND xtype = 'P'
)
	DROP PROCEDURE CompUsage
GO

CREATE PROCEDURE CompUsage
	@compCN AS VARCHAR(64)='%',
	@oudn AS VARCHAR(800)=NULL, 	--DN of the selected OU
	@ouMatch AS BIT=0		--0 if we traverse down to sub OUs, 1 otherwise
AS 
BEGIN

CREATE TABLE #Organization(OUID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

SELECT cl.ComputerID AS ComputerID,
	cl.ComputerCN AS ComputerCN,
	MAX(cu.LastReported) AS LastReported
FROM (
	--List of relevent computers
	SELECT c.ComputerID AS ComputerID,
		c.ComputerCN AS ComputerCN
	FROM Computer c, #Organization s 
	WHERE c.ComputerOUID = s.OUID
	  AND c.ComputerCN LIKE @compCN
) AS cl,
	ComputerUsage AS cu
WHERE cu.ComputerID = cl.ComputerID
GROUP BY cl.ComputerID, cl.ComputerCN


END /*Create procedure*/
GO

/*
 * DROP PROCEDURE AUSessions
 * GO
 */

-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'AUSessions' AND xtype = 'P'
)
	DROP PROCEDURE AUSessions
GO

CREATE PROCEDURE AUSessions
	@fromDate AS DATETIME=NULL,	
	@tillDate AS DATETIME=NULL,	
	@compID AS INTEGER=NULL,
	@svId AS INTEGER=NULL,			--The software id
	@userCN AS VARCHAR(64)='%',
	@fileName AS NVARCHAR(128)='%',
	@fileVersion AS NVARCHAR(128)='%'
AS 
BEGIN

IF(
	(@compID IS NOT NULL)
	AND(@svId IS NOT NULL)
	AND (@fromDate IS NOT NULL)
	AND (@tillDate IS NOT NULL)
	AND (DATEDIFF(Day, @fromDate, @tillDate) >= 0)
)
BEGIN

-- The StartOfWeek represents the start of the week in which usage has been reported 
-- and NOT the day the usage has been reported. 
-- Thus we need to do some processing to map the date ranges (from and till date) back
-- to the start of the week
DECLARE @l_fromDate AS DATETIME
DECLARE @l_tillDate AS DATETIME
SET @l_fromDate = dbo.GetStartOfWeekForDate(@fromDate)
SET @l_tillDate = dbo.GetStartOfWeekForDate(@tillDate)

SELECT u.UserCN AS UserCN,
	su.StartOfWeek AS StartOfWeek,
	su.Sessions AS Sessions,
	su.Days AS Days,
	su.Duration AS RunTime, 
	su.ActiveTime AS ActiveTime,
	sn.Name AS FileName,
	sf.Version AS FileVersion
FROM SoftwareUsagePerWeek AS su,
	SoftwareFileUsage AS sf,
	SoftwareFileName AS sn,
	[User] AS u
WHERE u.UserID = su.UserID
	AND su.ComputerID = @compID 
	AND u.UserCN LIKE @userCN
	AND su.SoftwareID = @svId
	AND su.StartOfWeek >= @l_fromDate
	AND su.StartOfWeek <= @l_tillDate
	AND su.SoftwareFileUsageID = sf.SoftwareFileUsageID
	AND sf.ComputerID = @compID
	AND sf.Version LIKE @fileVersion
	AND sf.SoftwareFileNameID = sn.SoftwareFileNameID
	AND sn.Name LIKE @fileName

END /*Outer most IF*/
END /*Create procedure*/
GO


-- USE ManageSoft
GO

PRINT 'Creating WakeOnLANTasks procedure:'

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'WakeOnLANTasks' AND xtype = 'P'
)
	DROP PROCEDURE WakeOnLANTasks
GO

CREATE PROCEDURE [WakeOnLANTasks]
	@friendlyName AS VARCHAR(400) = '%',
	@oudn AS VARCHAR(800)=NULL,	--DN of the selected OU
	@ouMatch AS BIT=0		--0 if we traverse down to sub OUs, 1 otherwise
AS
BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0
	
	SELECT	Task.TaskUID,
		Task.FriendlyName AS [Task Name], 
		CASE
			WHEN Task.StartTime IS NULL THEN 'As soon as possible'
			ELSE CONVERT(VARCHAR, Task.StartTime,126)
		END AS [Start Time], 
		COUNT(fc.ComputerCN) AS Targets
	FROM	WakeOnLANTask AS Task,
		WakeOnLANDistributionJob AS Job, 
		WakeOnLANStatus AS Status,
		(	
			--List of relevent computers
			SELECT c.ComputerID AS ComputerID,
				c.ComputerCN AS ComputerCN
			FROM Computer c, #Organization s 
			WHERE c.ComputerOUID = s.OUID 
		) AS fc
	WHERE	Task.TaskUID = Job.TaskUID
		AND Job.DistJobUID = Status.DistJobUID
		AND Status.ComputerID = fc.ComputerID
		AND Task.FriendlyName LIKE @friendlyName
	GROUP BY
		Task.TaskUID, Task.FriendlyName, Task.StartTime
	ORDER BY
	        Task.FriendlyName, Task.StartTime
END
GO

PRINT 'Creating WakeOnLANTaskDetails procedure:'

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'WakeOnLANTaskDetails' AND xtype = 'P'
)
	DROP PROCEDURE WakeOnLANTaskDetails
GO

CREATE PROCEDURE [WakeOnLANTaskDetails]
	@taskId BINARY(16),
	@computerCN VARCHAR(64) = '%',
	@oudn AS VARCHAR(800)=NULL,	--DN of the selected OU
	@ouMatch AS BIT=0		--0 if we traverse down to sub OUs, 1 otherwise
AS
BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

	SELECT	fc.ComputerCN AS [Target Name], 
		Status.State AS [Status], 
		DistServer.ServerName AS [DS Name], 
		Job.State AS [Job Status] 
	FROM	WakeOnLANDistributionJob AS Job, 
		WakeOnLANStatus AS Status,
		(
			--List of relevent computers
			SELECT c.ComputerID AS ComputerID,
				c.ComputerCN AS ComputerCN
			FROM Computer c, #Organization s 
			WHERE c.ComputerOUID = s.OUID 
				AND c.ComputerCN LIKE @computerCN
		) AS fc,
		DistributionServer AS DistServer
	WHERE	Job.TaskUID = @taskId 
		AND Job.DistJobUID = Status.DistJobUID
		AND Job.ServerUID = DistServer.ServerUID
		AND Status.ComputerID = fc.ComputerID
	ORDER BY
		Job.ServerUID
END
GO

PRINT 'Creating WakeOnLANTaskDetailsGraph procedure:'

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'WakeOnLANTaskDetailsGraph' AND xtype = 'P'
)
	DROP PROCEDURE WakeOnLANTaskDetailsGraph
GO

CREATE PROCEDURE [WakeOnLANTaskDetailsGraph]
	@taskId BINARY(16)
AS
BEGIN
	SELECT	DISTINCT Status.State AS [Category],
		COUNT(Status.State) AS [Quantity]
	FROM	WakeOnLANStatus AS Status,
		WakeOnLANDistributionJob AS Job
	WHERE	Status.DistJobUID = Job.DistJobUID AND
		Job.TaskUID = @taskId
	GROUP BY
		Status.State
END
GO

PRINT 'Creating WakeOnLANEffectivePolicy procedure:'

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'WakeOnLANEffectivePolicy' AND xtype = 'P'
)
	DROP PROCEDURE WakeOnLANEffectivePolicy
GO

CREATE PROCEDURE [WakeOnLANEffectivePolicy]
AS
BEGIN
	-- Local time can be a maximum of 12 hours ahead of UTC
	-- we only have to look at records that have an 
	-- effective date of local time minus 12 hours
	SELECT	c.ComputerCN,
		'CN=' + c.ComputerCN + ',' + ISNULL(o.RDN, '<unknown>') + ',' + ISNULL(d.DN, ''),
		pa.PolicyGUID,
		l.DisplayName,
		ad.EffectiveFrom,
		CAST(ad.EffectiveFromIsLocal AS tinyint) AS EffectiveFromIsLocal
	FROM	Computer AS c,
		Organization as o,
		Domain as d,
		TargetType AS t,
		PackageApplies AS pa,
		AllocationDetails AS ad,
		Policy AS l
	WHERE	(
			(c.ComputerID = pa.TargetID AND pa.TargetTypeID = 1)
			OR (pa.TargetTypeID = 3 AND c.ComputerID IN (
				SELECT	m.TargetID
				FROM	Member as m
				WHERE	m.GroupID = pa.TargetID
				  AND	m.TargetTypeID = 1
				)
			)
		)
	  AND	c.ComputerOUID = o.OrganizationID
	  AND	o.DomainID = d.OrganizationID
	  AND	t.TargetTypeName = 'Computer'
	  AND	t.TargetTypeID = pa.TargetTypeID
	  AND	pa.AllocationDetailsID = ad.AllocationDetailsID
	  AND	ad.Action = 'install'
	  AND	ad.Wake = 1
	  AND	ad.EffectiveFrom IS NOT NULL
	  AND	ad.EffectiveFrom > DATEADD(hh, -12, GETDATE())
	  AND	pa.PolicyGUID = l.GUID
	GROUP BY
		ad.EffectiveFrom,
		CAST(ad.EffectiveFromIsLocal AS tinyint),
		pa.PolicyGUID,
		c.ComputerCN,
		o.RDN,
		d.DN,
		l.DisplayName
END
GO

/*
 * $Header$
 *
 * DESCRIPTION: Stored Procedure: ListDomains
 *	Input:
 *
 *	Returns:
 *	- OrganizationID, DN, DNReverse, DomainType, FlatName, 
 *		PreferredDomainController, PreferredDomainControllerOnly
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'ListDomains' AND xtype = 'P'
)
        DROP PROCEDURE ListDomains
GO

CREATE PROCEDURE [ListDomains]
AS
	SELECT	OrganizationID,
			DN, 
			DNReverse,
			DomainType,
			FlatName,
			PreferredDomainController,
			PreferredDomainControllerOnly
	FROM	Domain
	WHERE	DN IS NOT NULL
	ORDER BY DN
GO
/* 
 * $Id: CreateNpl.sql 96041 2010-03-29 02:39:12Z tma $
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2010 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

PRINT 'Creating procedure to retrieve information required in policy distribution for full RSOP Mapping'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'PolicyDistributeFullRSOPMapping'
)
	DROP PROCEDURE PolicyDistributeFullRSOPMapping
GO
CREATE PROCEDURE PolicyDistributeFullRSOPMapping
	@guids binary(16),
	@OUpattern nvarchar(400),
	@DomainDN nvarchar(100)
AS
	IF @DomainDN IS NULL
	BEGIN
		SET @DomainDN = '%'
	END

IF OBJECT_ID('tempdb..#TEMP_COMPUTERDIRECTORY') IS NOT NULL
	DROP TABLE #TEMP_COMPUTERDIRECTORY

	CREATE TABLE #TEMP_COMPUTERDIRECTORY(
			ComputerID  int,
			ComputerCN 	nvarchar(128) COLLATE database_default,
			RDN	   	nvarchar(800) COLLATE database_default,
			DN		nvarchar(200) COLLATE database_default,
			TargetTypeName	nvarchar(8) COLLATE database_default,
			PrincipalDN 	nvarchar(1133) COLLATE database_default
		);

	INSERT 
	INTO
		#TEMP_COMPUTERDIRECTORY
	(
	   ComputerID,
	   ComputerCN,  
	   RDN,  
	   DN,  
	   TargetTypeName,  
	   PrincipalDN  
	)
	SELECT
	t.ComputerID,  
	   t.ComputerCN,  
	   o.RDN,  
	   d.DN,  
	   'Computer' as TargetTypeName,  
	   'CN=' + t.ComputerCN + ',' + o.RDN + ',' + d.DN AS PrincipalDN  
	  FROM [Computer] AS t,  
	   Organization AS o,  
	   Domain AS d  
	  WHERE t.ComputerOUID = o.OrganizationID  
		AND o.DomainID = d.OrganizationID  
		AND (@OUpattern IS NULL OR o.RDN LIKE @OUpattern)  
		AND (d.dn LIKE @DomainDN)  
		AND (d.DomainType = 'AD')  
		AND t.GUID IS NOT NULL  
		AND t.ComputerID NOT IN  
	   (  
		SELECT TargetID  
		 FROM Member AS m JOIN dbo.[Group] AS g ON g.GroupID = m.GroupID AND g.GroupCN = '+RSoP'  
		 WHERE m.TargetTypeID = 1 -- Computers  
		  )  


	CREATE CLUSTERED INDEX IX_TEMP_CMPDIRECTORY 
		ON #TEMP_COMPUTERDIRECTORY(ComputerID)

	IF OBJECT_ID('tempdb..#TEMP_COMPUTERPACKAGEALLOCATIONS') IS NOT NULL
		DROP TABLE #TEMP_COMPUTERPACKAGEALLOCATIONS

	CREATE TABLE #TEMP_COMPUTERPACKAGEALLOCATIONS(
		TargetID int,  
		PolicyGUID binary(16),  
		PolicyVersion int,  
		PolicyPrecedence int,  
		[Action] varchar(16) COLLATE database_default,  
		EffectiveFromIsLocal bit,  
		Exclusive bit,  
		EffectiveFrom datetime,  
		EffectiveUntil datetime,  
		PostponeNoLaterThan datetime,  
		PostponeNoLaterThanIsLocal bit,  
		PostponePeriod int,  
		PostponeLatest bit,  
		PostponeOKForLowBandwidth bit,  
		PostponeOKForAnyReason bit,  
		Removable bit,  
		DisplayName nvarchar(1024) COLLATE database_default,  
		TargetTypeName nvarchar(512) COLLATE database_default,  
		PackageFullName nvarchar(512) COLLATE database_default,  
		NetPrecedence int
	);

	INSERT 
	INTO
		#TEMP_COMPUTERPACKAGEALLOCATIONS 
	SELECT pap.TargetID,  
	   pap.PolicyGUID,  
	   pap.PolicyVersion,  
	   pal.Precedence AS PolicyPrecedence,  
	   ad.[Action],  
	   ad.EffectiveFromIsLocal,  
	   ad.Exclusive,  
	   ad.EffectiveFrom,  
	   ad.EffectiveUntil,  
	   ad.PostponeNoLaterThan,  
	   ad.PostponeNoLaterThanIsLocal,  
	   ad.PostponePeriod,  
	   ad.PostponeLatest,  
	   ad.PostponeOKForLowBandwidth,  
	   ad.PostponeOKForAnyReason,  
	   ad.Removable,  
	   p.DisplayName,  
	   tt.TargetTypeName,  
	   pp.PackageFullName,  
	   pap.Precedence AS NetPrecedence 

	  FROM PackageApplies AS pap,  
	   PackageAllocation AS pal,  
	   AllocationDetails AS ad,  
	   Policy AS p,  
	   TargetType AS tt,  
	   PackagePath AS pp  
	  WHERE pap.TargetTypeID = 1  
		AND pap.PolicyGUID = pal.PolicyGUID  
		AND pap.PackagePathID = pal.PackagePathID  
		AND pap.TargetTypeID = pal.TargetTypeID  
		AND pap.AllocationDetailsID = pal.AllocationDetailsID  
		AND   pap.AllocationDetailsID = ad.AllocationDetailsID  
		AND pap.PolicyGUID = p.GUID  
		AND pap.TargetTypeID  = tt.TargetTypeID  
		AND pap.PackagePathID = pp.PackagePathID  
		AND (@guids IS NULL OR p.GUID IN (@guids))  
		AND (ad.EffectiveUntil = 0  
	   OR ad.EffectiveUntil IS NULL  
	   OR ad.EffectiveUntil > DATEADD(Day, -2, GETDATE()))


	CREATE CLUSTERED INDEX IX_TEMP_COMPUTERPACKAGEALLOCATIONS
		ON #TEMP_COMPUTERPACKAGEALLOCATIONS(TargetID)

IF OBJECT_ID('tempdb..#TEMP_USERDIRECTORY') IS NOT NULL
	DROP TABLE #TEMP_USERDIRECTORY

	CREATE TABLE #TEMP_USERDIRECTORY(
			UserID  int,
			SAMAccountName 	nvarchar(40) COLLATE database_default,
			RDN	   	nvarchar(800) COLLATE database_default,
			DN		nvarchar(200) COLLATE database_default,
			TargetTypeName	nvarchar(8) COLLATE database_default,
			PrincipalDN 	nvarchar(1133) COLLATE database_default
		);

	INSERT 
	INTO
		#TEMP_USERDIRECTORY
	(
	   UserID,
	   SAMAccountName,  
	   RDN,  
	   DN,  
	   TargetTypeName,  
	   PrincipalDN  
	)
	SELECT	t.UserID,
			t.SAMAccountName,
			o.RDN,
			d.DN,
			'User' AS TargetTypeName,
			'CN=' + t.UserCN +','+ o.RDN + ',' + d.DN AS PrincipalDN
	FROM	[User] AS t,
		Organization AS o,
		Domain AS d
	WHERE	t.UserOUID = o.OrganizationID
	  AND	o.DomainID = d.OrganizationID
	  AND	(@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
	  AND	(d.dn LIKE @DomainDN)
	  AND	(d.DomainType = 'AD')
	  AND	t.UserID <> 1
	  AND	t.GUID IS NOT NULL
	  AND	t.UserID NOT IN
		(
			SELECT	TargetID
		 	FROM	Member AS m JOIN dbo.[Group] AS g ON g.GroupID = m.GroupID AND GroupCN = '+RSoP'
		 	WHERE	m.TargetTypeID = 2	-- Users
		) 


	CREATE CLUSTERED INDEX IX_TEMP_USRDIRECTORY 
		ON #TEMP_USERDIRECTORY(UserID)

	IF OBJECT_ID('tempdb..#TEMP_USERPACKAGEALLOCATIONS') IS NOT NULL
		DROP TABLE #TEMP_USERPACKAGEALLOCATIONS

	CREATE TABLE #TEMP_USERPACKAGEALLOCATIONS(
		TargetID int,  
		PolicyGUID binary(16),  
		PolicyVersion int,  
		PolicyPrecedence int,  
		[Action] varchar(16) COLLATE database_default,  
		EffectiveFromIsLocal bit,  
		Exclusive bit,  
		EffectiveFrom datetime,  
		EffectiveUntil datetime,  
		PostponeNoLaterThan datetime,  
		PostponeNoLaterThanIsLocal bit,  
		PostponePeriod int,  
		PostponeLatest bit,  
		PostponeOKForLowBandwidth bit,  
		PostponeOKForAnyReason bit,  
		Removable bit,  
		DisplayName nvarchar(1024) COLLATE database_default,  
		TargetTypeName nvarchar(512) COLLATE database_default,  
		PackageFullName nvarchar(512) COLLATE database_default,  
		NetPrecedence int
	);

	INSERT 
	INTO
		#TEMP_USERPACKAGEALLOCATIONS 
	SELECT	pap.TargetID,
			pap.PolicyGUID,
			pap.PolicyVersion,
			pal.Precedence AS PolicyPrecedence,
			ad.[Action],
			ad.EffectiveFromIsLocal,
			ad.Exclusive,
			ad.EffectiveFrom,
			ad.EffectiveUntil,
			ad.PostponeNoLaterThan,
			ad.PostponeNoLaterThanIsLocal,
			ad.PostponePeriod,
			ad.PostponeLatest,
			ad.PostponeOKForLowBandwidth,
			ad.PostponeOKForAnyReason,
			ad.Removable,
			p.DisplayName,
			tt.TargetTypeName,
			pp.PackageFullName,
			pap.Precedence AS NetPrecedence
	FROM	PackageApplies AS pap,
		PackageAllocation AS pal,
		AllocationDetails AS ad,
		Policy AS p,
		TargetType AS tt,
		PackagePath AS pp
	WHERE	pap.TargetTypeID = 2
	  AND	pap.PolicyGUID = pal.PolicyGUID
	  AND	pap.PackagePathID = pal.PackagePathID
	  AND	pap.TargetTypeID = pal.TargetTypeID
	  AND	pap.AllocationDetailsID = pal.AllocationDetailsID
	  AND   pap.AllocationDetailsID = ad.AllocationDetailsID
	  AND	pap.PolicyGUID = p.GUID
	  AND	pap.TargetTypeID  = tt.TargetTypeID
	  AND	pap.PackagePathID = pp.PackagePathID
	  AND	(@guids IS NULL OR p.GUID IN (@guids))
	  AND	(ad.EffectiveUntil = 0
		OR ad.EffectiveUntil IS NULL
		OR ad.EffectiveUntil > DATEADD(Day, -2, GETDATE()))


	CREATE CLUSTERED INDEX IX_TEMP_USRPACKAGEALLOCATIONS
		ON #TEMP_USERPACKAGEALLOCATIONS(TargetID) 
  

	-- Users Package Applies
	SELECT
		u.SAMAccountName AS PrincipalName,
		pn.DisplayName AS PolicyName, 
		pn.PolicyGUID,
		pn.PolicyVersion,
		pn.[Action],
		pn.PackageFullName,
		u.RDN,
		pn.PolicyPrecedence AS Precedence,
		u.TargetTypeName,
		u.DN,
		ISNULL(pn.EffectiveFromIsLocal,0),
		ISNULL(pn.Exclusive,0),
		pn.EffectiveFrom,
		pn.EffectiveUntil,
		u.PrincipalDN,
		pn.PostponeNoLaterThan,
		pn.PostponeNoLaterThanIsLocal,
		pn.PostponePeriod,
		pn.PostponeLatest,
		pn.PostponeOKForLowBandwidth,
		pn.PostponeOKForAnyReason,
		ISNULL(pn.Removable,0),
		pn.NetPrecedence,
		cast(NULL AS binary(16)) AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM #TEMP_USERDIRECTORY u  
	  LEFT OUTER JOIN #TEMP_USERPACKAGEALLOCATIONS pn ON pn.TargetID = u.UserID 
	
	UNION ALL
	
	-- Computers Package Applies
	SELECT   
	  u.ComputerCN AS PrincipalName,  
	  pn.DisplayName AS PolicyName,   
	  pn.PolicyGUID,  
	  pn.PolicyVersion,  
	  pn.[Action],  
	  pn.PackageFullName,  
	  u.RDN,  
	  pn.PolicyPrecedence AS Precedence,  
	  u.TargetTypeName,  
	  u.DN,  
	  ISNULL(pn.EffectiveFromIsLocal,0),  
	  ISNULL(pn.Exclusive,0),  
	  pn.EffectiveFrom,  
	  pn.EffectiveUntil,  
	  u.PrincipalDN,  
	  pn.PostponeNoLaterThan,  
	  pn.PostponeNoLaterThanIsLocal,  
	  pn.PostponePeriod,  
	  pn.PostponeLatest,  
	  pn.PostponeOKForLowBandwidth,  
	  pn.PostponeOKForAnyReason,  
	  ISNULL(pn.Removable,0),  
	  pn.NetPrecedence,  
	  cast(NULL AS binary(16)) AS RSOPGUID,  
	  CAST(0 as bit) AS EmptyRSOP  
	FROM #TEMP_COMPUTERDIRECTORY AS u  
	  LEFT OUTER JOIN #TEMP_COMPUTERPACKAGEALLOCATIONS pn ON pn.TargetID = u.ComputerID 

	UNION ALL

	-- Users RSOP Mapping
	SELECT
		u.SAMAccountName AS PrincipalName,
		u.SAMAccountName  AS PolicyName, 
		cast(null AS binary(16)) AS PolicyGUID,
		cast(0 AS int) AS PolicyVersion,
		cast(null AS varchar) AS [Action],
		cast(null AS varchar) AS PackageFullName,
		u.RDN,
		cast(null AS int) AS Precedence,
		u.TargetTypeName,
		u.DN,
		cast(0 AS bit),
		cast(0 AS bit),
		cast(null AS datetime) AS EffectiveFrom,
		cast(null AS datetime) AS EffectiveUntil,
		u.PrincipalDN,
		cast(null AS datetime) AS PostponeNoLaterThan,
		cast(null AS bit) AS PostponeNoLaterThanIsLocal,
		cast(null AS int) AS PostponePeriod,
		cast(null AS bit) AS PostponeLatest,
		cast(null AS bit) AS PostponeOKForLowBandwidth,
		cast(null AS bit) AS PostponeOKForAnyReason,
		cast(null AS bit) AS Removable,
		cast(null AS int) AS NetPrecedence,
		g.GUID AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM	dbo.Member AS m JOIN dbo.[Group] AS g ON g.GroupID = m.GroupID AND g.GroupCN = '+RSoP',
		(
			SELECT	t.UserID,
				t.SAMAccountName,
				o.RDN,
				d.DN,
				'User' as TargetTypeName,
				'CN=' + t.UserCN +','+ o.RDN + ',' + d.DN AS PrincipalDN
			FROM	[User] AS t,
				Organization AS o,
				Domain AS d
			WHERE	t.UserOUID = o.OrganizationID
			    AND o.DomainID = d.OrganizationID
			    AND (@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
			    AND (d.dn LIKE @DomainDN)
			    AND	(d.DomainType = 'AD')
			    AND t.UserID <> 1
			    AND t.GUID IS NOT NULL
		) AS u
	WHERE	m.TargetTypeID = 2	-- Users
	  AND	m.TargetID = u.UserID
	
	UNION ALL
	
	-- Computers RSOP Mapping
	SELECT 
		u.ComputerCN AS PrincipalName,
		u.ComputerCN  AS PolicyName, 
		cast(null AS binary(16)) AS PolicyGUID,
		cast(0 AS int) AS PolicyVersion,
		cast(null AS varchar) AS [Action],
		cast(null AS varchar) AS PackageFullName,
		u.RDN,
		cast(null AS int) AS Precedence,
		u.TargetTypeName,
		u.DN,
		cast(0 AS bit),
		cast(0 AS bit),
		cast(null AS datetime) AS EffectiveFrom,
		cast(null AS datetime) AS EffectiveUntil,
		u.PrincipalDN,
		cast(null AS datetime) AS PostponeNoLaterThan,
		cast(null AS bit) AS PostponeNoLaterThanIsLocal,
		cast(null AS int) AS PostponePeriod,
		cast(null AS bit) AS PostponeLatest,
		cast(null AS bit) AS PostponeOKForLowBandwidth,
		cast(null AS bit) AS PostponeOKForAnyReason,
		cast(null AS bit) AS Removable,
		cast(null AS int) AS NetPrecedence,
		g.GUID AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM	dbo.Member AS m JOIN dbo.[Group] AS g ON g.GroupID = m.GroupID AND g.GroupCN = '+RSoP',
		(
			SELECT	t.ComputerID,
				t.ComputerCN,
				o.RDN,
				d.DN,
				'Computer' AS TargetTypeName,
				'CN=' + t.ComputerCN + ',' + o.RDN + ',' + d.DN AS PrincipalDN
			FROM	[Computer] AS t,
				Organization AS o,
				Domain AS d
			WHERE	t.ComputerOUID = o.OrganizationID
			    AND o.DomainID = d.OrganizationID
			    AND (@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
			    AND (d.dn LIKE @DomainDN)
			    AND	(d.DomainType = 'AD')
			    AND t.GUID IS NOT NULL
		) AS u
	WHERE	m.TargetTypeID = 1	-- Computers
	  AND	m.TargetID = u.ComputerID
	
	UNION ALL

	-- MGS Policy
	SELECT  DISTINCT
		p.DisplayName as PrincipalName,
		p.DisplayName as PolicyName,
		p.GUID as PolicyGUID,
		0 as PolicyVersion,
		ad.[Action],
		pp.PackageFullName,
		'' as RDN,	
		pa.Precedence,
		CASE WHEN pa.TargetTypeID = 1 THEN 'Computer' ELSE 'User' END AS TargetTypeName,
		d.DN,
		ISNULL(ad.EffectiveFromIsLocal,0),
		ISNULL(ad.Exclusive,0),
		ad.EffectiveFrom,
		ad.EffectiveUntil,
		d.DN as PrincipleDN,
		ad.PostponeNoLaterThan,
		ad.PostponeNoLaterThanIsLocal,
		ad.PostponePeriod,
		ad.PostponeLatest,
		ad.PostponeOKForLowBandwidth,
		ad.PostponeOKForAnyReason,
		ad.Removable,
		pa.Precedence as NetPrecedence,
		CAST(NULL AS binary(16)) AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM Policy as p
	JOIN PackageAllocation as pa
		ON pa.PolicyGUID = p.GUID
	JOIN Domain as d
		ON p.DomainID = d.OrganizationID
	JOIN PackagePath as pp
		ON pp.PackagePathID = pa.PackagePathID
	JOIN AllocationDetails as ad
		ON ad.AllocationDetailsID = pa.AllocationDetailsID
	WHERE d.DomainType = 'MGS'
		AND (d.DN LIKE @DomainDN)
		AND (@guids IS NULL OR p.GUID IN (@guids))

	ORDER BY
		u.DN,
		u.RDN,
		u.TargetTypeName,
		PrincipalName,
		pn.NetPrecedence
GO

PRINT 'Creating procedure to retrieve information required in policy distribution for partial RSOP Mapping'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'PolicyDistributePartialRSOPMapping'
)
	DROP PROCEDURE PolicyDistributePartialRSOPMapping
GO
CREATE PROCEDURE PolicyDistributePartialRSOPMapping
	@guids binary(16),
	@OUpattern nvarchar(400),
	@DomainDN nvarchar(100)
AS
	IF @DomainDN IS NULL
	BEGIN
		SET @DomainDN = '%'
	END
		
	CREATE TABLE #RSOPWithPolicySetting
	(
		GroupID int
	)
	
	INSERT INTO #RSOPWithPolicySetting
	SELECT	DISTINCT TargetID
	FROM 	dbo.PackageApplies AS pa
			JOIN dbo.AllocationDetails AS ad ON ad.AllocationDetailsID = pa.AllocationDetailsID
	WHERE	TargetTypeID = 3 -- RSOP
		AND (
			(ad.EffectiveFrom IS NOT NULL)
			OR (ISNULL(ad.Wake, 0) = 1)
		)
	
	-- Users Package Applies
	SELECT
		u.SAMAccountName AS PrincipalName,
		pn.DisplayName AS PolicyName, 
		pn.PolicyGUID,
		pn.PolicyVersion,
		pn.[Action],
		pn.PackageFullName,
		u.RDN,
		pn.PolicyPrecedence AS Precedence,
		u.TargetTypeName,
		u.DN,
		ISNULL(pn.EffectiveFromIsLocal,0),
		ISNULL(pn.Exclusive,0),
		pn.EffectiveFrom,
		pn.EffectiveUntil,
		u.PrincipalDN,
		pn.PostponeNoLaterThan,
		pn.PostponeNoLaterThanIsLocal,
		pn.PostponePeriod,
		pn.PostponeLatest,
		pn.PostponeOKForLowBandwidth,
		pn.PostponeOKForAnyReason,
		ISNULL(pn.Removable,0),
		pn.NetPrecedence,
		cast(NULL AS binary(16)) AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM	(SELECT	t.UserID,
			t.SAMAccountName,
			o.RDN,
			d.DN,
			'User' AS TargetTypeName,
			'CN=' + t.UserCN +','+ o.RDN + ',' + d.DN AS PrincipalDN
		FROM	[User] AS t,
			Organization AS o,
			Domain AS d
		WHERE	t.UserOUID = o.OrganizationID
		  AND	o.DomainID = d.OrganizationID
		  AND	(@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
		  AND	(d.dn LIKE @DomainDN)
		  AND	(d.DomainType = 'AD')
		  AND	t.UserID <> 1
		  AND	t.GUID IS NOT NULL
		  AND	t.UserID NOT IN
			(
				SELECT	TargetID
			 	FROM	Member AS m JOIN dbo.[Group] AS g ON g.GroupID = m.GroupID AND GroupCN = '+RSoP'
			 	WHERE	m.TargetTypeID = 2	-- Users
				  AND	(m.GroupID NOT IN
					(
						SELECT	GROUPID
						FROM 	#RSOPWithPolicySetting
					)
				  )
			)
		) AS u
	LEFT OUTER JOIN
		(SELECT	pap.TargetID,
			pap.PolicyGUID,
			pap.PolicyVersion,
			pal.Precedence AS PolicyPrecedence,
			ad.[Action],
			ad.EffectiveFromIsLocal,
			ad.Exclusive,
			ad.EffectiveFrom,
			ad.EffectiveUntil,
			ad.PostponeNoLaterThan,
			ad.PostponeNoLaterThanIsLocal,
			ad.PostponePeriod,
			ad.PostponeLatest,
			ad.PostponeOKForLowBandwidth,
			ad.PostponeOKForAnyReason,
			ad.Removable,
			p.DisplayName,
			tt.TargetTypeName,
			pp.PackageFullName,
			pap.Precedence AS NetPrecedence
		FROM	TargetedPackage AS pap,
			PackageAllocation AS pal,
			AllocationDetails AS ad,
			Policy AS p,
			TargetType AS tt,
			PackagePath AS pp
		WHERE	pap.TargetTypeID = 2
		  AND	pap.PolicyGUID = pal.PolicyGUID
		  AND	pap.PackagePathID = pal.PackagePathID
		  AND	pap.TargetTypeID = pal.TargetTypeID
		  AND	pap.AllocationDetailsID = pal.AllocationDetailsID
		  AND   pap.AllocationDetailsID = ad.AllocationDetailsID
		  AND	pap.PolicyGUID = p.GUID
		  AND	pap.TargetTypeID  = tt.TargetTypeID
		  AND	pap.PackagePathID = pp.PackagePathID
		  AND	(@guids IS NULL OR p.GUID IN (@guids))
		  AND	(ad.EffectiveUntil = 0
			OR ad.EffectiveUntil IS NULL
			OR ad.EffectiveUntil > DATEADD(Day, -2, GETDATE()))
		  AND	(pap.FromRSOP = 0
			OR (pap.RSOPGroupID IN (SELECT GroupID FROM #RSOPWithPolicySetting)))
		) AS pn
	ON	pn.TargetID = u.UserID 
	
	UNION ALL
	
	-- Computers Package Applies
	SELECT 
		u.ComputerCN AS PrincipalName,
		pn.DisplayName AS PolicyName, 
		pn.PolicyGUID,
		pn.PolicyVersion,
		pn.[Action],
		pn.PackageFullName,
		u.RDN,
		pn.PolicyPrecedence AS Precedence,
		u.TargetTypeName,
		u.DN,
		ISNULL(pn.EffectiveFromIsLocal,0),
		ISNULL(pn.Exclusive,0),
		pn.EffectiveFrom,
		pn.EffectiveUntil,
		u.PrincipalDN,
		pn.PostponeNoLaterThan,
		pn.PostponeNoLaterThanIsLocal,
		pn.PostponePeriod,
		pn.PostponeLatest,
		pn.PostponeOKForLowBandwidth,
		pn.PostponeOKForAnyReason,
		ISNULL(pn.Removable,0),
		pn.NetPrecedence,
		CAST(NULL AS binary(16)) AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM	(SELECT	t.ComputerID,
			t.ComputerCN,
			o.RDN,
			d.DN,
			'Computer' as TargetTypeName,
			'CN=' + t.ComputerCN + ',' + o.RDN + ',' + d.DN AS PrincipalDN
		FROM	[Computer] AS t,
			Organization AS o,
			Domain AS d
		WHERE	t.ComputerOUID = o.OrganizationID
		    AND o.DomainID = d.OrganizationID
		    AND (@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
		    AND (d.dn LIKE @DomainDN)
		    AND	(d.DomainType = 'AD')
		    AND	t.GUID IS NOT NULL
		    AND t.ComputerID NOT IN
			(
				SELECT	TargetID
			 	FROM	Member AS m JOIN dbo.[Group] AS g ON g.GroupID = m.GroupID AND g.GroupCN = '+RSoP'
			 	WHERE	m.TargetTypeID = 1	-- Computers
				  AND	(m.GroupID NOT IN
					(
						SELECT	GROUPID
						FROM 	#RSOPWithPolicySetting
					)
				  )
			)
		    
		) AS u
	LEFT OUTER JOIN
		(SELECT	pap.TargetID,
			pap.PolicyGUID,
			pap.PolicyVersion,
			pal.Precedence AS PolicyPrecedence,
			ad.[Action],
			ad.EffectiveFromIsLocal,
			ad.Exclusive,
			ad.EffectiveFrom,
			ad.EffectiveUntil,
			ad.PostponeNoLaterThan,
			ad.PostponeNoLaterThanIsLocal,
			ad.PostponePeriod,
			ad.PostponeLatest,
			ad.PostponeOKForLowBandwidth,
			ad.PostponeOKForAnyReason,
			ad.Removable,
			p.DisplayName,
			tt.TargetTypeName,
			pp.PackageFullName,
			pap.Precedence AS NetPrecedence
		FROM	TargetedPackage AS pap,
			PackageAllocation AS pal,
			AllocationDetails AS ad,
			Policy AS p,
			TargetType AS tt,
			PackagePath AS pp
		WHERE	pap.TargetTypeID = 1
		  AND	pap.PolicyGUID = pal.PolicyGUID
		  AND	pap.PackagePathID = pal.PackagePathID
		  AND	pap.TargetTypeID = pal.TargetTypeID
		  AND	pap.AllocationDetailsID = pal.AllocationDetailsID
		  AND   pap.AllocationDetailsID = ad.AllocationDetailsID
		  AND	pap.PolicyGUID = p.GUID
		  AND	pap.TargetTypeID  = tt.TargetTypeID
		  AND	pap.PackagePathID = pp.PackagePathID
		  AND	(@guids IS NULL OR p.GUID IN (@guids))
		  AND	(ad.EffectiveUntil = 0
			OR ad.EffectiveUntil IS NULL
			OR ad.EffectiveUntil > DATEADD(Day, -2, GETDATE()))
		  AND	(pap.FromRSOP = 0
			OR pap.RSOPGroupID IN (SELECT GroupID FROM #RSOPWithPolicySetting))
		) AS pn
	ON	pn.TargetID = u.ComputerID
	
	UNION ALL
	
	-- Users RSOP Mapping
	SELECT
		u.SAMAccountName AS PrincipalName,
		u.SAMAccountName  AS PolicyName, 
		cast(null AS binary(16)) AS PolicyGUID,
		cast(0 AS int) AS PolicyVersion,
		cast(null AS varchar) AS [Action],
		cast(null AS varchar) AS PackageFullName,
		u.RDN,
		cast(null AS int) AS Precedence,
		u.TargetTypeName,
		u.DN,
		cast(0 AS bit),
		cast(0 AS bit),
		cast(null AS datetime) AS EffectiveFrom,
		cast(null AS datetime) AS EffectiveUntil,
		u.PrincipalDN,
		cast(null AS datetime) AS PostponeNoLaterThan,
		cast(null AS bit) AS PostponeNoLaterThanIsLocal,
		cast(null AS int) AS PostponePeriod,
		cast(null AS bit) AS PostponeLatest,
		cast(null AS bit) AS PostponeOKForLowBandwidth,
		cast(null AS bit) AS PostponeOKForAnyReason,
		cast(null AS bit) AS Removable,
		cast(null AS int) AS NetPrecedence,
		g.GUID AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM	dbo.Member AS m JOIN dbo.[Group] AS g ON g.GroupID = m.GroupID AND g.GroupCN = '+RSoP',
		(
			SELECT	t.UserID,
				t.SAMAccountName,
				o.RDN,
				d.DN,
				'User' as TargetTypeName,
				'CN=' + t.UserCN +','+ o.RDN + ',' + d.DN AS PrincipalDN
			FROM	[User] AS t,
				Organization AS o,
				Domain AS d
			WHERE	t.UserOUID = o.OrganizationID
			    AND o.DomainID = d.OrganizationID
			    AND (@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
			    AND (d.dn LIKE @DomainDN)
			    AND	(d.DomainType = 'AD')
			    AND t.UserID <> 1
			    AND t.GUID IS NOT NULL
		) AS u
	WHERE	m.TargetTypeID = 2	-- Users
	  AND	m.TargetID = u.UserID
	  AND	(g.GroupID NOT IN 
		(
			SELECT	GROUPID
			FROM	#RSOPWithPolicySetting
		)
	  )
	
	UNION ALL
	
	-- Computers RSOP Mapping
	SELECT 
		u.ComputerCN AS PrincipalName,
		u.ComputerCN  AS PolicyName, 
		cast(null AS binary(16)) AS PolicyGUID,
		cast(0 AS int) AS PolicyVersion,
		cast(null AS varchar) AS [Action],
		cast(null AS varchar) AS PackageFullName,
		u.RDN,
		cast(null AS int) AS Precedence,
		u.TargetTypeName,
		u.DN,
		cast(0 AS bit),
		cast(0 AS bit),
		cast(null AS datetime) AS EffectiveFrom,
		cast(null AS datetime) AS EffectiveUntil,
		u.PrincipalDN,
		cast(null AS datetime) AS PostponeNoLaterThan,
		cast(null AS bit) AS PostponeNoLaterThanIsLocal,
		cast(null AS int) AS PostponePeriod,
		cast(null AS bit) AS PostponeLatest,
		cast(null AS bit) AS PostponeOKForLowBandwidth,
		cast(null AS bit) AS PostponeOKForAnyReason,
		cast(null AS bit) AS Removable,
		cast(null AS int) AS NetPrecedence,
		g.GUID AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM	dbo.Member AS m JOIN dbo.[Group] AS g ON g.GroupID = m.GroupID AND g.GroupCN = '+RSoP',
		(
			SELECT	t.ComputerID,
				t.ComputerCN,
				o.RDN,
				d.DN,
				'Computer' AS TargetTypeName,
				'CN=' + t.ComputerCN + ',' + o.RDN + ',' + d.DN AS PrincipalDN
			FROM	[Computer] AS t,
				Organization AS o,
				Domain AS d
			WHERE	t.ComputerOUID = o.OrganizationID
			    AND o.DomainID = d.OrganizationID
			    AND (@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
			    AND (d.dn LIKE @DomainDN)
			    AND	(d.DomainType = 'AD')
			    AND t.GUID IS NOT NULL
		) AS u
	WHERE	m.TargetTypeID = 1	-- Computers
	  AND	m.TargetID = u.ComputerID
	  AND	(g.GroupID NOT IN
		(
			SELECT	GROUPID
			FROM	#RSOPWithPolicySetting
		)
	  )

	UNION ALL

	-- MGS Policy
	SELECT  DISTINCT
		p.DisplayName as PrincipalName,
		p.DisplayName as PolicyName,
		p.GUID as PolicyGUID,
		0 as PolicyVersion,
		ad.[Action],
		pp.PackageFullName,
		'' as RDN,	
		pa.Precedence,
		CASE WHEN pa.TargetTypeID = 1 THEN 'Computer' ELSE 'User' END AS TargetTypeName,
		d.DN,
		ISNULL(ad.EffectiveFromIsLocal,0),
		ISNULL(ad.Exclusive,0),
		ad.EffectiveFrom,
		ad.EffectiveUntil,
		d.DN as PrincipleDN,
		ad.PostponeNoLaterThan,
		ad.PostponeNoLaterThanIsLocal,
		ad.PostponePeriod,
		ad.PostponeLatest,
		ad.PostponeOKForLowBandwidth,
		ad.PostponeOKForAnyReason,
		ISNULL(ad.Removable, 0),
		pa.Precedence as NetPrecedence,
		CAST(NULL AS binary(16)) AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM Policy as p
	JOIN PackageAllocation as pa
		ON pa.PolicyGUID = p.GUID
	JOIN Domain as d
		ON p.DomainID = d.OrganizationID
	JOIN PackagePath as pp
		ON pp.PackagePathID = pa.PackagePathID
	JOIN AllocationDetails as ad
		ON ad.AllocationDetailsID = pa.AllocationDetailsID
	WHERE d.DomainType = 'MGS'
		AND (d.DN LIKE @DomainDN)
		AND (@guids IS NULL OR p.GUID IN (@guids))
	
	ORDER BY
		u.DN,
		u.RDN,
		u.TargetTypeName,
		PrincipalName,
		pn.NetPrecedence
	
	DROP TABLE #RSOPWithPolicySetting
GO

PRINT 'Creating procedure to retrieve information required in policy distribution for MGS domain'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
        AND [name] = 'PolicyDistributeMGSDomainPolicy'
)
        DROP PROCEDURE PolicyDistributeMGSDomainPolicy
GO
CREATE PROCEDURE PolicyDistributeMGSDomainPolicy
        @guids binary(16),
        @DomainDN nvarchar(100)
AS
	IF @DomainDN IS NULL
	BEGIN
		SET @DomainDN = '%'
	END
	SELECT  DISTINCT
		p.DisplayName as PrincipalName,
		p.DisplayName as PolicyName,
		p.GUID as PolicyGUID,
		0 as PolicyVersion,
		ad.[Action],
		pp.PackageFullName,
		'' as RDN,	
		pa.Precedence,
		CASE WHEN pa.TargetTypeID = 1 THEN 'Computer' ELSE 'User' END AS TargetTypeName,
		d.DN,
		ISNULL(ad.EffectiveFromIsLocal,0),
		ISNULL(ad.Exclusive,0),
		ad.EffectiveFrom,
		ad.EffectiveUntil,
		d.DN as PrincipleDN,
		ad.PostponeNoLaterThan,
		ad.PostponeNoLaterThanIsLocal,
		ad.PostponePeriod,
		ad.PostponeLatest,
		ad.PostponeOKForLowBandwidth,
		ad.PostponeOKForAnyReason,
		ISNULL(ad.Removable, 0),
		pa.Precedence as NetPrecedence,
		CAST(NULL AS binary(16)) AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM Policy as p
	JOIN PackageAllocation as pa
		ON pa.PolicyGUID = p.GUID
	JOIN Domain as d
		ON p.DomainID = d.OrganizationID
	JOIN PackagePath as pp
		ON pp.PackagePathID = pa.PackagePathID
	JOIN AllocationDetails as ad
		ON ad.AllocationDetailsID = pa.AllocationDetailsID
	WHERE d.DomainType = 'MGS'
		AND (d.DN LIKE @DomainDN)
		AND (@guids IS NULL OR p.GUID IN (@guids))
	ORDER BY
	        d.DN,
	        RDN,
		TargetTypeName,
		PrincipalName,
		NetPrecedence
GO

PRINT 'Creating procedure to retrieve information required in policy distribution with no RSOP'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'PolicyDistributeNoRSOP'
)
	DROP PROCEDURE PolicyDistributeNoRSOP
GO
CREATE PROCEDURE PolicyDistributeNoRSOP
	@guids binary(16),
	@OUpattern nvarchar(400),
	@DomainDN nvarchar(100)
AS
	IF @DomainDN IS NULL
	BEGIN
		SET @DomainDN = '%'
	END
	
	-- Users Package Applies
	SELECT
		u.SAMAccountName AS PrincipalName,
		pn.DisplayName AS PolicyName, 
		pn.PolicyGUID,
		pn.PolicyVersion,
		pn.[Action],
		pn.PackageFullName,
		u.RDN,
		pn.PolicyPrecedence AS Precedence,
		u.TargetTypeName,
		u.DN,
		ISNULL(pn.EffectiveFromIsLocal,0),
		ISNULL(pn.Exclusive,0),
		pn.EffectiveFrom,
		pn.EffectiveUntil,
		u.PrincipalDN,
		pn.PostponeNoLaterThan,
		pn.PostponeNoLaterThanIsLocal,
		pn.PostponePeriod,
		pn.PostponeLatest,
		pn.PostponeOKForLowBandwidth,
		pn.PostponeOKForAnyReason,
		ISNULL(pn.Removable,0),
		pn.NetPrecedence,
		CAST(NULL AS binary(16)) AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM	(SELECT	t.UserID,
			t.SAMAccountName,
			o.RDN,
			d.DN,
			'User' AS TargetTypeName,
			'CN=' + t.UserCN +','+ o.RDN + ',' + d.DN AS PrincipalDN
		FROM	[User] AS t,
			Organization AS o,
			Domain AS d
		WHERE	t.UserOUID = o.OrganizationID
		    AND o.DomainID = d.OrganizationID
		    AND (@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
		    AND (d.dn LIKE @DomainDN)
		    AND	(d.DomainType = 'AD')
		    AND t.UserID <> 1
			AND t.GUID IS NOT NULL
		) AS u
	LEFT OUTER JOIN
		(SELECT	pap.TargetID,
			pap.PolicyGUID,
			pap.PolicyVersion,
			pal.Precedence AS PolicyPrecedence,
			ad.[Action],
			ad.EffectiveFromIsLocal,
			ad.Exclusive,
			ad.EffectiveFrom,
			ad.EffectiveUntil,
			ad.PostponeNoLaterThan,
			ad.PostponeNoLaterThanIsLocal,
			ad.PostponePeriod,
			ad.PostponeLatest,
			ad.PostponeOKForLowBandwidth,
			ad.PostponeOKForAnyReason,
			ad.Removable,
			p.DisplayName,
			tt.TargetTypeName,
			pp.PackageFullName,
			pap.Precedence AS NetPrecedence
		FROM	TargetedPackage AS pap,
			PackageAllocation AS pal,
			AllocationDetails AS ad,
			Policy AS p,
			TargetType AS tt,
			PackagePath AS pp
		WHERE	pap.TargetTypeID = 2
		  AND	pap.PolicyGUID = pal.PolicyGUID
		  AND	pap.PackagePathID = pal.PackagePathID
		  AND	pap.TargetTypeID = pal.TargetTypeID
		  AND	pap.AllocationDetailsID = pal.AllocationDetailsID
		  AND   pap.AllocationDetailsID = ad.AllocationDetailsID
		  AND	pap.PolicyGUID = p.GUID
		  AND	pap.TargetTypeID  = tt.TargetTypeID
		  AND	pap.PackagePathID = pp.PackagePathID
		  AND	(@guids IS NULL OR p.GUID IN (@guids))
		  AND	(ad.EffectiveUntil = 0
			OR ad.EffectiveUntil IS NULL
			OR ad.EffectiveUntil > DATEADD(Day, -2, GETDATE()))
		) AS pn
	ON	pn.TargetID = u.UserID 

	UNION ALL

	-- Computers Package Applies
	SELECT 
		u.ComputerCN AS PrincipalName,
		pn.DisplayName AS PolicyName, 
		pn.PolicyGUID,
		pn.PolicyVersion,
		pn.[Action],
		pn.PackageFullName,
		u.RDN,
		pn.PolicyPrecedence AS Precedence,
		u.TargetTypeName,
		u.DN,
		ISNULL(pn.EffectiveFromIsLocal,0),
		ISNULL(pn.Exclusive,0),
		pn.EffectiveFrom,
		pn.EffectiveUntil,
		u.PrincipalDN,
		pn.PostponeNoLaterThan,
		pn.PostponeNoLaterThanIsLocal,
		pn.PostponePeriod,
		pn.PostponeLatest,
		pn.PostponeOKForLowBandwidth,
		pn.PostponeOKForAnyReason,
		ISNULL(pn.Removable,0),
		pn.NetPrecedence,
		cast(NULL AS binary(16)) AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM	(SELECT	t.ComputerID,
			t.ComputerCN,
			o.RDN,
			d.DN,
			'Computer' as TargetTypeName,
			'CN=' + t.ComputerCN + ',' + o.RDN + ',' + d.DN AS PrincipalDN
		FROM	[Computer] AS t,
			Organization AS o,
			Domain AS d
		WHERE	t.ComputerOUID = o.OrganizationID
		    AND o.DomainID = d.OrganizationID
		    AND (@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
		    AND (d.dn LIKE @DomainDN)
		    AND	(d.DomainType = 'AD')
		    AND t.GUID IS NOT NULL
		) AS u
	LEFT OUTER JOIN
		(SELECT	pap.TargetID,
			pap.PolicyGUID,
			pap.PolicyVersion,
			pal.Precedence AS PolicyPrecedence,
			ad.[Action],
			ad.EffectiveFromIsLocal,
			ad.Exclusive,
			ad.EffectiveFrom,
			ad.EffectiveUntil,
			ad.PostponeNoLaterThan,
			ad.PostponeNoLaterThanIsLocal,
			ad.PostponePeriod,
			ad.PostponeLatest,
			ad.PostponeOKForLowBandwidth,
			ad.PostponeOKForAnyReason,
			ad.Removable,
			p.DisplayName,
			tt.TargetTypeName,
			pp.PackageFullName,
			pap.Precedence AS NetPrecedence
		FROM	TargetedPackage AS pap,
			PackageAllocation AS pal,
			AllocationDetails AS ad,
			Policy AS p,
			TargetType AS tt,
			PackagePath AS pp
		WHERE	pap.TargetTypeID = 1
		  AND	pap.PolicyGUID = pal.PolicyGUID
		  AND	pap.PackagePathID = pal.PackagePathID
		  AND	pap.TargetTypeID = pal.TargetTypeID
		  AND	pap.AllocationDetailsID = pal.AllocationDetailsID
		  AND   pap.AllocationDetailsID = ad.AllocationDetailsID
		  AND	pap.PolicyGUID = p.GUID
		  AND	pap.TargetTypeID  = tt.TargetTypeID
		  AND	pap.PackagePathID = pp.PackagePathID
		  AND	(@guids IS NULL OR p.GUID IN (@guids))
		  AND	(ad.EffectiveUntil = 0
			OR ad.EffectiveUntil IS NULL
			OR ad.EffectiveUntil > DATEADD(Day, -2, GETDATE()))
		) AS pn
	ON	pn.TargetID = u.ComputerID

	UNION ALL
	 
	-- MGS Policy
	SELECT  DISTINCT
		p.DisplayName as PrincipalName,
		p.DisplayName as PolicyName,
		p.GUID as PolicyGUID,
		0 as PolicyVersion,
		ad.[Action],
		pp.PackageFullName,
		'' as RDN,	
		pa.Precedence,
		CASE WHEN pa.TargetTypeID = 1 THEN 'Computer' ELSE 'User' END AS TargetTypeName,
		d.DN,
		ISNULL(ad.EffectiveFromIsLocal,0),
		ISNULL(ad.Exclusive,0),
		ad.EffectiveFrom,
		ad.EffectiveUntil,
		d.DN as PrincipleDN,
		ad.PostponeNoLaterThan,
		ad.PostponeNoLaterThanIsLocal,
		ad.PostponePeriod,
		ad.PostponeLatest,
		ad.PostponeOKForLowBandwidth,
		ad.PostponeOKForAnyReason,
		ISNULL(ad.Removable,0),
		pa.Precedence as NetPrecedence,
		CAST(NULL AS binary(16)) AS RSOPGUID,
		CAST(0 as bit) AS EmptyRSOP
	FROM Policy as p
	JOIN PackageAllocation as pa
		ON pa.PolicyGUID = p.GUID
	JOIN Domain as d
		ON p.DomainID = d.OrganizationID
	JOIN PackagePath as pp
		ON pp.PackagePathID = pa.PackagePathID
	JOIN AllocationDetails as ad
		ON ad.AllocationDetailsID = pa.AllocationDetailsID
	WHERE d.DomainType = 'MGS'
		AND (d.DN LIKE @DomainDN)
		AND (@guids IS NULL OR p.GUID IN (@guids))
	
	ORDER BY
		u.DN,
		u.RDN,
		u.TargetTypeName,
		PrincipalName,
		pn.NetPrecedence
GO

PRINT 'Creating procedure to retrieve information required in policy distribution'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'PolicyDistributeQuery'
)
	DROP PROCEDURE PolicyDistributeQuery
GO
CREATE PROCEDURE PolicyDistributeQuery
	@guids binary(16),
	@OUpattern nvarchar(400),
	@DomainDN nvarchar(100),
	@SupportRSOP bit = 0,
	@FullRSOP bit = 0
AS

	IF @SupportRSOP = 1
		BEGIN
			IF @FullRSOP = 1
				BEGIN
					EXEC dbo.PolicyDistributeFullRSOPMapping @guids, @OUpattern, @DomainDN 
				END
			ELSE
				BEGIN
					EXEC dbo.PolicyDistributePartialRSOPMapping @guids, @OUpattern, @DomainDN
				END
		END
	ELSE
		BEGIN
			EXEC dbo.PolicyDistributeNoRSOP @guids, @OUpattern, @DomainDN
		END
GO

PRINT 'Creating procedure to retrieve information required in policy distribution for full RSOP'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'PolicyDistributeFullRSOP'
)
	DROP PROCEDURE PolicyDistributeFullRSOP
GO
CREATE PROCEDURE dbo.PolicyDistributeFullRSOP
	@guids binary(16),
	@OUpattern nvarchar(400),
	@DomainDN nvarchar(100)
AS
	IF @DomainDN IS NULL
	BEGIN
		SET @DomainDN = '%'
	END
	
	SELECT
		'' AS PrincipalName,
		package.DisplayName AS PolicyName,
		package.PolicyGUID,
		package.PolicyVersion,
		package.[Action],
		package.PackageFullName,	
		'' AS RDN,
		ISNULL(package.Precedence, 0) AS Precedence,
		rsopgroup.TargetTypeName,
		rsopgroup.DN,	
		ISNULL(package.EffectiveFromIsLocal, 0) AS EffectiveFromIsLocal,
		ISNULL(package.Exclusive, 0) AS Exclusive,
		package.EffectiveFrom,
		package.EffectiveUntil,
		rsopgroup.DN AS PrincipalDN,
		package.PostponeNoLaterThan,
		ISNULL(package.PostponeNoLaterThanIsLocal, 0) AS PostponeNoLaterThanIsLocal,
		package.PostponePeriod,
		package.PostponeLatest,
		package.PostponeOKForLowBandwidth,
		package.PostponeOKForAnyReason,
		ISNULL(package.Removable, 0) AS Removable,
		ISNULL(package.NetPrecedence, 0) AS NetPrecedence,
		rsopgroup.GUID,
		CAST(CASE WHEN package.PackageFullName IS NULL THEN 1 ELSE 0 END as bit) AS EmptyRSOP
	FROM
		(
			SELECT	g.GroupID,
				g.GUID,
				g.GroupOUID,
				tt.TargetTypeName,
				o.RDN,
				d.DN
			FROM	[Group] AS g
				INNER JOIN
				(
					SELECT	GroupID,
							TargetTypeID
					FROM	Member
					GROUP BY GroupID, TargetTypeID
				) AS m ON m.GroupID = g.GroupID
				INNER JOIN TargetType AS tt ON tt.TargetTypeID = m.TargetTypeID
				INNER JOIN Organization AS o ON o.OrganizationID = g.GroupOUID
				INNER JOIN Domain AS d ON d.OrganizationID = o.DomainID
			WHERE	g.GroupCN LIKE '+RSoP'
			  AND	d.DN LIKE @DomainDN
			  AND	d.DomainType = 'AD'
		) AS rsopgroup
		LEFT OUTER JOIN
		(
			SELECT
				pap.TargetID,
				p.DisplayName,
				pap.PolicyGUID,
				pap.PolicyVersion,
				ad.[Action],
				pp.PackageFullName,	
				pal.Precedence,
				ISNULL(ad.EffectiveFromIsLocal, 0) AS EffectiveFromIsLocal,
				ISNULL(ad.Exclusive, 0) AS Exclusive,
				ad.EffectiveFrom,
				ad.EffectiveUntil,
				ad.PostponeNoLaterThan,
				ad.PostponeNoLaterThanIsLocal,
				ad.PostponePeriod,
				ad.PostponeLatest,
				ad.PostponeOKForLowBandwidth,
				ad.PostponeOKForAnyReason,
				ISNULL(ad.Removable, 0) AS Removable,
				pap.Precedence AS NetPrecedence
			FROM	PackageApplies AS pap,
				PackageAllocation AS pal,
				AllocationDetails AS ad,
				Policy AS p,
				TargetType AS tt,
				PackagePath AS pp,
				(
					select GroupID, TargetTypeID
					from dbo.Member
					group by GroupID, TargetTypeID
				) as m
			WHERE	pap.TargetTypeID = 3	-- RSOP
			  AND	pap.PolicyGUID = pal.PolicyGUID
			  AND	pap.PackagePathID = pal.PackagePathID
			  AND	pap.AllocationDetailsID = pal.AllocationDetailsID
			  AND   pap.AllocationDetailsID = ad.AllocationDetailsID
			  AND	pap.TargetID = m.GroupID
			  AND	m.TargetTypeID = pal.TargetTypeID
			  AND	m.TargetTypeID = tt.TargetTypeID
			  AND	pal.TargetTypeID = tt.TargetTypeID
			  AND	pap.PolicyGUID = p.GUID
			  AND	pap.PackagePathID = pp.PackagePathID
			  AND	(@guids IS NULL OR p.GUID IN (@guids))
			  AND	(ad.EffectiveUntil = 0
				OR ad.EffectiveUntil IS NULL
				OR ad.EffectiveUntil > DATEADD(Day, -2, GETDATE()))
		) AS package ON package.TargetID = rsopgroup.GroupID

	ORDER BY
		rsopgroup.DN,
		rsopgroup.TargetTypeName,
		rsopgroup.Guid,
		package.NetPrecedence
GO

PRINT 'Creating procedure to retrieve information required in policy distribution for partial RSOP'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'PolicyDistributePartialRSOP'
)
	DROP PROCEDURE PolicyDistributePartialRSOP
GO
CREATE PROCEDURE dbo.PolicyDistributePartialRSOP
	@guids binary(16),
	@OUpattern nvarchar(400),
	@DomainDN nvarchar(100)
AS
	IF @DomainDN IS NULL
	BEGIN
		SET @DomainDN = '%'
	END
	
	CREATE TABLE #RSOPWithPolicySetting
	(
		GroupID int
	)
	
	INSERT INTO #RSOPWithPolicySetting
	SELECT	DISTINCT TargetID
	FROM 	dbo.PackageApplies AS pa
		JOIN dbo.AllocationDetails AS ad ON ad.AllocationDetailsID = pa.AllocationDetailsID
	WHERE	TargetTypeID = 3 -- RSOP
		AND (
			(ad.EffectiveFrom IS NOT NULL)
			OR (ISNULL(ad.Wake, 0) = 1)
		)

	SELECT
		'' AS PrincipalName,
		package.DisplayName AS PolicyName,
		package.PolicyGUID,
		package.PolicyVersion,
		package.[Action],
		package.PackageFullName,	
		'' AS RDN,
		ISNULL(package.Precedence, 0) AS Precedence,
		rsopgroup.TargetTypeName,
		rsopgroup.DN,	
		ISNULL(package.EffectiveFromIsLocal, 0) AS EffectiveFromIsLocal,
		ISNULL(package.Exclusive, 0) AS Exclusive,
		package.EffectiveFrom,
		package.EffectiveUntil,
		rsopgroup.DN AS PrincipalDN,
		package.PostponeNoLaterThan,
		ISNULL(package.PostponeNoLaterThanIsLocal, 0) AS PostponeNoLaterThanIsLocal,
		package.PostponePeriod,
		package.PostponeLatest,
		package.PostponeOKForLowBandwidth,
		package.PostponeOKForAnyReason,
		ISNULL(package.Removable, 0) AS Removable,
		ISNULL(package.NetPrecedence, 0) AS NetPrecedence,
		rsopgroup.GUID,
		CAST(CASE WHEN package.PackageFullName IS NULL THEN 1 ELSE 0 END as bit) AS EmptyRSOP
	FROM
		(
			SELECT	g.GroupID,
				g.GUID,
				g.GroupOUID,
				tt.TargetTypeName,
				o.RDN,
				d.DN
			FROM	[Group] AS g
				INNER JOIN
				(
					SELECT	GroupID,
							TargetTypeID
					FROM	Member
					GROUP BY GroupID, TargetTypeID
				) AS m ON m.GroupID = g.GroupID
				INNER JOIN TargetType AS tt ON tt.TargetTypeID = m.TargetTypeID
				INNER JOIN Organization AS o ON o.OrganizationID = g.GroupOUID
				INNER JOIN Domain AS d ON d.OrganizationID = o.DomainID
			WHERE	g.GroupCN LIKE '+RSoP'
			  AND	d.DN LIKE @DomainDN
			  AND	d.DomainType = 'AD'
		) AS rsopgroup
		LEFT OUTER JOIN
		(
			SELECT
				pap.TargetID,
				p.DisplayName,
				pap.PolicyGUID,
				pap.PolicyVersion,
				ad.[Action],
				pp.PackageFullName,	
				pal.Precedence,
				ISNULL(ad.EffectiveFromIsLocal, 0) AS EffectiveFromIsLocal,
				ISNULL(ad.Exclusive, 0) AS Exclusive,
				ad.EffectiveFrom,
				ad.EffectiveUntil,
				ad.PostponeNoLaterThan,
				ad.PostponeNoLaterThanIsLocal,
				ad.PostponePeriod,
				ad.PostponeLatest,
				ad.PostponeOKForLowBandwidth,
				ad.PostponeOKForAnyReason,
				ISNULL(ad.Removable, 0) AS Removable,
				pap.Precedence AS NetPrecedence
			FROM	PackageApplies AS pap,
				PackageAllocation AS pal,
				AllocationDetails AS ad,
				Policy AS p,
				TargetType AS tt,
				PackagePath AS pp,
				(
					select GroupID, TargetTypeID
					from dbo.Member
					group by GroupID, TargetTypeID
				) as m
			WHERE	pap.TargetTypeID = 3	-- RSOP
			  AND	pap.PolicyGUID = pal.PolicyGUID
			  AND	pap.PackagePathID = pal.PackagePathID
			  AND	pap.AllocationDetailsID = pal.AllocationDetailsID
			  AND   pap.AllocationDetailsID = ad.AllocationDetailsID
			  AND	pap.TargetID = m.GroupID
			  AND	m.TargetTypeID = pal.TargetTypeID
			  AND	m.TargetTypeID = tt.TargetTypeID
			  AND	pal.TargetTypeID = tt.TargetTypeID
			  AND	pap.PolicyGUID = p.GUID
			  AND	pap.PackagePathID = pp.PackagePathID
			  AND	(@guids IS NULL OR p.GUID IN (@guids))
			  AND	(ad.EffectiveUntil = 0
				OR ad.EffectiveUntil IS NULL
				OR ad.EffectiveUntil > DATEADD(Day, -2, GETDATE()))
			  AND	NOT EXISTS
				(
					SELECT	GroupID
					FROM	#RSOPWithPolicySetting
					WHERE	GroupID = pap.TargetID
				)
		) AS package ON package.TargetID = rsopgroup.GroupID

	ORDER BY
		rsopgroup.DN,
		rsopgroup.TargetTypeName,
		rsopgroup.Guid,
		package.NetPrecedence

	DROP TABLE #RSOPWithPolicySetting
GO

PRINT 'Creating procedure to retrieve information required in policy distribution for RSOP'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'PolicyDistributeRSOPQuery'
)
	DROP PROCEDURE PolicyDistributeRSOPQuery
GO
CREATE PROCEDURE PolicyDistributeRSOPQuery
	@guids binary(16),
	@OUpattern nvarchar(400),
	@DomainDN nvarchar(100),
	@FullRSOP bit = 0
AS

	IF @FullRSOP = 1
		BEGIN
			EXEC dbo.PolicyDistributeFullRSOP @guids, @OUpattern, @DomainDN
		END
	ELSE
		BEGIN
			EXEC dbo.PolicyDistributePartialRSOP @guids, @OUpattern, @DomainDN
		END
GO

PRINT 'Creating procedure to get a row count from the above stored procedure'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'PolicyDistributeCount'
)
	DROP PROCEDURE PolicyDistributeCount
GO
CREATE PROCEDURE PolicyDistributeCount
	@guids binary(16),
	@OUpattern nvarchar(400),
	@DomainDN nvarchar(100),
	@SupportRSOP bit = 0,
	@FullRSOP bit = 0
AS
	IF @DomainDN IS NULL
	BEGIN
		SET @DomainDN = '%'
	END
	
	CREATE TABLE #RSOPWithPolicySetting
	(
		GroupID int
	)
	
	IF @FullRSOP = 0
	BEGIN
		INSERT INTO #RSOPWithPolicySetting
		SELECT	DISTINCT TargetID
		FROM	dbo.PackageApplies AS pa
			JOIN dbo.AllocationDetails AS ad ON ad.AllocationDetailsID = pa.AllocationDetailsID
		WHERE	TargetTypeID = 3 -- RSOP
			AND (
				(ad.EffectiveFrom IS NOT NULL)
				OR (ISNULL(ad.Wake, 0) = 1)
			)
	END

	SELECT count(*) as CountColumn	
	FROM	(	
			-- Users
			SELECT	1 as Column1
			FROM	(SELECT	t.UserID
				FROM	[User] AS t, Organization AS o, Domain AS d
				WHERE	t.UserOUID = o.OrganizationID
				    AND o.DomainID = d.OrganizationID
				    AND (@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
				    AND (d.dn LIKE @DomainDN)
				    AND t.UserID <> 1
					AND t.GUID IS NOT NULL
				  AND	(t.UserID NOT IN
					(
						SELECT	TargetID
					 	FROM	Member AS m JOIN dbo.[Group] AS g ON g.GroupID = m.GroupID AND g.GroupCN = '+RSoP'
					 	WHERE	m.TargetTypeID = 2	-- Users
						  AND	(m.GroupID NOT IN
							(
								SELECT	GROUPID
								FROM 	#RSOPWithPolicySetting
							)
						  )
					)
					OR (@SupportRSOP = 0)
				  )
				) AS u
			LEFT OUTER JOIN
				(SELECT pap.TargetID
				FROM	TargetedPackage AS pap, Policy AS p, PackagePath AS pp
				WHERE	pap.TargetTypeID = 2
				    AND pap.PolicyGUID = p.GUID
				    AND pp.PackagePathID = pap.PackagePathID
				    AND (@guids IS NULL OR p.GUID IN (@guids))
				  AND	(pap.FromRSOP = 0
					OR @SupportRSOP = 0
					OR (pap.RSOPGroupID IN (SELECT GroupID FROM #RSOPWithPolicySetting))) 
				) AS pn
			ON	pn.TargetID = u.UserID 

			UNION ALL

			-- Computers
			SELECT 	1 AS Column1
			FROM	(SELECT	t.ComputerID
				FROM	[Computer] AS t,
					Organization AS o,
					Domain AS d
				WHERE	t.ComputerOUID = o.OrganizationID
				    AND o.DomainID = d.OrganizationID
				    AND (@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
				    AND (d.dn LIKE @DomainDN)
					AND	t.GUID IS NOT NULL
				  	AND	(t.ComputerID NOT IN
					(
						SELECT	TargetID
						FROM	Member AS m JOIN dbo.[Group] AS g ON g.GroupID = m.GroupID AND g.GroupCN = '+RSoP'
					 	WHERE	m.TargetTypeID = 1	-- Computers
						  AND	(m.GroupID NOT IN
							(
								SELECT	GROUPID
								FROM 	#RSOPWithPolicySetting
							)
						  )
					)
					OR (@SupportRSOP = 0)
				  )
				) AS u
			LEFT OUTER JOIN
				(SELECT pap.TargetID
				FROM	TargetedPackage AS pap, Policy AS p, PackagePath AS pp
				WHERE	pap.TargetTypeID = 1
				    AND pap.PolicyGUID = p.GUID
				    AND pp.PackagePathID = pap.PackagePathID
				    AND (@guids IS NULL OR p.GUID IN (@guids))
				  	AND	(pap.FromRSOP = 0
					OR @SupportRSOP = 0
					OR (pap.RSOPGroupID IN (SELECT GroupID FROM #RSOPWithPolicySetting)))
				) AS pn
			ON	pn.TargetID = u.ComputerID

			UNION ALL
			
			-- Users RSOP Mapping
			SELECT	1 AS Column1
			FROM	dbo.Member AS m join dbo.[Group] AS g ON g.GroupID = m.GroupID AND g.GroupCN = '+RSoP',
				(SELECT	t.UserID
				FROM	[User] AS t,
					Organization AS o,
					Domain AS d
				WHERE	t.UserOUID = o.OrganizationID
				    AND o.DomainID = d.OrganizationID
				    AND (@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
				    AND (d.dn LIKE @DomainDN)
				    AND t.UserID <> 1
					AND	t.GUID IS NOT NULL
				) AS u
			WHERE	m.TargetTypeID = 2	-- Users
			  AND	m.TargetID = u.UserID
			  AND   @SupportRSOP = 1
			  AND	(g.GroupID NOT IN 
				(
					SELECT	GROUPID
					FROM	#RSOPWithPolicySetting
				)
			  )
			
			UNION ALL

			-- Computers RSOP Mapping
			SELECT	1 AS Column1
			FROM 	dbo.Member AS m join dbo.[Group] AS g ON g.GroupID = m.GroupID AND g.GroupCN = '+RSoP',
				(SELECT	t.ComputerID
				FROM	[Computer] AS t,
					Organization AS o,
					Domain AS d
				WHERE	t.ComputerOUID = o.OrganizationID
				    AND o.DomainID = d.OrganizationID
				    AND (@OUpattern IS NULL OR o.RDN LIKE @OUpattern)
				    AND (d.dn LIKE @DomainDN)
					AND	t.GUID IS NOT NULL
				) AS u
			where	m.TargetTypeID = 1
			  AND	m.TargetID = u.ComputerID
			  AND   @SupportRSOP = 1
			  AND	(g.GroupID NOT IN 
				(
					SELECT	GROUPID
					FROM	#RSOPWithPolicySetting
				)
			  )

			UNION ALL

			-- RSOP Groups
			SELECT	1 as Column1
			FROM
				(
					SELECT	g.GroupID
					FROM	[Group] AS g
						INNER JOIN
						(
							SELECT	GroupID,
									TargetTypeID
							FROM	Member
							GROUP BY GroupID, TargetTypeID
						) AS m ON m.GroupID = g.GroupID
						INNER JOIN TargetType AS tt ON tt.TargetTypeID = m.TargetTypeID
						INNER JOIN Organization AS o ON o.OrganizationID = g.GroupOUID
						INNER JOIN Domain AS d ON d.OrganizationID = o.DomainID
					WHERE	g.GroupCN LIKE '+RSoP'
					  AND	d.DN LIKE @DomainDN
					  AND @SupportRSOP = 1
				) AS rsopgroup
				LEFT OUTER JOIN
				(
					SELECT	pap.TargetID
					FROM	PackageApplies AS pap,
							AllocationDetails AS ad
					WHERE	pap.TargetTypeID = 3	-- RSOP
					  AND   pap.AllocationDetailsID = ad.AllocationDetailsID
					  AND	(@guids IS NULL OR pap.PolicyGUID IN (@guids))
					  AND	(ad.EffectiveUntil = 0
						OR ad.EffectiveUntil IS NULL
						OR ad.EffectiveUntil > DATEADD(Day, -2, GETDATE()))
					  AND @SupportRSOP = 1
					  AND	(pap.TargetID NOT IN 
						(
							SELECT	GROUPID
							FROM	#RSOPWithPolicySetting
						)
					  )
				) AS package ON package.TargetID = rsopgroup.GroupID
		) as tempTable	

	DROP TABLE #RSOPWithPolicySetting
GO

PRINT 'Creating procedure to get the OUs that a policy affects'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'TargetedPolicyOUs'
)
	DROP PROCEDURE TargetedPolicyOUs
GO
CREATE PROCEDURE TargetedPolicyOUs
	@guid binary(16)
AS
	SELECT	o.RDN,
		d.DN
	FROM	Organization AS o,
		Domain AS d
	WHERE EXISTS(
	    	SELECT	*
		FROM	(SELECT pap.GUID, pap.TargetOUID
			FROM dbo.PolicyApplies AS pap
			WHERE pap.TargetTypeID <= 2	-- Computers and Users
			UNION
			SELECT pap.GUID, t.TargetOUID
			FROM dbo.PolicyApplies AS pap join dbo.Member AS m ON m.GroupID = pap.TargetID
				join dbo.Target(2) AS t ON t.TargetID = m.TargetID and t.TargetTypeID = m.TargetTypeID
			WHERE pap.TargetTypeID = 3	-- RSoP
			) AS pa
		WHERE	o.OrganizationID = pa.TargetOUID
		  AND	pa.GUID = @guid
		)
	  AND	o.DomainID = d.OrganizationID
GO

PRINT 'Creating procedure to get the users and computers unaffected by policy'
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
	AND [name] = 'EmptyPolicyUsers'
)
	DROP PROCEDURE EmptyPolicyUsers
GO
CREATE PROCEDURE EmptyPolicyUsers
AS
	SELECT UserCN, d.DN 
	FROM [User], Organization AS o, Domain AS d
	WHERE UserID NOT IN 
	(
		SELECT TargetID 
		FROM TargetedPackage
		WHERE TargetTypeID=2
	)
	AND UserOUID = o.OrganizationID
	AND o.DomainID = d.OrganizationID
	UNION
	SELECT ComputerCN, d.DN
	FROM [Computer], Organization AS o, Domain AS d
	WHERE ComputerID NOT IN 
	(
		SELECT TargetID 
		FROM TargetedPackage
		WHERE TargetTypeID=1
	)
	AND ComputerOUID = o.OrganizationID
	AND o.DomainID = d.OrganizationID

GO
/* 
 * $Id: LicenseInventorySummaryOfDetails.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: LicenseInventorySummaryOfDetails
 *	Input:
 *	@spID, @oudn, @ouMatch
 *
 *	Returns:
 *	ComputerCN, OU, UserCount
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
 
-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'LicenseInventorySummaryOfDetails' AND xtype = 'P'
)
	DROP PROCEDURE LicenseInventorySummaryOfDetails
GO

CREATE PROCEDURE [LicenseInventorySummaryOfDetails]
	@spID INT, -- Match on license ID
	@oudn VARCHAR(800) = '%',
	@ouMatch BIT=1 --Include sub-Ous 1=True, 0=False
AS

CREATE TABLE #Organization(OrganizationID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

SELECT 
	tab.ComputerID,
	tab.ComputerCN,
	tab.OU,
	UserCount = COUNT(DISTINCT tab.UserID)
FROM
(
	SELECT 
		c.ComputerID,
		c.ComputerCN,
		dbo.OUName(o.OrganizationID) AS OU,
		so.UserID
	
	FROM 
		ProductContainsSoftware pcs, 
		SoftwareOccurrence so, 
		#Organization o, 
		Computer c
	
	WHERE	pcs.SoftwareProductID = @spID
	  AND	pcs.SoftwareVersionID = so.SoftwareID
	  AND	so.ComputerID = c.ComputerID
	  AND	o.OrganizationID = c.ComputerOUID
	
) AS tab

GROUP BY tab.ComputerID, tab.ComputerCN, tab.OU
ORDER BY UserCount ASC
GO
/* 
 * $Id: LicenseInventorySummaryOfDetailsByUser.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: LicenseInventorySummaryOfDetailsByUser
 *	Input:
 *	@spID, @oudn, @ouMatch
 *
 *	Returns:
 *	UserCN, OU, ComputerCount
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
 
-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'LicenseInventorySummaryOfDetailsByUser' AND xtype = 'P'
)
	DROP PROCEDURE LicenseInventorySummaryOfDetailsByUser
GO




CREATE PROCEDURE [LicenseInventorySummaryOfDetailsByUser]
	@spID INT, -- Match on license ID
	@oudn VARCHAR(800) = '%',
	@ouMatch BIT=1 --Include sub-Ous 1=True, 0=False
AS

CREATE TABLE #Organization(OrganizationID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

SELECT 
	tab.UserID,
	tab.UserCN,
	tab.OU,
	ComputerCount = COUNT(DISTINCT tab.ComputerID)
FROM
(
	SELECT 
		u.UserID,
		u.UserCN,
		dbo.OUName(o.OrganizationID) AS OU,
		so.ComputerID
	
	FROM 
		ProductContainsSoftware pcs, 
		SoftwareOccurrence so, 
		#Organization o, 
		[User] u
	
	WHERE	pcs.SoftwareProductID = @spID
	  AND	pcs.SoftwareVersionID = so.SoftwareID
	  AND	so.UserID = u.UserID
	  AND	o.OrganizationID = u.UserOUID

	UNION

	SELECT 
		UserID = 1,
		UserCN = (SELECT UserCN FROM [User] WHERE UserID = 1),
		OU = NULL,
		so.ComputerID
	
	FROM 
		ProductContainsSoftware pcs, 
		SoftwareOccurrence so, 
		#Organization o,
		Computer c
	
	WHERE	pcs.SoftwareProductID = @spID
	  AND	pcs.SoftwareVersionID = so.SoftwareID
	  AND	so.UserID = 1
	  AND	so.ComputerID = c.ComputerID
	  AND	o.OrganizationID = c.ComputerOUID
	
) AS tab

GROUP BY tab.UserID, tab.UserCN, tab.OU
ORDER BY ComputerCount ASC
GO
/* 
 * $Id: LicenseInventoryDetails.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: LicenseInventoryDetails
 *	Input:
 *	@spID, @oudn, @ouMatch
 *
 *	Returns:
 *	ComputerCN, UserCN, OU, SoftwareID, SoftwareName, Version, Evidence
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
 
-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'LicenseInventoryDetails' AND xtype = 'P'
)
	DROP PROCEDURE LicenseInventoryDetails
GO

CREATE PROCEDURE [LicenseInventoryDetails]
	@spID INT, -- Match on license ID
	@compID INT -- Match on computer ID
AS

SELECT 
	c.ComputerID,
	c.ComputerCN,
	OU = (o.RDN + ',' + d.DN),
	u.UserCN,
	so.SoftwareID, 
	sv.SoftwareName,
	sv.Version,
	so.Evidence

FROM 
	ProductContainsSoftware pcs, 
	SoftwareOccurrence so, 
	SoftwareVersion sv, 
	Domain d,
	Organization o, 
	[User] u, 
	Computer c

WHERE	pcs.SoftwareProductID = @spID
  AND	pcs.SoftwareVersionID = so.SoftwareID
  AND	so.SoftwareID = sv.SoftwareID
  AND	so.ComputerID = c.ComputerID
  AND	c.ComputerID = @compID
  AND	so.UserID = u.UserID
  AND	o.OrganizationID = c.ComputerOUID
  AND	o.DomainID = d.OrganizationID

ORDER BY c.ComputerCN, u.UserCN
GO
/* 
 * $Id: LicenseInventoryDetailsByUser.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: LicenseInventoryDetailsByUser
 *	Input:
 *	@spID, @oudn, @ouMatch
 *
 *	Returns:
 *	ComputerCN, UserCN, OU, SoftwareID, SoftwareName, Version, Evidence
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
 
-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'LicenseInventoryDetailsByUser' AND xtype = 'P'
)
	DROP PROCEDURE LicenseInventoryDetailsByUser
GO


CREATE PROCEDURE [LicenseInventoryDetailsByUser]
	@spID INT, -- Match on license ID
	@userID INT, -- Match on computer ID
	@oudn VARCHAR(800) = '%',
	@ouMatch BIT=1 --Include sub-Ous 1=True, 0=False
AS

CREATE TABLE #Organization(OrganizationID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

IF (@userID <> 1)
BEGIN
SELECT 
	u.UserID,
	u.UserCN,
	dbo.OUName(o.OrganizationID) AS OU,
	c.ComputerCN,
	so.SoftwareID, 
	sv.SoftwareName,
	sv.Version,
	Evidence =
		CASE so.Evidence
		WHEN 'Uninstall' THEN 'Add/Remove Entry'
		WHEN 'ExeHdr' THEN 'EXE Header Info'
		WHEN 'MSI' THEN 'MSI Database'
		WHEN 'ManageSoft' THEN 'ManageSoft'
		WHEN 'DllHdr' THEN 'DLL Header Info'
		ELSE so.Evidence
		END

FROM 
	ProductContainsSoftware pcs, 
	SoftwareOccurrence so, 
	SoftwareVersion sv, 
	#Organization o, 
	[User] u, 
	Computer c

WHERE	pcs.SoftwareProductID = @spID
  AND	pcs.SoftwareVersionID = so.SoftwareID
  AND	so.SoftwareID = sv.SoftwareID
  AND	so.ComputerID = c.ComputerID
  AND	u.UserID = @userID
  AND	so.UserID = u.UserID
  AND	o.OrganizationID = u.UserOUID


ORDER BY u.UserCN, c.ComputerCN
END

ELSE 

BEGIN

DECLARE @systemUser VARCHAR(20)
SET @systemUser = (SELECT UserCN FROM [User] WHERE UserID = 1)
/********************************************/

SELECT 
	UserID = 1,
	UserCN = @systemUser,
	OU = NULL,
	c.ComputerCN,
	so.SoftwareID, 
	sv.SoftwareName,
	sv.Version,
	so.Evidence

FROM 
	ProductContainsSoftware pcs, 
	SoftwareOccurrence so, 
	SoftwareVersion sv, 
	#Organization o,
	Computer c

WHERE	pcs.SoftwareProductID = @spID
  AND	pcs.SoftwareVersionID = so.SoftwareID
  AND	so.SoftwareID = sv.SoftwareID
  AND	so.ComputerID = c.ComputerID
  AND	so.UserID = 1
  AND	o.OrganizationID = c.ComputerOUID

ORDER BY c.ComputerCN
END
GO
/* 
 * $Id: LicenseUsageSummaryOfDetails.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: LicenseUsageSummaryOfDetails
 *	Input:
 *	@spID, @oudn, @ouMatch
 *
 *	Returns:
 *	ComputerCN, OU, UserCount, TotalNumbeOfTimesUsed
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
 
-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'LicenseUsageSummaryOfDetails' AND xtype = 'P'
)
	DROP PROCEDURE LicenseUsageSummaryOfDetails
GO

CREATE PROCEDURE [LicenseUsageSummaryOfDetails]
	@spID INT, -- Match on license ID
	@oudn VARCHAR(800) = '%',
	@ouMatch BIT=1, --Include sub-Ous 1=True, 0=False
	@fromDate DATETIME = NULL,
	@tillDate DATETIME = NULL
AS

CREATE TABLE #Organization(OrganizationID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0
 
-- SET the dates 
IF @fromDate IS NULL 
	SET @fromDate = (SELECT MIN(StartOfWeek) FROM SoftwareUsagePerWeek)

IF @tillDate IS NULL 
	SET @tillDate = (SELECT MAX(StartOfWeek) FROM SoftwareUsagePerWeek)
	
-- The StartOfWeek represents the start of the week in which usage has been reported 
-- and NOT the day the usage has been reported. 
-- Thus we need to do some processing to map the date ranges (from and till date) back
-- to the start of the week
SET @fromDate = dbo.GetStartOfWeekForDate(@fromDate)
SET @tillDate = dbo.GetStartOfWeekForDate(@tillDate)
	
/********************************************/

SELECT 
	tab.ComputerID,
	tab.ComputerCN,
	tab.OU,
	UserCount = COUNT(DISTINCT tab.UserCN),
	TotalNumberOfTimesUsed = SUM(tab.NumberOfTimesUsedPerComputer)
FROM
(
	SELECT 
		c.ComputerID,
		c.ComputerCN,
		u.UserCN,
		dbo.OUName(o.OrganizationID) AS OU,
		NumberOfTimesUsedPerComputer = COUNT(*)
	
	FROM 
		ProductContainsSoftware pcs, 
		SoftwareUsagePerWeek su, 
		#Organization o, 
		[User] u, 
		Computer c
	
	WHERE	pcs.SoftwareProductID = @spID
	  AND	pcs.SoftwareVersionID = su.SoftwareID
	  AND	su.ComputerID = c.ComputerID
	  AND	su.UserID = u.UserID
	  AND	o.OrganizationID = c.ComputerOUID -- Always get only the computer OU
	  AND	su.StartOfWeek >= @fromDate
	  AND	su.StartOfWeek <= @tillDate
	
	GROUP BY	
		c.ComputerID,
		c.ComputerCN,
		u.UserCN,
		dbo.OUName(o.OrganizationID)
) AS tab

GROUP BY tab.ComputerID, tab.ComputerCN, tab.OU
ORDER BY TotalNumberOfTimesUsed ASC, UserCount ASC
GO
/* 
 * $Id: LicenseUsageSummaryOfDetailsByUser.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: LicenseUsageSummaryOfDetailsByUser
 *	Input:
 *	@spID, @oudn, @ouMatch
 *
 *	Returns:
 *	UserCN, OU, ComputerCount, TotalNumbeOfTimesUsed
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
 
-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'LicenseUsageSummaryOfDetailsByUser' AND xtype = 'P'
)
	DROP PROCEDURE LicenseUsageSummaryOfDetailsByUser
GO

CREATE PROCEDURE [LicenseUsageSummaryOfDetailsByUser]
	@spID INT, -- Match on license ID
	@oudn VARCHAR(800) = '%',
	@ouMatch BIT=1, --Include sub-Ous 1=True, 0=False
	@fromDate DATETIME = NULL,
	@tillDate DATETIME = NULL
AS

CREATE TABLE #Organization(OrganizationID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0
 
-- SET the dates 
IF @fromDate IS NULL 
	SET @fromDate = (SELECT MIN(StartOfWeek) FROM SoftwareUsagePerWeek)

IF @tillDate IS NULL 
	SET @tillDate = (SELECT MAX(StartOfWeek) FROM SoftwareUsagePerWeek)
	
-- The StartOfWeek represents the start of the week in which usage has been reported 
-- and NOT the day the usage has been reported. 
-- Thus we need to do some processing to map the date ranges (from and till date) back
-- to the start of the week
SET @fromDate = dbo.GetStartOfWeekForDate(@fromDate)
SET @tillDate = dbo.GetStartOfWeekForDate(@tillDate)

/********************************************/

SELECT 
	tab.UserID,
	tab.UserCN,
	tab.OU,
	ComputerCount = COUNT(DISTINCT tab.ComputerCN),
	TotalNumberOfTimesUsed = SUM(tab.NumberOfTimesUsedPerComputer)
FROM
(
	SELECT 
		u.UserID,
		u.UserCN,
		dbo.OUName(o.OrganizationID) AS OU,
		c.ComputerCN,
		NumberOfTimesUsedPerComputer = COUNT(*)
	
	FROM 
		ProductContainsSoftware pcs, 
		SoftwareUsagePerWeek su, 
		#Organization o, 
		[User] u, 
		Computer c
	
	WHERE	pcs.SoftwareProductID = @spID
	  AND	pcs.SoftwareVersionID = su.SoftwareID
	  AND	su.ComputerID = c.ComputerID
	  AND	su.UserID = u.UserID
	  AND	o.OrganizationID = u.UserOUID
	  AND	su.StartOfWeek >= @fromDate
	  AND	su.StartOfWeek <= @tillDate
	
	GROUP BY	
		u.UserID,
		u.UserCN,
		dbo.OUName(o.OrganizationID),
		c.ComputerCN
) AS tab

GROUP BY tab.UserID, tab.UserCN, tab.OU
ORDER BY TotalNumberOfTimesUsed ASC, ComputerCount ASC
GO

/* 
 * $Id: LicenseUsageDetails.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: LicenseUsageDetails
 *	Input:
 *	@spID, @oudn, @ouMatch
 *
 *	Returns:
 *	ComputerCN, UserCN, OU, SoftwareID, SoftwareName, Version, NumbeOfTimesUsed
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
 
-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'LicenseUsageDetails' AND xtype = 'P'
)
	DROP PROCEDURE LicenseUsageDetails
GO

CREATE PROCEDURE [LicenseUsageDetails]
	@spID INT, -- Match on license ID
	@compID INT, -- Match on computer ID
	@fromDate DATETIME = NULL,
	@tillDate DATETIME = NULL
AS

-- SET the dates 
IF @fromDate IS NULL 
	SET @fromDate = (SELECT MIN(StartOfWeek) FROM SoftwareUsagePerWeek)

IF @tillDate IS NULL 
	SET @tillDate = (SELECT MAX(StartOfWeek) FROM SoftwareUsagePerWeek)
	
-- The StartOfWeek represents the start of the week in which usage has been reported 
-- and NOT the day the usage has been reported. 
-- Thus we need to do some processing to map the date ranges (from and till date) back
-- to the start of the week
SET @fromDate = dbo.GetStartOfWeekForDate(@fromDate)
SET @tillDate = dbo.GetStartOfWeekForDate(@tillDate)	
	
	
SELECT 
	c.ComputerCN,
	OU = (o.RDN + ',' + d.DN),
	u.UserCN,
	su.SoftwareID, 
	sv.SoftwareName,
	sv.Version,
	NumberOfTimesUsedPerComputer = COUNT(*)

FROM 
	ProductContainsSoftware pcs, 
	SoftwareUsagePerWeek su, 
	SoftwareVersion sv, 
	Domain d,
	Organization o, 
	[User] u, 
	Computer c

WHERE	pcs.SoftwareProductID = @spID
  AND	pcs.SoftwareVersionID = su.SoftwareID
  AND	su.SoftwareID = sv.SoftwareID
  AND	su.ComputerID = c.ComputerID
  AND	c.ComputerID = @compID
  AND	su.UserID = u.UserID
  AND	o.OrganizationID = c.ComputerOUID
  AND	o.DomainID = d.OrganizationID
  AND	su.StartOfWeek >= @fromDate
  AND	su.StartOfWeek <= @tillDate

GROUP BY	
	c.ComputerCN,
	u.UserCN,
	o.RDN,
	d.DN,
	su.SoftwareID, 
	sv.SoftwareName,
	sv.Version

ORDER BY c.ComputerCN, u.UserCN
GO
/* 
 * $Id: LicenseUsageDetailsByUser.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: LicenseUsageDetailsByUser
 *	Input:
 *	@spID, @oudn, @ouMatch
 *
 *	Returns:
 *	ComputerCN, UserCN, OU, SoftwareID, SoftwareName, Version, NumbeOfTimesUsed
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
 
-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'LicenseUsageDetailsByUser' AND xtype = 'P'
)
	DROP PROCEDURE LicenseUsageDetailsByUser
GO

CREATE PROCEDURE [LicenseUsageDetailsByUser]
	@spID INT, -- Match on license ID
	@userID INT, -- Match on the UserID
	@fromDate DATETIME = NULL,
	@tillDate DATETIME = NULL
AS

-- SET the dates 
IF @fromDate IS NULL 
	SET @fromDate = (SELECT MIN(StartOfWeek) FROM SoftwareUsagePerWeek)

IF @tillDate IS NULL 
	SET @tillDate = (SELECT MAX(StartOfWeek) FROM SoftwareUsagePerWeek)
	
-- The StartOfWeek represents the start of the week in which usage has been reported 
-- and NOT the day the usage has been reported. 
-- Thus we need to do some processing to map the date ranges (from and till date) back
-- to the start of the week
SET @fromDate = dbo.GetStartOfWeekForDate(@fromDate)
SET @tillDate = dbo.GetStartOfWeekForDate(@tillDate)

SELECT 	
	u.UserCN,
	OU = (o.RDN + ',' + d.DN),
	c.ComputerCN,	
	su.SoftwareID, 
	sv.SoftwareName,
	sv.Version,
	NumberOfTimesUsedPerComputer = COUNT(*)

FROM 
	ProductContainsSoftware pcs, 
	SoftwareUsagePerWeek su, 
	SoftwareVersion sv, 
	Domain d,
	Organization o, 
	[User] u, 
	Computer c

WHERE	pcs.SoftwareProductID = @spID
  AND	pcs.SoftwareVersionID = su.SoftwareID
  AND	su.SoftwareID = sv.SoftwareID
  AND	su.ComputerID = c.ComputerID
  AND	u.UserID = @userID
  AND	su.UserID = u.UserID
  AND	o.OrganizationID = u.UserOUID
  AND	o.DomainID = d.OrganizationID
  AND	su.StartOfWeek >= @fromDate
  AND	su.StartOfWeek <= @tillDate

GROUP BY	
	c.ComputerCN,
	u.UserCN,
	o.RDN,
	d.DN,
	su.SoftwareID, 
	sv.SoftwareName,
	sv.Version

ORDER BY u.UserCN, c.ComputerCN
GO
/*
 * $Id: PerLicenseSummary.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: PerLicenseSummary
 *	Input:
 *	@oudn, @ouMatch, @sprodName, @fromDate, @tillDate
 *
 *	Returns:
 *	SoftwareProductID, ProductName, LMName, PublisherName, TrackBy, TotalPurchases, ComputerInstalls, UserInstalls
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'PerLicenseSummary' AND xtype = 'P'
)
	DROP PROCEDURE PerLicenseSummary
GO


CREATE PROCEDURE [PerLicenseSummary]
	@oudn VARCHAR(800) = '%',
	@ouMatch BIT = 1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@sprodName VARCHAR(100) = '%'
AS

CREATE TABLE #Organization(OrganizationID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

SELECT 
	tab.SoftwareProductID,
	tab.ProductName,
	tab.LMName,
	tab.PublisherName,
	tab.TrackBy,
	tab.TotalPurchases,
	tab.ComputerInstalls,
	tab.ComputerOnlyInstalls,
	tab.UserInstalls,
	TotalInstalls = 
	(	CASE WHEN tab.TrackBy = 'computer' 
		THEN tab.ComputerInstalls
		ELSE tab.UserInstalls + ComputerOnlyInstalls
		END
	)

FROM
(
	SELECT
		License.SoftwareProductID,
		License.ProductName,
		License.LMName,
		License.PublisherName,
		License.TrackBy,
		TotalPurchases = 
		(	CASE WHEN License.TotalPurchases IS NULL
			THEN 0
			ELSE License.TotalPurchases
			END
		),		
		-- Count of all computers that have any type of installations on them
		ComputerInstalls = 
		(
			SELECT COUNT (DISTINCT so.ComputerID)
			  FROM	SoftwareOccurrence so, 
				ProductContainsSoftware pcs,
				#Organization o, 
				Computer c
			 WHERE	so.SoftwareID = pcs.SoftwareVersionID
			   AND	c.ComputerOUID = o.OrganizationID
			   AND	so.ComputerID = c.ComputerID
			   AND	pcs.SoftwareProductID = License.SoftwareProductID
		),
		-- Count of installs only for the SYSTEM user (that is computer only installs)
		ComputerOnlyInstalls = 
		(
			SELECT COUNT (DISTINCT so.ComputerID)
			  FROM	SoftwareOccurrence so, 
				ProductContainsSoftware pcs,
				#Organization o, 
				Computer c
			 WHERE	so.SoftwareID = pcs.SoftwareVersionID
			   AND	c.ComputerOUID = o.OrganizationID
			   AND	so.ComputerID = c.ComputerID
			   AND	pcs.SoftwareProductID = License.SoftwareProductID
			   AND	so.UserID = 1 -- Count ONLY the system installs
		),
		-- Count of user based installs (that is user is NOT SYSTEM)
		UserInstalls = 
		(
			SELECT COUNT (DISTINCT so.UserID)
			  FROM	SoftwareOccurrence so,
				ProductContainsSoftware pcs,
				#Organization o, 
				[User] u
			 WHERE	so.SoftwareID = pcs.SoftwareVersionID
			   AND	u.UserOUID = o.OrganizationID
			   AND	so.UserID = u.UserID
			   AND	pcs.SoftwareProductID = License.SoftwareProductID
			   AND	so.UserID <> 1 -- Do not count the system user
		)
	FROM
	(
		SELECT	lic.SoftwareProductID,
			lic.ProductName,
			lic.LMName,
			lic.PublisherName,
			lic.TrackBy,
			SUM(lp.Quantity) AS TotalPurchases
		FROM LicenseFull AS lic
		LEFT OUTER JOIN
		(	SELECT	lp.*
			FROM	LicensePurchase lp,
				#Organization o
			WHERE lp.OrganizationID = o.OrganizationID
		) AS lp
		ON lic.SoftwareProductID = lp.SoftwareProductID
		WHERE ProductName LIKE @sprodName
		GROUP BY
			lic.SoftwareProductID,
			lic.ProductName,
			lic.LMName,
			lic.PublisherName,
			lic.TrackBy
	) AS License
) AS tab
ORDER BY tab.ProductName

GO
/*
 * $Id: PerLicenseUsageSummary.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: PerLicenseUsageSummary
 *	Input:
 *	@oudn, @ouMatch, @sprodName, @fromDate, @tillDate
 *
 *	Returns:
 *	SoftwareProductID, ProductName, LMName, PublisherName, TrackBy, TotalPurchases, TotalUsage
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'PerLicenseUsageSummary' AND xtype = 'P'
)
	DROP PROCEDURE PerLicenseUsageSummary
GO


CREATE PROCEDURE [PerLicenseUsageSummary] 
	@oudn VARCHAR(800) = '%',
	@ouMatch BIT = 1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@sprodName  VARCHAR(100) = '%',
	@fromDate DATETIME = NULL,
	@tillDate DATETIME = NULL
AS

CREATE TABLE #Organization(OrganizationId int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

-- SET the dates 
IF @fromDate IS NULL 
	SET @fromDate = (SELECT MIN(StartOfWeek) FROM SoftwareUsagePerWeek)

IF @tillDate IS NULL 
	SET @tillDate = (SELECT MAX(StartOfWeek) FROM SoftwareUsagePerWeek)

-- The StartOfWeek represents the start of the week in which usage has been reported 
-- and NOT the day the usage has been reported. 
-- Thus we need to do some processing to map the date ranges (from and till date) back
-- to the start of the week
SET @fromDate = dbo.GetStartOfWeekForDate(@fromDate)
SET @tillDate = dbo.GetStartOfWeekForDate(@tillDate)

/********************************************/

SELECT 
	License.SoftwareProductID, 
	License.ProductName, 
	License.LMName, 
	License.PublisherName,
	License.TrackBy,
	TotalPurchases = (CASE WHEN License.TotalPurchases IS NULL THEN 0 ELSE License.TotalPurchases END),
	TotalUsage = 
	(CASE WHEN License.TrackBy = 'Computer' THEN 
		(
			SELECT COUNT (DISTINCT su.ComputerID)
			  FROM	SoftwareUsagePerWeek su, 
				ProductContainsSoftware pcs,
				#Organization o, 
				Computer c
			 WHERE	su.SoftwareID = pcs.SoftwareVersionID
			   AND	c.ComputerOUID = o.OrganizationID
			   AND	su.ComputerID = c.ComputerID
			   AND	pcs.SoftwareProductID = License.SoftwareProductID
			   AND	su.StartOfWeek >= @fromDate
			   AND	su.StartOfWeek <= @tillDate
		)
	 ELSE
		(
			SELECT COUNT (DISTINCT su.UserID)
			  FROM	SoftwareUsagePerWeek su, 
				ProductContainsSoftware pcs,
				#Organization o, 
				[User] u
			 WHERE	su.SoftwareID = pcs.SoftwareVersionID
			   AND	u.UserOUID = o.OrganizationID
			   AND	su.UserID = u.UserID
			   AND	pcs.SoftwareProductID = License.SoftwareProductID
			   AND	su.StartOfWeek >= @fromDate
			   AND	su.StartOfWeek <= @tillDate
		) 
	 END)
FROM
(
	SELECT 
		lic.SoftwareProductID, 
		lic.ProductName, 
		lic.LMName, 
		lic.PublisherName, 
		lic.TrackBy,
		SUM(lp.Quantity) AS TotalPurchases 
	FROM LicenseFull AS lic
	LEFT OUTER JOIN 
	(
		SELECT lp.*
		FROM LicensePurchase lp, #Organization o
		WHERE lp.OrganizationID = o.OrganizationID
	) AS lp
	ON lic.SoftwareProductID = lp.SoftwareProductID     	
	WHERE ProductName LIKE @sprodName
	GROUP BY
		lic.SoftwareProductID, 
		lic.ProductName, 
		lic.LMName, 
		lic.PublisherName,
		lic.TrackBy
) AS License
ORDER BY License.ProductName


GO
/* 
 * $Id: LicensePurchaseSummaryList.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: LicensePurchaseSummaryList
 *	Input:
 *	@oudn, @ouMatch, @sprodName, @expiryFrom, @expiryTo
 *
 *	Returns:
 *	SoftwareProductID, ProductName, LMName, PublisherName, TrackBy, NearestExpiry, NumPurchases, TotalPurchases
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
 
-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'LicensePurchaseSummaryList' AND xtype = 'P'
)
	DROP PROCEDURE LicensePurchaseSummaryList
GO

CREATE PROCEDURE [LicensePurchaseSummaryList] 
	@oudn VARCHAR(800) = '%',
	@ouMatch Bit=1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@sprodName  VARCHAR(100) = '%',
	@expiryFrom DATETIME = NULL,
	@expiryTo DATETIME = NULL
	
AS

-- REVISIT : Need to remove this and pass in the correct value 
--		     for date range as soon as the UI supports taking a date range as an input
SET @expiryFrom = '1970/01/01'
SET @expiryTo = '2070/01/01'

CREATE TABLE #Organization(OrganizationID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

SELECT 
	Licenses.SoftwareProductID,
	Licenses.ProductName,
	Licenses.LMName,
	Licenses.PublisherName,
	Licenses.TrackBy, 
	MIN(Purchases.Expires) AS NearestExpiry,
	COUNT(Purchases.SoftwareProductID) AS NumPurchases,
	SUM(Purchases.Quantity) AS TotalPurchases
FROM
      ( SELECT *  
        FROM LicenseFull 
        WHERE ProductName LIKE @sprodName 
      ) AS Licenses
      LEFT OUTER JOIN
      ( SELECT lp.* 
        FROM LicensePurchase AS lp, #Organization AS o 
        WHERE ((lp.Expires IS NULL) OR (lp.Expires >= @expiryFrom AND lp.Expires <= @expiryTo))
        AND   lp.OrganizationID = o.OrganizationID
      ) AS Purchases
      ON Licenses.SoftwareProductID = Purchases.SoftwareProductID
GROUP BY
	Licenses.SoftwareProductID,
	Licenses.ProductName,
	Licenses.LMName,
	Licenses.PublisherName,
	Licenses.TrackBy
ORDER BY Licenses.ProductName
GO
/* 
 * $Id: LicensePurchaseDetails.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: LicensePurchaseDetails
 *	Input:
 *	@spID, @oudn, @ouMatch, @expiryFrom, @expiryTo
 *
 *	Returns:
 *	SoftwareProductID, ResellerName, OrganizationID, DN, Purchased, Expires, Price, Quantity, OrderNumber
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
 
-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'LicensePurchaseDetails' AND xtype = 'P'
)
	DROP PROCEDURE LicensePurchaseDetails
GO

CREATE PROCEDURE [LicensePurchaseDetails] 
	@spID INT,
	@oudn VARCHAR(800) = '%',
	@ouMatch BIT = 1, --Values:[0=do exact OU Match | 1=include child-OUs in match]	
	@expiryFrom DATETIME = NULL,
	@expiryTo DATETIME = NULL
AS

-- REVISIT : Need to remove this and pass in the correct value 
--		     for date range as soon as the UI supports taking a date range as an input
SET @expiryFrom = '1970/01/01'
SET @expiryTo = '2070/01/01'

PRINT(@spID)

CREATE TABLE #Organization(OrganizationID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

-- Get the purchases
SELECT  
	lp.SoftwareProductID, 
	sr.Name AS ResellerName,
	lp.OrganizationID,
	dbo.OUDomainDN(o.OrganizationID) AS DN,
	lp.Purchased,
	lp.Expires,
	lp.Price,
	lp.Quantity,
	lp.OrderNumber
FROM 
	LicensePurchase AS lp, 
	SoftwareReseller AS sr, 
	#Organization AS o

WHERE  lp.SoftwareProductID = @spID
AND	  ((lp.Expires IS NULL) OR (lp.Expires >= @expiryFrom AND lp.Expires <= @expiryTo))
AND  	  lp.ResellerID = sr.ResellerID
AND  	  lp.OrganizationID = o.OrganizationID
ORDER BY lp.Purchased
GO
/* 
 * $Id: PerOUAllocDetails.sql 95576 2010-01-21 02:54:16Z rlowery $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: PerOULicAllocDetails
 *	Input:
 *	@domainDN, @spID, @ourdn
 *
 *	Returns:
 *	OUID, AllocationID, OU, SoftwareCounrPerOU, NumInstalledForOU, NumAllocForOU, NumPurchasedForOU
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name] = 'PerOULicAllocDetails' AND xtype = 'P'
)
	DROP PROCEDURE PerOULicAllocDetails
GO

CREATE PROCEDURE [PerOULicAllocDetails] 
	@domainDN	VARCHAR(800) = '%',
	@spID		INT = 0,
	@ourdn		VARCHAR(800) = '%'
AS

DECLARE @trackedByID INT
SET @trackedByID = (SELECT TrackedByID FROM SoftwareProduct WHERE SoftwareProductID = @spID)


SELECT
	tab.OUID, 
	tab.AllocationID,
	tab.OU,
	NumInstalledForOU = CASE WHEN tab.InstalledForOU = 0 THEN NULL ELSE tab.InstalledForOU END,
	tab.NumAllocForOU,
	tab.NumPurchasedForOU
FROM
(
	SELECT 
		OUAlloc.OUID,
		OUAlloc.AllocationID,
		OUAlloc.OU,
	
		InstalledForOU = 
		(	CASE WHEN @trackedByID = 1 
			THEN
				(
					-- Count the distinct computers for installations
					-- regardless of whether the software has been installed by 
					-- SYSTEM or some specific user
					SELECT	COUNT(DISTINCT c.ComputerID)
					  FROM	ProductContainsSoftware PCS
						INNER JOIN SoftwareOccurrence AS SofO
						ON PCS.SoftwareVersionID = SofO.SoftwareID
						INNER JOIN Computer AS c
						ON SofO.ComputerID = c.ComputerID
					 WHERE	SoftwareProductID = @spID
					   AND	c.ComputerOUID = OUAlloc.OUID
				)
			ELSE			
				(
					-- Count the distinct users for installations
					-- where the UserID is NOT 1, that is NOT SYSTEM.
					-- These are the user based installs
					SELECT	COUNT(DISTINCT u.UserID)
					  FROM	ProductContainsSoftware PCS
						INNER JOIN SoftwareOccurrence AS SofO
						ON PCS.SoftwareVersionID = SofO.SoftwareID
						INNER JOIN [User] AS u
						ON SofO.UserID = u.UserID
					 WHERE	SoftwareProductID = @spID
					   AND	u.UserOUID = OUAlloc.OUID
					   AND	SofO.UserID <> 1
				)
				+
				(
					-- Count the distinct users for installations
					-- where the UserID is 1, that is SYSTEM.
					-- These are the user based installs
					SELECT	COUNT(DISTINCT c.ComputerID)
					  FROM	ProductContainsSoftware PCS
						INNER JOIN SoftwareOccurrence AS SofO
						ON PCS.SoftwareVersionID = SofO.SoftwareID
						INNER JOIN Computer AS c
						ON SofO.ComputerID = c.ComputerID
					 WHERE	SoftwareProductID = @spID
					   AND	c.ComputerOUID = OUAlloc.OUID
					   AND	SofO.UserID = 1
				)
			END
		),
		NumAllocForOU = 
		(	CASE  WHEN OUAlloc.NumAlloc = 0 THEN NULL
			ELSE OUAlloc.NumAlloc
			END
		),
		NumPurchasedForOU = 
		(	CASE WHEN (OUAlloc.OU = @domainDN) AND (OUAlloc.NumPurchased IS NULL) THEN  0
			WHEN OUAlloc.NumPurchased = 0 THEN NULL
			ELSE OUAlloc.NumPurchased
			END
		)
	FROM
	(	SELECT	SDOU.OUID,
			LicA.AllocationID, 
			(	CASE WHEN SDOU.OU = ''
				THEN @domaindn
				ELSE (@domaindn+','+SDOU.OU)
				END
			) AS OU, 
			(	CASE WHEN SUM(UnitsAllocated) IS NULL
				THEN 0
				ELSE SUM(UnitsAllocated)
				END
			) AS NumAlloc,
			SUM(Quantity) AS NumPurchased
		FROM	(	SELECT	Organization.OrganizationID as OUID,
						RDNReverse AS OU
				FROM	Organization,
					Domain 
				WHERE	Organization.OrganizationID <> 1 
		 		AND	Domain.OrganizationID
						= Organization.DomainID 
			 		AND Domain.DN LIKE @domaindn
					AND RDN LIKE @ourdn 
					AND RDN NOT LIKE 'CN=%'
			) AS SDOU
		LEFT OUTER JOIN (
			SELECT	*
			FROM	LicenseAllocation
			WHERE	SoftwareProductID = @spID
		) AS LicA
			ON SDOU.OUID = LicA.OrganizationID
	
		-- Get the purchase information as ONE single row only
		-- as we do not want multiple rows for each purchase.
		-- Thus we need to summarise the purchase information
		-- here itself, so that only one row per OU appears.
		LEFT OUTER JOIN (
			SELECT	SoftwareProductID,
				OrganizationID,
				SUM(Quantity) AS Quantity
			FROM	LicensePurchase
			WHERE	SoftwareProductID = @spID
			GROUP BY SoftwareProductID, OrganizationID
		) AS LicP
			ON SDOU.OUID = LicP.OrganizationID
		GROUP BY SDOU.OUID, SDOU.OU, LicA.AllocationID
	) AS OUAlloc
	GROUP BY
		OUAlloc.OUID,
		OUAlloc.OU,
		OUAlloc.NumAlloc,
		OUAlloc.NumPurchased,
		OUAlloc.AllocationID 
) AS tab
ORDER BY
	tab.OU

GO
/* 
 * $Id: ManagedDeviceHWSummarySP.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: ManagedDeviceHWSummary
 *	Input:
 * 	- @compID
 *
 *	Returns:
 *	- ComputerID, IPAddress, LastUserName, MACAddress, Memory
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'ManagedDeviceHWSummary' AND xtype = 'P'
)
	DROP PROCEDURE ManagedDeviceHWSummary
GO

CREATE PROCEDURE [ManagedDeviceHWSummary]
	@compID INT
AS
	DECLARE @macAddr nvarchar(32)
	DECLARE @allMacAddrs nvarchar(256)
	DECLARE @ipAddr nvarchar(32)
	DECLARE @allIPAddrs nvarchar(256)
	DECLARE hpropCur CURSOR FOR
		SELECT	DISTINCT CASE WHEN HProp.Property = 'IPAddress' THEN HVal.Value END AS IPAddress,
			CASE WHEN HProp.Property = 'MACAddress' THEN HVal.Value END AS MACAddress
		FROM	HardwareObject AS HObj,
			HardwareValue AS HVal,
			HardwareProperty AS HProp
		WHERE	HObj.ComputerID = @compID
		  AND	HObj.HardwareObjectID = HVal.HardwareObjectID
		  AND	HVal.HardwarePropertyID = HProp.HardwarePropertyID
		  AND	(
				HProp.Property = 'MACAddress'
				OR HProp.Property = 'IPAddress' 
			)

	OPEN hpropCur

	SET @allIPAddrs = ''
	SET @allMacAddrs = ''
	FETCH NEXT FROM hpropCur INTO @ipAddr, @macAddr
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF (NOT(@ipAddr IS NULL))
			SET @allIPAddrs = @allIPAddrs + @ipAddr
		IF (NOT(@macAddr IS NULL))
			SET @allMacAddrs = @allMacAddrs + @macAddr
		FETCH NEXT FROM hpropCur INTO @ipAddr, @macAddr

		IF @@FETCH_STATUS = 0
		BEGIN
			IF (NOT(@ipAddr IS NULL) AND @allIPAddrs <> '')
				SET @allIPAddrs = @allIPAddrs + ', '
			IF (NOT(@macAddr IS NULL) AND @allMacAddrs <> '')
				SET @allMacAddrs = @allMacAddrs + ', '
		END
	END
	CLOSE hpropCur
	DEALLOCATE hpropCur

	SELECT	ComputerID, 
		@allIPAddrs AS IPAddress,
		MAX(CASE WHEN HProp.Property = 'UserName' THEN HVal.Value END) AS LastUserName, 
		@allMacAddrs AS MACAddress,
		MAX(CASE WHEN (HProp.Property = 'TotalPhysicalMemory') OR (HProp.Property = 'TotalVisibleMemorySize') THEN HVal.Value END) AS Memory,
		MAX(CASE WHEN HProp.Property = 'DNSDomain' THEN HVal.Value END) AS DNSDomain,
		MAX(CASE WHEN HProp.Property = 'DNSHostName' THEN HVal.Value END) AS DNSHostName
	FROM	HardwareObject AS HObj,
		HardwareValue AS HVal,
		HardwareProperty AS HProp
	WHERE	HObj.ComputerID = @compID
	  AND	HObj.HardwareObjectID = HVal.HardwareObjectID
	  AND	HVal.HardwarePropertyID = HProp.HardwarePropertyID
	  AND	(
			HProp.Property = 'TotalPhysicalMemory' 
			OR HProp.Property = 'TotalVisibleMemorySize' 
			OR HProp.Property = 'UserName'
			OR HProp.Property = 'DNSDomain'
			OR HProp.Property = 'DNSHostName'
		)
	GROUP BY	HObj.ComputerID

GO

EXEC CopyPermission 'ManagedDeviceHWSummary', 'mgsOSBreakdown'
GO


/* 
 * $Id: ManagedDeviceInstallDetailsSP.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: ManagedDeviceInstallDetails
 *	Input:
 * 	- @compID
 *
 *	Returns:
 *	- ComputerID, PackageName, Version, Result, Reported, InstalledBy, InstalledByID, PolicyAction, EffectiveFrom, PackageFullName
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'ManagedDeviceInstallDetails' AND xtype = 'P'
)
	DROP PROCEDURE ManagedDeviceInstallDetails
GO

CREATE PROCEDURE [ManagedDeviceInstallDetails]
	@compID INT,
	@userInfo BIT = NULL
AS


-- Get the installation status for the computer for "all user" installs (ie installs for the machine)
SELECT	InS.ComputerID, 
	InS.PackageName AS PackageName, 
	InS.Version, 
	InS.Result, 
	InS.Reported,
	[User].UserCN AS InstalledBy,
	InS.UserID AS InstalledByID,
	CASE 
		WHEN ad.EffectiveFrom > GETDATE() AND InS.Result ='success' THEN 'early'
		WHEN InS.[Action] = 'residual'
		OR (PaApp.TargetID IS NULL AND InS.Action = 'installne')
			THEN 'residual'
		WHEN InS.[Action] = 'redundant'
		OR (PaApp.TargetID IS NULL AND InS.Action = 'installex')
			THEN 'redundant'
		WHEN ad.[Action] IS NULL THEN 'Null'
		ELSE ad.[Action] 
	END AS PolicyAction,
	CASE WHEN ad.EffectiveFrom IS NULL THEN '' ELSE CAST(ad.EffectiveFrom AS VARCHAR(20)) END AS EffectiveFrom,
	-- LOCALIZE !!
	CASE WHEN PaV.PackageFullName IS NULL THEN '<not in software library>' ELSE PaV.PackageFullName END AS PackageFullName
FROM 	
	(SELECT InS.*, pf.PackageName, pv.Version 
	    FROM Installation AS InS, PackageVersion pv, PackageFamily pf
	 WHERE InS.ComputerID = @compID 
	       AND InS.UserID = 1 
	       AND (@userInfo IS NULL OR @userInfo = 0)
	       AND InS.PackageVersionID = pv.PackageVersionID
	       AND pv.PackageFamilyID = pf.PackageFamilyID
	) AS InS
	INNER JOIN [User]
		ON InS.UserID = [User].UserID
	LEFT OUTER JOIN PackageVersionFull AS PaV
		ON InS.PackageVersionID = PaV.PackageVersionID
		AND PaV.MediaID = 1 -- packaged that are only in the Warehouse/SL 
	LEFT OUTER JOIN PackageApplies AS PaApp
		ON PaApp.PackagePathID = PaV.PackagePathID
		AND (
			(PaApp.TargetTypeID = 1 -- Computers
				AND InS.ComputerID = PaApp.TargetID)
			OR (PaApp.TargetTypeID = 3
				AND InS.UserID IN (
					SELECT	m.TargetID
					FROM	Member AS m
					WHERE	m.GroupID = PaApp.TargetID
					  AND	m.TargetTypeID = 1
				)
			)
		)
	LEFT OUTER JOIN AllocationDetails AS ad
		ON PaApp.AllocationDetailsID = ad.AllocationDetailsID
UNION
-- Get the packages that this computer should get, but has not installed as yet
SELECT	ComputerID = @compID, 
	PaV.PackageName AS PackageName, 
	PaV.Version, 
	Result = 'not installed', -- LOCALIZE !!
	Reported = null,
	InstalledBy = null,
	InstalledByID = null,
	CASE 
	WHEN	TaP.EffectiveFrom > GETDATE() AND TaP.[Action] = 'install' THEN 'scheduled'
	WHEN	TaP.[Action] IS NULL THEN 'out of policy'
	WHEN	TaP.[Action] = 'alwaysupdate' THEN 
		CASE
		WHEN EXISTS(
			SELECT * 
			FROM	Installation ins,
				PackageVersion v,
				PackageFamily f
			WHERE	ins.PackageVersionID = v.PackageVersionID
			  AND	v.PackageFamilyID = f.PackageFamilyID
			  AND	f.PackageName = PaV.PackageName
			  AND	ins.ComputerID = TaP.TargetID
			  AND	ins.OrganizationID = TaP.TargetOUID
			  AND	ins.UserID = 1
			)
			THEN 'alwaysupdate'
		ELSE 'choose' 
		END		
	ELSE TaP.[Action] 
	END AS PolicyAction,
	CASE WHEN TaP.EffectiveFrom IS NULL THEN '' ELSE CAST(TaP.EffectiveFrom AS VARCHAR(20)) END AS EffectiveFrom,
	-- LOCALIZE !!
	CASE WHEN PaV.PackageFullName IS NULL THEN '<not in software library>' ELSE PaV.PackageFullName END AS PackageFullName
FROM 	
	(SELECT	@compID AS TargetID,
		c.ComputerOUID AS TargetOUID,
		pa.PackagePathID,
		ad.[Action],
		ad.EffectiveFrom
	FROM	PackageApplies as pa,
		AllocationDetails AS ad,
		Computer AS c
	WHERE (
			(pa.TargetTypeID = 1 -- Computers
				AND pa.TargetID = @compID)
			OR (pa.TargetTypeID = 3
				AND EXISTS (
					SELECT	m.TargetID
					FROM	Member AS m
					WHERE	m.GroupID = pa.TargetID
					  AND	m.TargetTypeID = 1
					  AND	m.TargetID = @compID
				)
			)
		)
	  AND	pa.AllocationDetailsID = ad.AllocationDetailsID
	  AND	c.ComputerID = @compID
	) AS TaP
	LEFT OUTER JOIN PackageVersionFull AS PaV
		ON TaP.PackagePathID = PaV.PackagePathID
		AND PaV.MediaID = 1 -- packaged that are only in the Warehouse/SL

WHERE PaV.PackageVersionID NOT IN 
	(
		SELECT	DISTINCT PackageVersionID 
		FROM	Installation
		WHERE	ComputerID = @compID 
		  AND	UserID = 1
	)

UNION 
-- Get the installations by users on this computer 
SELECT	InS.ComputerID, 
	InS.PackageName AS PackageName, 
	InS.Version, 
	InS.Result, 
	InS.Reported,
	[User].UserCN AS InstalledBy,
	InS.UserID AS InstalledByID,
	CASE 
		WHEN ad.EffectiveFrom > GETDATE() AND InS.Result ='success' THEN 'early'
		WHEN InS.[Action] = 'residual'
		OR (PaApp.TargetID IS NULL AND InS.Action = 'installne')
			THEN 'residual'
		WHEN InS.[Action] = 'redundant'
		OR (PaApp.TargetID IS NULL AND InS.Action = 'installex')
			THEN 'redundant'
		WHEN ad.[Action] IS NULL THEN 'Null'
		ELSE ad.[Action] 
	END AS PolicyAction,
	CASE WHEN ad.EffectiveFrom IS NULL THEN '' ELSE CAST(ad.EffectiveFrom AS VARCHAR(20)) END AS EffectiveFrom,
	-- LOCALIZE !!
	CASE WHEN PaV.PackageFullName IS NULL THEN '<not in software library>' ELSE PaV.PackageFullName END AS PackageFullName
FROM 	
	(SELECT InS.*, pf.PackageName, pv.Version 
	    FROM Installation AS InS, PackageVersion pv, PackageFamily pf
	 WHERE InS.ComputerID = @compID 
	       AND InS.UserID <> 1
	       AND (@userInfo IS NULL OR @userInfo = 1)
	       AND InS.PackageVersionID = pv.PackageVersionID
	       AND pv.PackageFamilyID = pf.PackageFamilyID
	) AS InS
	INNER JOIN [User]
		ON InS.UserID = [User].UserID
	LEFT OUTER JOIN PackageVersionFull AS PaV
		ON InS.PackageVersionID = PaV.PackageVersionID
		AND PaV.MediaID = 1 -- packaged that are only in the Warehouse/SL
	LEFT OUTER JOIN PackageApplies AS PaApp
		ON PaApp.PackagePathID = PaV.PackagePathID
		AND (
			(PaApp.TargetTypeID = 2 -- Users
				AND InS.UserID = PaApp.TargetID)
			OR (PaApp.TargetTypeID = 3
				AND InS.UserID IN (
					SELECT	m.TargetID
					FROM	Member AS m
					WHERE	m.GroupID = PaApp.TargetID
					  AND	m.TargetTypeID = 2
				)
			)
		)
	LEFT OUTER JOIN AllocationDetails AS ad
		ON PaApp.AllocationDetailsID = ad.AllocationDetailsID

GO

EXEC CopyPermission 'ManagedDeviceInstallDetails', 'mgsOSBreakdown'
GO
-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'ManagedDeviceSummaryList' AND xtype = 'P'
)
	DROP PROCEDURE ManagedDeviceSummaryList
GO

CREATE PROCEDURE [ManagedDeviceSummaryList]
	@oudn VARCHAR(800)='%', --OUs
	@ouMatch BIT=1, --Match on OUs include sub-OUs [True=1|False=0]
	@compCN Varchar(128)='%' -- computer name (size=64*2 --to take into acct encoded chars)
AS
BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0
	
	SELECT
		Com.ComputerID, 
		ComputerCN, 
		OperatingSystemName AS OperatingSystem, 
		MAX(InR.SWDate) AS SWDate,
		MAX(InR.HWDate) AS HWDate,
		MAX(InR.FilesDate) AS FilesDate,
		MAX(InR.ServicesDate) AS ServicesDate,
		COUNT(InS.Result) AS InstallFailures,
		dbo.OUName(s.OUID) AS OU
	FROM #Organization AS s
		INNER JOIN (SELECT * FROM Computer WHERE ComputerCN LIKE @compCN)  AS Com
			ON (Com.ComputerOUID = s.OUID)
		LEFT OUTER JOIN OperatingSystem AS Os
			ON Com.OperatingSystemID = Os.OperatingSystemID
		LEFT OUTER JOIN InventoryReport AS InR
			ON (Com.ComputerID = InR.ComputerID AND InR.UserID = 1)
		LEFT OUTER JOIN Installation AS InS
			ON Ins.Result ='failure' AND InS.ComputerID = Com.ComputerID
	GROUP BY Com.ComputerID, Com.ComputerCN, dbo.OUName(s.OUID), Os.OperatingSystemName
	ORDER BY Com.ComputerCN

END

/* 
 * $Id: ManagedDeviceSummaryListSP.sql 90554 2008-12-02 04:49:18Z vcolquho $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: ManagedDeviceSummaryList
 *	Input:
 * 	- @oudn, @ouMatch, @compCN
 *
 *	Returns:
 *	- ComputerID, ComputerCN, OU, OperatingSystem, 
 *	- SWDate, HWDate, FilesDate, ServicesDate,
 *	- InstallFailures
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
GO

EXEC CopyPermission 'ManagedDeviceSummaryList', 'mgsOSBreakdown'
GO
-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'UserSummaryList' AND xtype = 'P'
)
	DROP PROCEDURE UserSummaryList
GO

CREATE PROCEDURE [UserSummaryList]
	@oudn VARCHAR(800)='%', --OUs
	@ouMatch BIT=1, --Match on OUs include sub-OUs [True=1|False=0]
	@userCN Varchar(128)='%' -- computer name (size=64*2 --to take into acct encoded chars)
AS
BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

	SELECT	
		Usr.UserID, 
		UserCN, 
		Usr.SAMAccountName,
		MAX(InR.SWDate) AS SWDate,
		InstallFailures = (SELECT COUNT(Result) FROM Installation WHERE Result ='failure' AND UserID = Usr.UserID),
		COUNT(DISTINCT InR.ComputerID) AS ComputersVisited,
		dbo.OUName(SDOU.OUID) AS OU

	FROM #Organization AS SDOU 
		INNER JOIN (SELECT * FROM [User] WHERE UserCN LIKE @userCN) AS Usr
			ON (Usr.UserOUID = SDOU.OUID)
		LEFT OUTER JOIN (SELECT * FROM InventoryReport WHERE UserID <> 1) AS InR
			ON (Usr.UserID = InR.UserID)

	GROUP BY Usr.UserID, Usr.UserCN, Usr.SAMAccountName, dbo.OUName(SDOU.OUID)
	ORDER BY Usr.UserCN

END

/* 
 * $Id: UserSummaryListSP.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: UserSummaryList
 *	Input:
 * 	- @oudn, @ouMatch, @userCN
 *
 *	Returns:
 *	- UserID, UserCN, SAMAccountName, OperatingSystem, SWDate, InstallFailures, ComputersVisited, OU
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
GO

EXEC CopyPermission 'UserSummaryList', 'mgsOSBreakdown'
GO
-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'UserComputerList' AND xtype = 'P'
)
	DROP PROCEDURE UserComputerList
GO

CREATE PROCEDURE [UserComputerList]
	@userID INT
AS
	SELECT	
		Com.ComputerID, 
		Com.ComputerCN,
		Os.OperatingSystemName AS OperatingSystem,
		COUNT(InS.Result) AS InstallFailures,
		MAX(InR.SWDate) AS LatestSWDate,
		SD.OU

	FROM	(SELECT DISTINCT ComputerID, SWDate FROM InventoryReport WHERE UserID = @userID) AS InR		 
		INNER JOIN Computer AS Com
			ON (Com.ComputerID = InR.ComputerID)			
		INNER JOIN (
						SELECT	o.OrganizationID as OUID,
										CASE
										    WHEN o.RDN IS NULL THEN	-- Unknown OU in this domain
											'<NULL>,'+d.DN		-- or the universal domain
										    WHEN o.RDN = '' THEN
										    	d.DN			-- DomainDN for the domain
										    ELSE
										    	o.RDN+','+d.DN		-- Ordinary OU or container
										END AS OU
					FROM Organization AS o, Domain AS d
					WHERE o.DomainID = d.OrganizationID) as SD
			ON Com.ComputerOUID = SD.OUID		
		LEFT OUTER JOIN OperatingSystem AS Os
			ON Com.OperatingSystemID = Os.OperatingSystemID	
		LEFT OUTER JOIN (SELECT * FROM Installation WHERE UserID = @userID AND Result ='failure') AS InS
			ON InS.ComputerID = Com.ComputerID

	GROUP BY Com.ComputerID, Com.ComputerCN, Os.OperatingSystemName, SD.OU
	ORDER BY LatestSWDate DESC  -- Latest first
	
/* 
 * $Id: UserComputerListSP.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: UserComputerList
 *	Input:
 * 	- @userID
 *
 *	Returns:
 *	- ComputerID, ComputerCN, OperatingSystem, InstallFailures, OU
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */
GO

EXEC CopyPermission 'UserComputerList', 'mgsOSBreakdown'
GO
-- USE MANAGESOFT
GO

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'UserInstallDetails' AND xtype = 'P'
)
	DROP PROCEDURE UserInstallDetails
GO


CREATE PROCEDURE [UserInstallDetails]
	@userID INT
AS
SELECT
	UserID = @userID,
	InS.PackageName AS PackageName, 
	InS.Version, 
	CASE 
		WHEN ad.EffectiveFrom > GETDATE() AND InS.Result ='success' THEN 'early'
		WHEN InS.[Action] = 'residual'
		OR (InS.[Action] = 'installne' AND PaApp.TargetID IS NULL)
			THEN 'residual'
		WHEN InS.[Action] = 'redundant'
		OR (InS.[Action] = 'installex' AND PaApp.TargetID IS NULL)
			THEN 'redundant'
		WHEN ad.[Action] IS NULL THEN 'Null'
		ELSE ad.[Action] 
	END AS PolicyAction,
	CASE WHEN ad.EffectiveFrom IS NULL THEN '' ELSE CAST(ad.EffectiveFrom AS VARCHAR(20)) END AS EffectiveFrom,
	InS.Result, 
	InS.Reported,
	InS.ComputerID AS InstalledOnID, 
	Com.ComputerCN AS InstalledOn,
	-- LOCALIZE !!
	CASE WHEN PaV.PackageFullName IS NULL THEN '<not in software library>' ELSE PaV.PackageFullName END AS PackageFullName
FROM 	
	(SELECT InS.*, pf.PackageName, pv.Version 
	    FROM Installation AS InS, PackageVersion pv, PackageFamily pf
	 WHERE InS.UserID = @userID
	       AND InS.PackageVersionID = pv.PackageVersionID
	       AND pv.PackageFamilyID = pf.PackageFamilyID
	) AS InS
	INNER JOIN [User]
		ON InS.UserID = [User].UserID
	INNER JOIN Computer AS Com
		ON InS.ComputerID = Com.ComputerID
	LEFT OUTER JOIN PackageVersionFull AS PaV
		ON InS.PackageVersionID = PaV.PackageVersionID
		AND PaV.MediaID = 1 -- packaged that are only in the Warehouse/SL
	LEFT OUTER JOIN PackageApplies AS PaApp
		ON PaApp.PackagePathID = PaV.PackagePathID
		AND (
			(PaApp.TargetTypeID = 2 -- Users
				AND InS.UserID = PaApp.TargetID)
			OR (PaApp.TargetTypeID = 3
				AND InS.UserID IN (
					SELECT	m.TargetID
					FROM	Member AS m
					WHERE	m.GroupID = PaApp.TargetID
					  AND	m.TargetTypeID = 2
				)
			)
		)
	LEFT OUTER JOIN AllocationDetails AS ad
		ON PaApp.AllocationDetailsID = ad.AllocationDetailsID
UNION 

SELECT	
	UserID = @userID,
	PaV.PackageName AS PackageName, 
	PaV.Version,
	CASE 
		WHEN TaP.EffectiveFrom > GETDATE() AND TaP.[Action] = 'install' THEN 'scheduled'
		WHEN TaP.[Action] IS NULL THEN 'Null'
		ELSE TaP.[Action] 
	END AS PolicyAction,
	CASE WHEN TaP.EffectiveFrom IS NULL THEN '' ELSE CAST(TaP.EffectiveFrom AS VARCHAR(20)) END AS EffectiveFrom,
	Result = 'not installed',  
	Reported = null,
	InstalledOnID = null, 
	InstalledOn = '',
	-- LOCALIZE !!
	CASE WHEN PaV.PackageFullName IS NULL THEN '<not in software library>' ELSE PaV.PackageFullName END AS PackageFullName
FROM	
	(SELECT	pa.PackagePathID,
		ad.[Action],
		ad.EffectiveFrom
	FROM	PackageApplies as pa,
		AllocationDetails AS ad
	WHERE	(
			(pa.TargetTypeID = 2 -- Users
				AND pa.TargetID = @userID)
			OR (pa.TargetTypeID = 3
				AND EXISTS (
					SELECT	m.TargetID
					FROM	Member AS m
					WHERE	m.GroupID = pa.TargetID
					  AND	m.TargetTypeID = 2
					  AND	m.TargetID = @userID
				)
			)
		)
	  AND	pa.AllocationDetailsID = ad.AllocationDetailsID
	) AS TaP
	LEFT OUTER JOIN PackageVersionFull AS PaV
		ON TaP.PackagePathID = Pav.PackagePathID
		AND PaV.MediaID = 1 -- packaged that are only in the Warehouse/SL

WHERE PaV.PackageVersionID NOT IN 
	(
		SELECT DISTINCT PackageVersionID
		FROM Installation
		WHERE UserID = @userID
	)


/* 
 * $Id: UserInstallDetailsSP.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: UserInstallDetails
 *	Input:
 * 	- @userID
 *
 *	Returns:
 *	- UserID, PackageName, Version, Result, Reported, PolicyAction, EffectiveFrom, InstalledOn, InstalledOnID, PackageFullName
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2003 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

GO


EXEC CopyPermission 'UserInstallDetails', 'mgsOSBreakdown'
GO
-- USE ManageSoft
GO
--
-- Stored procedures
--
--
--


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'RPMPackageExists' AND xtype = 'P'
)
        DROP PROCEDURE RPMPackageExists
GO

CREATE PROCEDURE [RPMPackageExists]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64)
AS

	SELECT	PackagePath.PackageFullName, PackageVersion.Category
	FROM 	PackageVersion, PackagePath, PackageFamily, MediaContainsPackageVersion, Media, MediaType
	WHERE	PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND	PackagePath.PackageFullName is not NULL
	  AND	PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND	PackageFamily.PackageName = @l_name
	  AND	PackageVersion.Version = @l_version
	  AND	PackageVersion.[Update] = @l_release
	  AND	PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND	MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND	Media.MediaTypeID = MediaType.MediaTypeID
	  AND	MediaType.[Description] = 'Warehouse'

GO

CopyPermission 'RPMPackageExists', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'UnixGetPackageArchitectures' AND xtype = 'P'
)
        DROP PROCEDURE UnixGetPackageArchitectures
GO

CREATE PROCEDURE [UnixGetPackageArchitectures]
	@l_path nvarchar(256)
AS
	SELECT ArchitectureName
	FROM PackageVersion, PackagePath, Architecture, PackageVersionArchitecture
	WHERE PackagePath.PackageFullName = @l_path
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackageVersionArchitecture.PackageVersionID = PackageVersion.PackageVersionID
	  AND Architecture.ArchitectureID = PackageVersionArchitecture.ArchitectureID
GO

CopyPermission 'UnixGetPackageArchitectures', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'UnixPackageGet' AND xtype = 'P'
)
        DROP PROCEDURE UnixPackageGet
GO


CREATE PROCEDURE [UnixPackageGet]
	@l_packageFullName nvarchar(256),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_packageFamily nvarchar(64)
AS
	
	SELECT PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath, PackageFamily
	WHERE PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName = @l_packageFullName
	  AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageFamily.PackageName = @l_packageFamily
	  AND PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
GO

CopyPermission 'UnixPackageGet', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'MediaPackageVersionGet' AND xtype = 'P'
)
        DROP PROCEDURE MediaPackageVersionGet
GO

CREATE PROCEDURE [MediaPackageVersionGet]
	@p_name nvarchar(64),
	@p_version nvarchar(64),
	@l_release nvarchar(64),
	@p_path nvarchar(256)
AS

	SELECT PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath, PackageFamily
	WHERE PackageVersion.Version = @p_version
	   AND PackageVersion.[Update] = @l_release
	   AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	   AND PackageFamily.PackageName = @p_name
	   AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	   AND PackagePath.PackageFullName = @p_path

GO

CopyPermission 'MediaPackageVersionGet', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'MediaRPMPackageUpdate' AND xtype = 'P'
)
        DROP PROCEDURE MediaRPMPackageUpdate
GO

CREATE PROCEDURE [MediaRPMPackageUpdate]
	@p_name nvarchar(64),
	@p_version nvarchar(64),
	@p_release nvarchar(64),
	@p_group nvarchar(128),
	@p_path nvarchar(256),
	@p_media_type nvarchar(128), -- description from the mediatype table
	@p_media_location nvarchar(256), -- location from the media table
	@p_media_title nvarchar(128) -- title from the media table
AS

	DECLARE @l_MediaID int
	DECLARE @l_FamilyID int
	DECLARE @l_PackageVersionID int
	DECLARE @l_PackagePathID int

	-- update the media table, storing the media ID
	IF NOT EXISTS (
		SELECT *
		FROM Media
		WHERE Media.Title = 'RPM Media'
	)
	BEGIN
		EXEC MediaInsert 'RPM Media', NULL, @p_media_type
	END
	
	SELECT @l_MediaID = Media.MediaID
	FROM Media, MediaType
	WHERE Media.Title = 'RPM Media'
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = @p_media_type

	-- update the MediaPackageFamily table
	EXEC @l_FamilyID = PackageFamilyBind @p_name
	
	-- update the PackagePath table
	EXEC @l_PackagePathID = PackagePathBind @p_path, NULL

	IF NOT EXISTS (
		SELECT *
		FROM PackageVersion, PackagePath
		WHERE PackageVersion.PackageFamilyID = @l_FamilyID
		  AND PackageVersion.Version = @p_version
		  AND PackageVersion.[Update] = @p_release
		  AND PackageVersion.PackagePathID = @l_PackagePathID
	)
	BEGIN
		INSERT INTO PackageVersion
		(PackagePathID, Version, [Update], PackageFamilyID, Title, Category)
		VALUES
		(@l_PackagePathID, @p_version, @p_release, @l_FamilyID, @p_name, @p_group)
	END	

	SELECT @l_PackageVersionID = PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath
	WHERE PackageVersion.PackageFamilyID = @l_FamilyID
	  AND PackageVersion.Version = @p_version
	  AND PackageVersion.[Update] = @p_release
	  AND PackageVersion.PackagePathID = @l_PackagePathID
	
	-- update the MediaContainsPackageVersion table
	IF NOT EXISTS (
		SELECT *
		FROM MediaContainsPackageVersion
		WHERE MediaID = @l_MediaID
		  AND PackageVersionID = @l_PackageVersionID
	)
	BEGIN
		EXEC MediaContainsPackageVersionAdd
			@l_MediaID, @l_PackageVersionID
	END
GO

CopyPermission 'MediaRPMPackageUpdate', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'MediaInsert' AND xtype = 'P'
)
        DROP PROCEDURE MediaInsert
GO

CREATE PROCEDURE [MediaInsert]
	@p_title nvarchar(128),
	@p_location nvarchar(256),
	@p_type nvarchar(128)
AS

	DECLARE @l_typeID int
	
	-- obtain the media type id
	EXEC MediaTypeInsert @p_type

	SELECT @l_typeID = MediaTypeID
	FROM MediaType
	WHERE Description = @p_type

	IF NOT EXISTS (
		SELECT MediaID
		FROM Media
		WHERE Title = @p_title
		  AND Location = @p_location
		  AND MediaTypeID = @l_typeID
	)
	BEGIN
		INSERT INTO Media
		(Title, Location, MediaTypeID)
		VALUES
		(@p_title, @p_location, @l_typeID)
	END
GO

CopyPermission 'MediaInsert', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'MediaTypeInsert' AND xtype = 'P'
)
        DROP PROCEDURE MediaTypeInsert

GO

CREATE PROCEDURE [MediaTypeInsert]
	@p_description nvarchar(128)
AS

	IF NOT EXISTS (
		SELECT MediaTypeID
		FROM MediaType
		WHERE [Description] = @p_description
	)
	BEGIN
		INSERT INTO MediaType
		([Description])
		VALUES
		(@p_description)
	END
GO

CopyPermission 'MediaTypeInsert', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'RequiresInsert' AND xtype = 'P'
)
        DROP PROCEDURE RequiresInsert
GO

CREATE PROCEDURE [RequiresInsert]
	@l_id int,
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_flags int,
	@l_reqdType char(8)
AS

	EXEC PackageFamilyBind @l_name

	IF NOT EXISTS(
		SELECT * 
		FROM PackageRequires
		WHERE PackageVersionID = @l_id 
		  AND RequiredType = @l_reqdType
		  AND RequiredObject = @l_name
	)
	BEGIN
		EXEC PackageRequiresAdd
			@l_id, 
			@l_reqdType,
			@l_name, 
			NULL, 		--default value
			'Version', 	--default value
			@l_version,
			@l_flags
		
	END

GO

CopyPermission 'RequiresInsert', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'MediaRequiresInsert' AND xtype = 'P'
)
        DROP PROCEDURE MediaRequiresInsert
GO

CREATE PROCEDURE [MediaRequiresInsert]
	@l_id int,
	@l_reqdType char(8),
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_flags int
AS

	DECLARE @l_required int
	DECLARE @l_familyName nvarchar(64)

	EXEC @l_required = PackageFamilyBind @l_name
	SELECT @l_familyName = PackageName
	FROM PackageFamily
	WHERE PackageFamilyID = @l_required

	IF NOT EXISTS(
		SELECT *
		FROM PackageRequires
		WHERE PackageVersionID = @l_id 
		  AND RequiredType = @l_reqdType
		  AND [Value] = @l_version 
		  AND [Match] = @l_flags
		  AND RequiredObject = @l_familyName
	)
	BEGIN
		EXEC PackageRequiresAdd
			@l_id,
			@l_reqdType,
			@l_familyName,
			NULL,
			'Version',
			@l_version,
			@l_flags
	END

GO

CopyPermission 'MediaRequiresInsert', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'ProvidesInsert' AND xtype = 'P'
)
        DROP PROCEDURE ProvidesInsert
GO

CREATE PROCEDURE [ProvidesInsert]
	@l_id int,
	@l_name nvarchar(64),
	@l_version nvarchar(64)
AS
	DECLARE	@l_packageFamilyID int

	EXEC @l_packageFamilyID = PackageFamilyBind @l_name

	IF NOT EXISTS(SELECT * 
		FROM PackageProvides
		WHERE PackageVersionID = @l_id 
		  AND Version = @l_version 
		  AND PackageFamilyID = @l_packageFamilyID
	)
	BEGIN
		EXEC PackageProvidesAdd
			@l_id,
			@l_packageFamilyID,
			@l_version
	END

GO

CopyPermission 'ProvidesInsert', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'MediaProvidesInsert' AND xtype = 'P'
)
        DROP PROCEDURE MediaProvidesInsert
GO

CREATE PROCEDURE [MediaProvidesInsert]
	@l_id int,
	@l_name nvarchar(64),
	@l_version nvarchar(64)
AS

	DECLARE @l_packageId int
	
	EXEC @l_packageId = PackageFamilyBind @l_name
	
	IF NOT EXISTS(SELECT * 
		FROM PackageProvides
		WHERE PackageVersionID = @l_id 
		  AND PackageFamilyID = @l_packageId
		  AND Version = @l_version 
	)
	BEGIN
		EXEC PackageProvidesAdd
			@l_id,
			@l_packageId,
			@l_version
	END
GO

CopyPermission 'MediaProvidesInsert', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'PackageRequiresGet' AND xtype = 'P'
)
        DROP PROCEDURE PackageRequiresGet
GO

CREATE PROCEDURE [PackageRequiresGet]
	@l_path nvarchar(512)
AS

	SELECT PackageRequires.RequiredObject as PackageName, PackageRequires.[Value], PackageRequires.[Match]
	FROM PackageFamily, PackageRequires, PackageVersion, PackagePath, MediaContainsPackageVersion, Media, MediaType
	WHERE PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName = @l_path
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'Warehouse'
	  AND PackageVersion.PackageVersionID = PackageRequires.PackageVersionID
	  AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID

GO

CopyPermission 'PackageRequiresGet', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'MediaRequiresGet' AND xtype = 'P'
)
        DROP PROCEDURE MediaRequiresGet
GO

CREATE PROCEDURE [MediaRequiresGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_file nvarchar(256)
AS

	SELECT PackageRequires.RequiredObject as PackageName, PackageRequires.[Value], PackageRequires.[Match]
	FROM PackageVersion, PackageFamily, PackageRequires, PackagePath, MediaContainsPackageVersion, Media
	WHERE PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
	  AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageFamily.PackageName = @l_name
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.Title = 'RPM Media'
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName = @l_file
	  AND PackageVersion.PackageVersionID = PackageRequires.PackageVersionID
	
GO

CopyPermission 'MediaRequiresGet', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'PackageProvidesGet' AND xtype = 'P'
)
        DROP PROCEDURE PackageProvidesGet
GO

CREATE PROCEDURE [PackageProvidesGet]
	@l_path nvarchar(512)
AS

	DECLARE	@l_PackageVersionID int

	SELECT @l_PackageVersionID = PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath, MediaContainsPackageVersion, Media, MediaType
	WHERE PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName = @l_path
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'Warehouse'

	SELECT PackageFamily.PackageName, PackageProvides.Version
	FROM PackageProvides, PackageFamily
	WHERE PackageProvides.PackageVersionID = @l_PackageVersionID
	  AND PackageProvides.PackageFamilyID = PackageFamily.PackageFamilyID

GO

CopyPermission 'PackageProvidesGet', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'MediaProvidesGet' AND xtype = 'P'
)
        DROP PROCEDURE MediaProvidesGet
GO

CREATE PROCEDURE [MediaProvidesGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_file nvarchar(256)
AS
	DECLARE @l_versionid int

	SELECT @l_versionid = PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath, MediaContainsPackageVersion, Media, PackageFamily
	WHERE PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.Title = 'RPM Media'
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName= @l_file

	SELECT PackageFamily.PackageName, PackageProvides.Version
	FROM PackageProvides, PackageFamily
	WHERE PackageProvides.PackageVersionID = @l_versionid
	  AND PackageProvides.PackageFamilyID = PackageFamily.PackageFamilyID

GO

CopyPermission 'MediaProvidesGet', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'PackageDependenciesGet' AND xtype = 'P'
)
        DROP PROCEDURE PackageDependenciesGet
GO

CREATE PROCEDURE [PackageDependenciesGet]
	@l_path nvarchar(512)
AS

	DECLARE	@l_PackageVersionID int

	SELECT @l_PackageVersionID = PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath, MediaContainsPackageVersion, Media, MediaType
	WHERE PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName = @l_path
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'Warehouse' -- Warehouse ID

	-- get the packages that implement the requirements
	SELECT 	PackageFamily.PackageName, PackageVersion.Version, PackageVersion.[Update]
	FROM 	PackageVersion, PackageFamily
	WHERE 	PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND 	PackageVersion.PackageVersionID IN
	(
		SELECT 	PackageProvides.PackageVersionID
		FROM 	PackageProvides, PackageFamily,
			PackageVersion, MediaContainsPackageVersion, Media, MediaType
		WHERE 	PackageProvides.PackageFamilyID = PackageFamily.PackageFamilyID
		  AND 	PackageFamily.PackageName IN
		  (
			-- get the requirements of the specified package
			SELECT RequiredObject
			FROM PackageRequires
			WHERE PackageRequires.PackageVersionID = @l_PackageVersionID
		  )
		  AND PackageProvides.PackageVersionID = PackageVersion.PackageVersionID
		  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
		  AND MediaContainsPackageVersion.MediaID = Media.MediaID
		  AND Media.MediaTypeID = MediaType.MediaTypeID
		  AND MediaType.[Description] = 'Warehouse'
	)
GO

CopyPermission 'PackageDependenciesGet', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'MediaPackageDependenciesGet' AND xtype = 'P'
)
        DROP PROCEDURE MediaPackageDependenciesGet
GO

CREATE PROCEDURE [MediaPackageDependenciesGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_file nvarchar(256)
AS
	--get all the packages that implement the requirements of the specified package
	SELECT PackageFamily.PackageName, PackageVersion.Version, PackageVersion.[Update]
	FROM PackageVersion, PackageFamily
	WHERE PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageVersion.PackageVersionID IN
	  (
		SELECT DISTINCT PackageProvides.PackageVersionID
		FROM PackageProvides, PackageVersion, MediaContainsPackageVersion, Media, MediaType
		WHERE PackageProvides.PackageFamilyID IN
		(
			-- Obtain all the requirements of the specified package
			SELECT 	PackageFamilyID
			FROM 	PackageRequires, PackageFamily
			WHERE 	PackageRequires.RequiredObject = PackageName
			  AND 	PackageRequires.PackageVersionID IN
			(
				-- Obtain packageversion id that satisfies this criteria
				SELECT 	PackageVersion.PackageVersionID 
				FROM	PackageVersion, PackagePath, PackageFamily
				WHERE	PackageVersion.Version = @l_version
				  AND	PackageVersion.[Update] = @l_release
				  AND	PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
				  AND	PackageFamily.PackageName = @l_name
				  AND	PackageVersion.PackagePathID = PackagePath.PackagePathID
				  AND	PackagePath.PackageFullName = @l_file
			)
		)
		  AND PackageProvides.PackageVersionID = PackageVersion.PackageVersionID
		  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
		  AND MediaContainsPackageVersion.MediaID = Media.MediaID
		  AND Media.MediaTypeID = MediaType.MediaTypeID
		  AND MediaType.[Description] = 'CD'
	  )
GO

CopyPermission 'MediaPackageDependenciesGet', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'MediaPackageGet' AND xtype = 'P'
)
        DROP PROCEDURE MediaPackageGet
GO

CREATE PROCEDURE [MediaPackageGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64)
AS
	SELECT Media.Location, PackagePath.PackageFullName, PackageVersion.Category 
	FROM PackageVersion, PackageFamily, PackagePath, MediaContainsPackageVersion, Media
	WHERE PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
	  AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageFamily.PackageName = @l_name
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.Title = 'RPM Media'

GO

CopyPermission 'MediaPackageGet', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'PackagePathGetOnlyPackages' AND xtype = 'P'
)
        DROP PROCEDURE PackagePathGetOnlyPackages
GO

CREATE PROCEDURE [PackagePathGetOnlyPackages]
AS

	SELECT PackagePathID,
	       PackageFullName,
	       ParentPathID
	FROM PackagePath
	WHERE PackageFullName Like 'Package/%'

GO

CopyPermission 'PackagePathGetOnlyPackages', 'mgsOSBreakdown'
GO
-- USE ManageSoft
GO
--
-- Stored procedures
--
--
--


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_PackageExists' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_PackageExists
GO

CREATE PROCEDURE [HPUX_PackageExists]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64)
AS

	SELECT	PackagePath.PackageFullName, PackageVersion.Category
	FROM 	PackageVersion, PackagePath, PackageFamily, MediaContainsPackageVersion, Media, MediaType
	WHERE	PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND	PackagePath.PackageFullName is not NULL
	  AND	PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND	PackageFamily.PackageName = @l_name
	  AND	PackageVersion.Version = @l_version
	  AND	PackageVersion.[Update] = @l_release
	  AND	PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND	MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND	Media.MediaTypeID = MediaType.MediaTypeID
	  AND	MediaType.[Description] = 'Warehouse'

GO

CopyPermission 'HPUX_PackageExists', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'UnixPackageGet' AND xtype = 'P'
)
        DROP PROCEDURE UnixPackageGet
GO


CREATE PROCEDURE [UnixPackageGet]
	@l_packageFullName nvarchar(256),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_packageFamily nvarchar(64)
AS
	
	SELECT PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath, PackageFamily
	WHERE PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName = @l_packageFullName
	  AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageFamily.PackageName = @l_packageFamily
	  AND PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
GO

CopyPermission 'UnixPackageGet', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaPackageVersionGet' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaPackageVersionGet
GO

CREATE PROCEDURE [HPUX_MediaPackageVersionGet]
	@p_name nvarchar(64),
	@p_version nvarchar(64),
	@l_release nvarchar(64),
	@p_path nvarchar(256)
AS

	SELECT PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath, PackageFamily
	WHERE PackageVersion.Version = @p_version
	   AND PackageVersion.[Update] = @l_release
	   AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	   AND PackageFamily.PackageName = @p_name
	   AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	   AND PackagePath.PackageFullName = @p_path

GO

CopyPermission 'HPUX_MediaPackageVersionGet', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaTypeInsert' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaTypeInsert

GO

CREATE PROCEDURE [HPUX_MediaTypeInsert]
	@p_description nvarchar(128)
AS

	IF NOT EXISTS (
		SELECT MediaTypeID
		FROM MediaType
		WHERE [Description] = @p_description
	)
	BEGIN
		INSERT INTO MediaType
		([Description])
		VALUES
		(@p_description)
	END
GO

CopyPermission 'HPUX_MediaTypeInsert', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaInsert' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaInsert
GO

CREATE PROCEDURE [HPUX_MediaInsert]
	@p_title nvarchar(128),
	@p_location nvarchar(256),
	@p_type nvarchar(128)
AS

	DECLARE @l_typeID int
	
	-- obtain the media type id
	EXEC HPUX_MediaTypeInsert @p_type

	SELECT @l_typeID = MediaTypeID
	FROM MediaType
	WHERE Description = @p_type

	IF NOT EXISTS (
		SELECT MediaID
		FROM Media
		WHERE Title = @p_title
		  AND Location = @p_location
		  AND MediaTypeID = @l_typeID
	)
	BEGIN
		INSERT INTO Media
		(Title, Location, MediaTypeID)
		VALUES
		(@p_title, @p_location, @l_typeID)
	END
GO

CopyPermission 'HPUX_MediaInsert', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaPackageUpdate' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaPackageUpdate
GO

CREATE PROCEDURE [HPUX_MediaPackageUpdate]
	@p_name nvarchar(64),
	@p_version nvarchar(64),
	@p_release nvarchar(64),
	@p_group nvarchar(128),
	@p_path nvarchar(256),
	@p_media_type nvarchar(128), -- description from the mediatype table
	@p_media_location nvarchar(256), -- location from the media table
	@p_media_title nvarchar(128) -- title from the media table
AS

	DECLARE @l_MediaID int
	DECLARE @l_FamilyID int
	DECLARE @l_PackageVersionID int
	DECLARE @l_PackagePathID int

	-- update the media table, storing the media ID
	IF NOT EXISTS (
		SELECT *
		FROM Media
		WHERE Media.Title = @p_media_title
	)
	BEGIN
		EXEC HPUX_MediaInsert @p_media_title, NULL, @p_media_type
	END
	
	SELECT @l_MediaID = Media.MediaID
	FROM Media, MediaType
	WHERE Media.Title = @p_media_title
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = @p_media_type

	-- update the MediaPackageFamily table
	EXEC @l_FamilyID = PackageFamilyBind @p_name
	
	-- update the PackagePath table
	EXEC @l_PackagePathID = PackagePathBind @p_path, NULL

	IF NOT EXISTS (
		SELECT *
		FROM PackageVersion, PackagePath
		WHERE PackageVersion.PackageFamilyID = @l_FamilyID
		  AND PackageVersion.Version = @p_version
		  AND PackageVersion.[Update] = @p_release
		  AND PackageVersion.PackagePathID = @l_PackagePathID
	)
	BEGIN
		INSERT INTO PackageVersion
		(PackagePathID, Version, [Update], PackageFamilyID, Title, Category)
		VALUES
		(@l_PackagePathID, @p_version, @p_release, @l_FamilyID, @p_name, @p_group)
	END	

	SELECT @l_PackageVersionID = PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath
	WHERE PackageVersion.PackageFamilyID = @l_FamilyID
	  AND PackageVersion.Version = @p_version
	  AND PackageVersion.[Update] = @p_release
	  AND PackageVersion.PackagePathID = @l_PackagePathID
	
	-- update the MediaContainsPackageVersion table
	IF NOT EXISTS (
		SELECT *
		FROM MediaContainsPackageVersion
		WHERE MediaID = @l_MediaID
		  AND PackageVersionID = @l_PackageVersionID
	)
	BEGIN
		EXEC MediaContainsPackageVersionAdd
			@l_MediaID, @l_PackageVersionID
	END
GO

CopyPermission 'HPUX_MediaPackageUpdate', 'mgsOSBreakdown'
GO



IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_RequiresInsert' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_RequiresInsert
GO

CREATE PROCEDURE [HPUX_RequiresInsert]
	@l_id int,
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_flags int,
	@l_reqdType char(8)
AS

	EXEC PackageFamilyBind @l_name

	IF NOT EXISTS(
		SELECT * 
		FROM PackageRequires
		WHERE PackageVersionID = @l_id 
		  AND RequiredType = @l_reqdType
		  AND RequiredObject = @l_name
	)
	BEGIN
		EXEC PackageRequiresAdd
			@l_id, 
			@l_reqdType,
			@l_name, 
			NULL, 		--default value
			'Version', 	--default value
			@l_version,
			@l_flags
		
	END

GO

CopyPermission 'HPUX_RequiresInsert', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaRequiresInsert' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaRequiresInsert
GO

CREATE PROCEDURE [HPUX_MediaRequiresInsert]
	@l_id int,
	@l_reqdType char(8),
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_flags int
AS

	DECLARE @l_required int
	DECLARE @l_familyName nvarchar(64)

	EXEC @l_required = PackageFamilyBind @l_name
	SELECT @l_familyName = PackageName
	FROM PackageFamily
	WHERE PackageFamilyID = @l_required

	IF NOT EXISTS(
		SELECT *
		FROM PackageRequires
		WHERE PackageVersionID = @l_id 
		  AND RequiredType = @l_reqdType
		  AND [Value] = @l_version 
		  AND [Match] = @l_flags
		  AND RequiredObject = @l_familyName
	)
	BEGIN
		EXEC PackageRequiresAdd
			@l_id,
			@l_reqdType,
			@l_familyName,
			NULL,
			'Version',
			@l_version,
			@l_flags
	END

GO

CopyPermission 'HPUX_MediaRequiresInsert', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_ProvidesInsert' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_ProvidesInsert
GO

CREATE PROCEDURE [HPUX_ProvidesInsert]
	@l_id int,
	@l_name nvarchar(64),
	@l_version nvarchar(64)
AS
	DECLARE	@l_packageFamilyID int

	EXEC @l_packageFamilyID = PackageFamilyBind @l_name

	IF NOT EXISTS(SELECT * 
		FROM PackageProvides
		WHERE PackageVersionID = @l_id 
		  AND Version = @l_version 
		  AND PackageFamilyID = @l_packageFamilyID
	)
	BEGIN
		EXEC PackageProvidesAdd
			@l_id,
			@l_packageFamilyID,
			@l_version
	END

GO

CopyPermission 'HPUX_ProvidesInsert', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaProvidesInsert' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaProvidesInsert
GO

CREATE PROCEDURE [HPUX_MediaProvidesInsert]
	@l_id int,
	@l_name nvarchar(64),
	@l_version nvarchar(64)
AS

	DECLARE @l_packageId int
	
	EXEC @l_packageId = PackageFamilyBind @l_name
	
	IF NOT EXISTS(SELECT * 
		FROM PackageProvides
		WHERE PackageVersionID = @l_id 
		  AND PackageFamilyID = @l_packageId
		  AND Version = @l_version 
	)
	BEGIN
		EXEC PackageProvidesAdd
			@l_id,
			@l_packageId,
			@l_version
	END
GO

CopyPermission 'HPUX_MediaProvidesInsert', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_PackageRequiresGet' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_PackageRequiresGet
GO

CREATE PROCEDURE [HPUX_PackageRequiresGet]
	@l_path nvarchar(512)
AS

	SELECT PackageRequires.RequiredObject as PackageName, PackageRequires.[Value], PackageRequires.[Match]
	FROM PackageFamily, PackageRequires, PackageVersion, PackagePath, MediaContainsPackageVersion, Media, MediaType
	WHERE PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName = @l_path
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'Warehouse'
	  AND PackageVersion.PackageVersionID = PackageRequires.PackageVersionID
	  AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID

GO

CopyPermission 'HPUX_PackageRequiresGet', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaRequiresGet' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaRequiresGet
GO

CREATE PROCEDURE [HPUX_MediaRequiresGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_file nvarchar(256)
AS

	SELECT PackageRequires.RequiredObject as PackageName, PackageRequires.[Value], PackageRequires.[Match]
	FROM PackageVersion, PackageFamily, PackageRequires, PackagePath, MediaContainsPackageVersion, Media, MediaType
	WHERE PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
	  AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageFamily.PackageName = @l_name
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'HP-UX Media'
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName = @l_file
	  AND PackageVersion.PackageVersionID = PackageRequires.PackageVersionID
	
GO

CopyPermission 'HPUX_MediaRequiresGet', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_PackageProvidesGet' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_PackageProvidesGet
GO

CREATE PROCEDURE [HPUX_PackageProvidesGet]
	@l_path nvarchar(512)
AS

	DECLARE	@l_PackageVersionID int

	SELECT @l_PackageVersionID = PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath, MediaContainsPackageVersion, Media, MediaType
	WHERE PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName = @l_path
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'Warehouse'

	SELECT PackageFamily.PackageName, PackageProvides.Version
	FROM PackageProvides, PackageFamily
	WHERE PackageProvides.PackageVersionID = @l_PackageVersionID
	  AND PackageProvides.PackageFamilyID = PackageFamily.PackageFamilyID

GO

CopyPermission 'HPUX_PackageProvidesGet', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaProvidesGet' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaProvidesGet
GO

CREATE PROCEDURE [HPUX_MediaProvidesGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_file nvarchar(256)
AS
	DECLARE @l_versionid int

	SELECT @l_versionid = PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath, MediaContainsPackageVersion, Media, PackageFamily, MediaType
	WHERE PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'HP-UX Media'
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName= @l_file

	SELECT PackageFamily.PackageName, PackageProvides.Version
	FROM PackageProvides, PackageFamily
	WHERE PackageProvides.PackageVersionID = @l_versionid
	  AND PackageProvides.PackageFamilyID = PackageFamily.PackageFamilyID

GO

CopyPermission 'HPUX_MediaProvidesGet', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_PackageDependenciesGet' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_PackageDependenciesGet
GO

CREATE PROCEDURE [HPUX_PackageDependenciesGet]
	@l_path nvarchar(512)
AS

	DECLARE	@l_PackageVersionID int

	SELECT @l_PackageVersionID = PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath, MediaContainsPackageVersion, Media, MediaType
	WHERE PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName = @l_path
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'Warehouse' -- Warehouse ID

	-- get the packages that implement the requirements
	SELECT 	PackageFamily.PackageName, PackageVersion.Version, PackageVersion.[Update]
	FROM 	PackageVersion, PackageFamily
	WHERE 	PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND 	PackageVersion.PackageVersionID IN
	(
		SELECT 	PackageProvides.PackageVersionID
		FROM 	PackageProvides, PackageFamily,
			PackageVersion, MediaContainsPackageVersion, Media, MediaType
		WHERE 	PackageProvides.PackageFamilyID = PackageFamily.PackageFamilyID
		  AND 	PackageFamily.PackageName IN
		  (
			-- get the requirements of the specified package
			SELECT RequiredObject
			FROM PackageRequires
			WHERE PackageRequires.PackageVersionID = @l_PackageVersionID
		  )
		  AND PackageProvides.PackageVersionID = PackageVersion.PackageVersionID
		  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
		  AND MediaContainsPackageVersion.MediaID = Media.MediaID
		  AND Media.MediaTypeID = MediaType.MediaTypeID
		  AND MediaType.[Description] = 'Warehouse'
	)
GO

CopyPermission 'HPUX_PackageDependenciesGet', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaPackageDependenciesGet' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaPackageDependenciesGet
GO

CREATE PROCEDURE [HPUX_MediaPackageDependenciesGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_file nvarchar(256)
AS
	--get all the packages that implement the requirements of the specified package
	select	implementation_F.PackageName, implementation.Version, implementation.[Update]
	FROM
		PackageVersion needy,
		PackagePath needy_PP,
		PackageFamily needy_F,
	
		PackageRequires requirement,
		PackageFamily requirementFamily,
	
		PackageProvides interface,
		PackageVersion implementation,
		MediaContainsPackageVersion implementation_MCPV,
		Media implementation_M,
		MediaType implementation_MT,
		PackageFamily implementation_F
		
	WHERE
		needy.Version = @l_version
	  and 	needy.[Update] = @l_release
	  AND	needy.PackagePathID = needy_PP.PackagePathID
	  and	needy.PackageFamilyID = needy_F.PackageFamilyID
	  and	needy_PP.PackageFullName = @l_file
	  and	needy_F.PackageName = @l_name
	
	  and	needy.PackageVersionID = requirement.PackageVersionID
	  and	requirement.RequiredObject = requirementFamily.PackageName
	
	  and	requirementFamily.PackageFamilyID = interface.PackageFamilyID
	  and	interface.PackageVersionID = implementation.PackageVersionID
	  and	implementation.PackageVersionID = implementation_MCPV.PackageVersionID
	  and	implementation_MCPV.MediaID = implementation_M.MediaID
	  and	implementation_M.MediaTypeID = implementation_MT.MediaTypeID
	  and	implementation_MT.[Description] = 'HP-UX Media'
	  and	implementation_F.PackageFamilyID = implementation.PackageFamilyID
GO

CopyPermission 'HPUX_MediaPackageDependenciesGet', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaPackageGet' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaPackageGet
GO

CREATE PROCEDURE [HPUX_MediaPackageGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64)
AS
	SELECT Media.Title, PackagePath.PackageFullName, PackageVersion.Category
	FROM PackageVersion, PackageFamily, PackagePath, MediaContainsPackageVersion, Media, MediaType
	WHERE PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
	  AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageFamily.PackageName = @l_name
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'HP-UX Media'
GO

CopyPermission 'HPUX_MediaPackageGet', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_PackagePathGetOnlyPackages' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_PackagePathGetOnlyPackages
GO

CREATE PROCEDURE [HPUX_PackagePathGetOnlyPackages]
AS
	select  pp.packagepathid, pp.packagefullname, pp.parentpathid
	from 	packageversion pv,
		mediacontainspackageversion mcpv,
		packagepath pp
	where	pv.packageversionid = mcpv.packageversionid
	  and	mcpv.mediaid=1
	  and	pv.packagepathid = pp.packagepathid
	  and	pp.packagefullname like 'Package/%'

GO

CopyPermission 'HPUX_PackagePathGetOnlyPackages', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaGetTitleByPackage' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaGetTitleByPackage
GO

CREATE PROCEDURE [HPUX_MediaGetTitleByPackage]
	@p_path nvarchar(256),
	@p_version nvarchar(64),
	@p_release nvarchar(64),
	@p_name nvarchar(256)
AS
	SELECT	m.Title
	FROM	PackageVersion 	pv,
		PackagePath	pp,
		PackageFamily	pf,
		MediaContainsPackageVersion mcpv,
		Media		m
	WHERE	pv.PackagePathID = pp.PackagePathID
	  AND	pv.PackageFamilyID = pf.PackageFamilyID
	  AND	mcpv.PackageVersionID = pv.PackageVersionID
	  AND	mcpv.MediaID = m.MediaID
	  AND	pf.PackageName = @p_name
	  AND	pp.PackageFullName = @p_path
	  AND	pv.Version = @p_version
	  AND	pv.[Update] = @p_release
GO

CopyPermission 'HPUX_MediaGetTitleByPackage', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaGetPath' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaGetPath
GO

CREATE PROCEDURE [HPUX_MediaGetPath]
	@p_name nvarchar(256)
AS
	SELECT 	pp.PackageFullName 
	FROM 	PackageVersion pv,
		PackagePath pp,
		Media m,
		MediaContainsPackageVersion mcpv
	WHERE	pv.PackagePathID = pp.PackagePathID
	  AND	mcpv.PackageVersionID = pv.PackageVersionID
	  AND	mcpv.MediaID = m.MediaID
	  AND	m.Title = @p_name
GO

CopyPermission 'HPUX_MediaGetPath', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_PackagePathGetMedia' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_PackagePathGetMedia
GO

CREATE PROCEDURE [HPUX_PackagePathGetMedia]
	@p_path nvarchar(256)
AS
	SELECT 	m.Title 
	FROM 	PackageVersion pv,
		PackagePath pp,
		Media m,
		MediaContainsPackageVersion mcpv
	WHERE	pv.PackagePathID = pp.PackagePathID
	  AND	mcpv.PackageVersionID = pv.PackageVersionID
	  AND	mcpv.MediaID = m.MediaID
	  AND	pp.PackageFullName LIKE @p_path + '%'
GO

CopyPermission 'HPUX_PackagePathGetMedia', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaGetAll' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaGetAll
GO

CREATE PROCEDURE [HPUX_MediaGetAll]
AS
	SELECT 	m.Title 
	FROM 	Media m,
		MediaType mt
	WHERE	mt.Description = 'HP-UX Media'
	  AND	m.MediaTypeID = mt.MediaTypeID
	  AND EXISTS
		(Select mediaid
		FROM MediaContainsPackageVersion mcpv
		Where mcpv.mediaid = m.mediaid)
GO

CopyPermission 'HPUX_MediaGetAll', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_FileNameMapGetDestFileBySourceFile' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_FileNameMapGetDestFileBySourceFile
GO

CREATE PROCEDURE [HPUX_FileNameMapGetDestFileBySourceFile]
	@p_MediaID int,
	@p_SourceFile nvarchar(256)
AS
	SELECT Destfile
	FROM FileNameMap
	WHERE mediaID = @p_MediaID
	  AND SourceFile = @p_SourceFile
GO

CopyPermission 'HPUX_FileNameMapGetDestFileBySourceFile', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_FileNameMapGetSourceFileByDestFile' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_FileNameMapGetSourceFileByDestFile
GO

CREATE PROCEDURE [HPUX_FileNameMapGetSourceFileByDestFile]
	@p_MediaID int,
	@p_DestFile nvarchar(256)
AS
	SELECT Sourcefile
	FROM FileNameMap
	WHERE mediaID = @p_MediaID
	  AND DestFile = @p_DestFile
GO

CopyPermission 'HPUX_FileNameMapGetSourceFileByDestFile', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'HPUX_MediaGetIDbyTitle' AND xtype = 'P'
)
        DROP PROCEDURE HPUX_MediaGetIDbyTitle
GO

CREATE PROCEDURE [HPUX_MediaGetIDbyTitle]
	@p_title nvarchar(128)
AS
	SELECT mediaid
	FROM media, mediatype
	WHERE mediatype.mediatypeid = media.mediatypeid
	  AND mediatype.[description] = 'HP-UX Media'
	  AND Title = @p_Title
GO

CopyPermission 'HPUX_MediaGetIDbyTitle', 'mgsOSBreakdown'
GO
-- USE ManageSoft
GO
--
-- Stored procedures
--
--
--


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'Solaris_MediaGetIDbyTitle' AND xtype = 'P'
)
        DROP PROCEDURE Solaris_MediaGetIDbyTitle
GO

CREATE PROCEDURE [Solaris_MediaGetIDbyTitle]
	@p_title nvarchar(128)
AS
	SELECT mediaid
	FROM media, mediatype
	WHERE mediatype.mediatypeid = media.mediatypeid
	  AND mediatype.[description] = 'Solaris Media'
	  AND Title = @p_Title
GO

CopyPermission 'Solaris_MediaGetIDbyTitle', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'Solaris_MediaPackageDependenciesGet' AND xtype = 'P'
)
        DROP PROCEDURE Solaris_MediaPackageDependenciesGet
GO

CREATE PROCEDURE [Solaris_MediaPackageDependenciesGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_file nvarchar(256)
AS
	--get all the packages that implement the requirements of the specified package
	select	implementation_F.PackageName, implementation.Version, implementation.[Update]
	FROM
		PackageVersion needy,
		PackagePath needy_PP,
		PackageFamily needy_F,
	
		PackageRequires requirement,
		PackageFamily requirementFamily,
	
		PackageProvides interface,
		PackageVersion implementation,
		MediaContainsPackageVersion implementation_MCPV,
		Media implementation_M,
		MediaType implementation_MT,
		PackageFamily implementation_F
		
	WHERE
		needy.Version = @l_version
	  and 	needy.[Update] = @l_release
	  AND	needy.PackagePathID = needy_PP.PackagePathID
	  and	needy.PackageFamilyID = needy_F.PackageFamilyID
	  and	needy_PP.PackageFullName = @l_file
	  and	needy_F.PackageName = @l_name
	
	  and	needy.PackageVersionID = requirement.PackageVersionID
	  and	requirement.RequiredObject = requirementFamily.PackageName
	
	  and	requirementFamily.PackageFamilyID = interface.PackageFamilyID
	  and	interface.PackageVersionID = implementation.PackageVersionID
	  and	implementation.PackageVersionID = implementation_MCPV.PackageVersionID
	  and	implementation_MCPV.MediaID = implementation_M.MediaID
	  and	implementation_M.MediaTypeID = implementation_MT.MediaTypeID
	  and	implementation_MT.[Description] = 'Solaris Media'
	  and	implementation_F.PackageFamilyID = implementation.PackageFamilyID
GO

CopyPermission 'Solaris_MediaPackageDependenciesGet', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'Solaris_MediaPackageGet' AND xtype = 'P'
)
        DROP PROCEDURE Solaris_MediaPackageGet
GO

CREATE PROCEDURE [Solaris_MediaPackageGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64)
AS
	SELECT Media.Title, PackagePath.PackageFullName, PackageVersion.Category
	FROM PackageVersion, PackageFamily, PackagePath, MediaContainsPackageVersion, Media, MediaType
	WHERE PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
	  AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageFamily.PackageName = @l_name
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'Solaris Media'
GO

CopyPermission 'Solaris_MediaPackageGet', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'Solaris_MediaPackagesGetAll' AND xtype = 'P'
)
        DROP PROCEDURE Solaris_MediaPackagesGetAll
GO

CREATE PROCEDURE [Solaris_MediaPackagesGetAll]
AS
SELECT pf1.PackageName + '-' + pv.Version AS 'PackageName', PackageFullName AS 'PackagePath', Category
FROM PackageVersion pv, PackagePath pp, PackageFamily pf1, Media m, MediaContainsPackageVersion mcp, MediaType mt
WHERE pv.PackagePAthID = pp.PackagePathID
	AND pv.PackageFamilyID = pf1.PackageFamilyID
	AND mcp.PackageVersionID = pv.PackageVersionID
	AND m.MediaID = mcp.MediaID
	AND mt.MediaTypeID = m.MediaTypeID
	AND mt.Description = 'Solaris Media'
ORDER BY PackageName
GO

CopyPermission 'Solaris_MediaPackagesGetAll', 'mgsOSBreakdown'
GO


IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'Solaris_MediaProvidesGet' AND xtype = 'P'
)
        DROP PROCEDURE Solaris_MediaProvidesGet

GO

CREATE PROCEDURE [Solaris_MediaProvidesGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_file nvarchar(256)
AS
	DECLARE @l_versionid int

	SELECT @l_versionid = PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath, MediaContainsPackageVersion, Media, PackageFamily, MediaType
	WHERE PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'Solaris Media'
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName= @l_file

	SELECT PackageFamily.PackageName, PackageProvides.Version
	FROM PackageProvides, PackageFamily
	WHERE PackageProvides.PackageVersionID = @l_versionid
	  AND PackageProvides.PackageFamilyID = PackageFamily.PackageFamilyID
GO

CopyPermission 'Solaris_MediaProvidesGet', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'Solaris_MediaRequiresGet' AND xtype = 'P'
)
        DROP PROCEDURE Solaris_MediaRequiresGet
GO


CREATE PROCEDURE [Solaris_MediaRequiresGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_file nvarchar(256)
AS

	SELECT PackageRequires.RequiredObject as PackageName, PackageRequires.[Value], PackageRequires.[Match]
	FROM PackageVersion, PackageFamily, PackageRequires, PackagePath, MediaContainsPackageVersion, Media, MediaType
	WHERE PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
	  AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageFamily.PackageName = @l_name
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'Solaris Media'
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName = @l_file
	  AND PackageVersion.PackageVersionID = PackageRequires.PackageVersionID
GO

CopyPermission 'Solaris_MediaRequiresGet', 'mgsOSBreakdown'
GO

-- USE ManageSoft
GO
--
-- Stored procedures
--
--
--

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'OSX_MediaPackageDependenciesGet' AND xtype = 'P'
)
        DROP PROCEDURE OSX_MediaPackageDependenciesGet
GO

CREATE PROCEDURE [OSX_MediaPackageDependenciesGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_file nvarchar(256)
AS
	--get all the packages that implement the requirements of the specified package
	select	implementation_F.PackageName, implementation.Version, implementation.[Update]
	FROM
		PackageVersion needy,
		PackagePath needy_PP,
		PackageFamily needy_F,
	
		PackageRequires requirement,
		PackageFamily requirementFamily,
	
		PackageProvides interface,
		PackageVersion implementation,
		MediaContainsPackageVersion implementation_MCPV,
		Media implementation_M,
		MediaType implementation_MT,
		PackageFamily implementation_F
		
	WHERE
		needy.Version = @l_version
	  and 	needy.[Update] = @l_release
	  AND	needy.PackagePathID = needy_PP.PackagePathID
	  and	needy.PackageFamilyID = needy_F.PackageFamilyID
	  and	needy_PP.PackageFullName = @l_file
	  and	needy_F.PackageName = @l_name
	
	  and	needy.PackageVersionID = requirement.PackageVersionID
	  and	requirement.RequiredObject = requirementFamily.PackageName
	
	  and	requirementFamily.PackageFamilyID = interface.PackageFamilyID
	  and	interface.PackageVersionID = implementation.PackageVersionID
	  and	implementation.PackageVersionID = implementation_MCPV.PackageVersionID
	  and	implementation_MCPV.MediaID = implementation_M.MediaID
	  and	implementation_M.MediaTypeID = implementation_MT.MediaTypeID
	  and	implementation_MT.[Description] = 'OS X Media'
	  and	implementation_F.PackageFamilyID = implementation.PackageFamilyID
GO

CopyPermission 'OSX_MediaPackageDependenciesGet', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'OSX_MediaPackageGet' AND xtype = 'P'
)
        DROP PROCEDURE OSX_MediaPackageGet
GO

CREATE PROCEDURE [OSX_MediaPackageGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64)
AS
	SELECT Media.Title, PackagePath.PackageFullName, PackageVersion.Category
	FROM PackageVersion, PackageFamily, PackagePath, MediaContainsPackageVersion, Media, MediaType
	WHERE PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
	  AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageFamily.PackageName = @l_name
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'OS X Media'
GO

CopyPermission 'OSX_MediaPackageGet', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'OSX_MediaProvidesGet' AND xtype = 'P'
)
        DROP PROCEDURE OSX_MediaProvidesGet

GO

CREATE PROCEDURE [OSX_MediaProvidesGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_file nvarchar(256)
AS
	DECLARE @l_versionid int

	SELECT @l_versionid = PackageVersion.PackageVersionID
	FROM PackageVersion, PackagePath, MediaContainsPackageVersion, Media, PackageFamily, MediaType
	WHERE PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'OS X Media'
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName= @l_file

	SELECT PackageFamily.PackageName, PackageProvides.Version
	FROM PackageProvides, PackageFamily
	WHERE PackageProvides.PackageVersionID = @l_versionid
	  AND PackageProvides.PackageFamilyID = PackageFamily.PackageFamilyID
GO

CopyPermission 'OSX_MediaProvidesGet', 'mgsOSBreakdown'
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'OSX_MediaRequiresGet' AND xtype = 'P'
)
        DROP PROCEDURE OSX_MediaRequiresGet
GO


CREATE PROCEDURE [OSX_MediaRequiresGet]
	@l_name nvarchar(64),
	@l_version nvarchar(64),
	@l_release nvarchar(64),
	@l_file nvarchar(256)
AS

	SELECT PackageRequires.RequiredObject as PackageName, PackageRequires.[Value], PackageRequires.[Match]
	FROM PackageVersion, PackageFamily, PackageRequires, PackagePath, MediaContainsPackageVersion, Media, MediaType
	WHERE PackageVersion.Version = @l_version
	  AND PackageVersion.[Update] = @l_release
	  AND PackageVersion.PackageFamilyID = PackageFamily.PackageFamilyID
	  AND PackageFamily.PackageName = @l_name
	  AND PackageVersion.PackageVersionID = MediaContainsPackageVersion.PackageVersionID
	  AND MediaContainsPackageVersion.MediaID = Media.MediaID
	  AND Media.MediaTypeID = MediaType.MediaTypeID
	  AND MediaType.[Description] = 'OS X Media'
	  AND PackageVersion.PackagePathID = PackagePath.PackagePathID
	  AND PackagePath.PackageFullName = @l_file
	  AND PackageVersion.PackageVersionID = PackageRequires.PackageVersionID
GO

CopyPermission 'OSX_MediaRequiresGet', 'mgsOSBreakdown'
GO

/*
 * $Id: AdoptionStatusSummary.sql 84480 2007-07-24 06:34:27Z pca $
 *
 * DESCRIPTION: Stored Procedure: AdoptionStatusSummary
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 */
 
-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'AdoptionStatusSummary' AND xtype = 'P'
)
        DROP PROCEDURE AdoptionStatusSummary
GO

CREATE PROCEDURE [AdoptionStatusSummary]
	@oudn varchar(800) = '%', --'%CN=Computers,DC=devscarlett,DC=mgsft,DC=com', --'%',
	@ouMatch bit = 1 --Values:[0=do exact OU Match | 1=include child-OUs in match]
AS

CREATE TABLE #Organization(OrganizationID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

SELECT
	ActionStatus = 
		(CASE WHEN Status.ActionStateName IN 
			(SELECT ActionStateName FROM ActionState WHERE ActionStateName NOT IN ('Applied', 'ApplyFailed'))
		 THEN 'Pending' ELSE Status.ActionStateName END
		),
	SUM(Status.StatusCount) AS StatusCount
FROM
(

SELECT	
		aa.ActionStateID,
		ast.ActionStateName,
		aa.LastUpdate,
		COUNT(ISNULL(c.ComputerID, nd.DeviceID)) AS StatusCount
	
	FROM 	
		(
			SELECT 
				aa.*, a.ServerUID 
			FROM 
			ActionApplies aa,
			(
				SELECT ActionUID, DeviceID, MAX(LastUpdate) AS LastUpdate
				FROM ActionApplies aaInner
				WHERE ActionUID = 
					(
						SELECT TOP 1 t1.ActionUID
						FROM ActionApplies t1, Action t2, Task t3 
						WHERE t1.ActionUID = t2.ActionUID
						  AND t2.TaskID = t3.TaskID
						  AND t3.TaskTypeID = 5 -- Adoption Task
						  AND t1.DeviceID = aaInner.DeviceID 
						ORDER BY t1.LastUpdate DESC -- Latest first
					)
				GROUP BY ActionUID, DeviceID
			) AS aa2,
			[Action] a,
			Task t,
			TaskType tt
			WHERE aa.ActionUID = aa2.ActionUID
			  AND aa.DeviceID = aa2.DeviceID
			  AND aa.LastUpdate = aa2.LastUpdate
			  AND aa.ActionUID = a.ActionUID
			  AND a.TaskID = t.TaskID
			  AND t.TaskTypeID = tt.TaskTypeID
			  AND tt.TaskTypeName = 'Adoption' -- ID = 5
		) AS aa
	INNER JOIN	ActionState ast ON aa.ActionStateID = ast.ActionstateID
	INNER JOIN	NetworkDevice nd ON aa.DeviceID = nd.DeviceID
	INNER JOIN	DistributionServer ds ON aa.ServerUID = ds.ServerUID
	LEFT OUTER JOIN	Computer c ON nd.ComputerID = c.ComputerID
	LEFT OUTER JOIN	#Organization o ON o.OrganizationID = c.ComputerOUID
	
	GROUP BY 
		aa.ActionStateID,
		ast.ActionStateName,
		aa.LastUpdate
) AS Status
GROUP BY Status.ActionStateName

GO
/*
 * $Id: AdoptionStatusDetails.sql 92365 2009-05-27 00:49:05Z rlowery $
 *
 * DESCRIPTION: Stored Procedure: AdoptionStatusDetails
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 */
 
-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'AdoptionStatusDetails' AND xtype = 'P'
)
        DROP PROCEDURE AdoptionStatusDetails
GO


CREATE PROCEDURE [AdoptionStatusDetails]
	@oudn varchar(800) = '%', --'%CN=Computers,DC=devscarlett,DC=mgsft,DC=com', --'%',
	@ouMatch bit = 1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@actionStatus varchar(32)
AS

-- Map the passed in action status to the real database values
DECLARE @actionState nvarchar(32)
SET @actionState = @actionStatus
IF (@actionState = 'Success') 
	SET @actionState = 'Applied'
IF (@actionState = 'Failure') 
	SET @actionState = 'ApplyFailed'

CREATE TABLE #Organization(OrganizationID int PRIMARY KEY)
EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0

SELECT	
	ISNULL(c.ComputerID, nd.DeviceID) AS ComputerID,
	ISNULL(c.ComputerCN, nd.DeviceName) AS ComputerCN,
	OUDN = dbo.OUName(o.OrganizationID),
	aa.TaskID,
	aa.TaskName,
	aa.TaskTypeID,
	ds.ServerName,
	aa.ActionStateID,
	ast.ActionStateName,
	aa.FailureReason,
	DATEADD(minute, DATEDIFF(minute, GETUTCDATE(), GETDATE()), aa.LastUpdate) as LastUpdate

FROM 	
	(
		SELECT 
			aa.*, a.ServerUID, t.TaskID, t.TaskName, t.TaskTypeID
		FROM 
		ActionApplies aa,
		(
			SELECT ActionUID, DeviceID, MAX(LastUpdate) AS LastUpdate
			FROM ActionApplies aaInner
			WHERE ActionUID = 
				(
					SELECT TOP 1 t1.ActionUID
					FROM ActionApplies t1, Action t2, Task t3 
					WHERE t1.ActionUID = t2.ActionUID
					  AND t2.TaskID = t3.TaskID
					  AND t3.TaskTypeID = 5 -- Adoption Task
					  AND t1.DeviceID = aaInner.DeviceID 
					ORDER BY t1.LastUpdate DESC -- Latest first
				)
			GROUP BY ActionUID, DeviceID
		) AS aa2,
		[Action] a,
		Task t,
		TaskType tt
		WHERE aa.ActionUID = aa2.ActionUID
		  AND aa.DeviceID = aa2.DeviceID
		  AND aa.LastUpdate = aa2.LastUpdate
		  AND aa.ActionUID = a.ActionUID
		  AND a.TaskID = t.TaskID
		  AND t.TaskTypeID = tt.TaskTypeID
		  AND tt.TaskTypeName = 'Adoption' -- ID = 5
	) AS aa
INNER JOIN	ActionState ast ON aa.ActionStateID = ast.ActionstateID
INNER JOIN	NetworkDevice nd ON aa.DeviceID = nd.DeviceID
INNER JOIN	DistributionServer ds ON aa.ServerUID = ds.ServerUID
LEFT OUTER JOIN	Computer c ON nd.ComputerID = c.ComputerID
LEFT OUTER JOIN	#Organization o ON o.OrganizationID = c.ComputerOUID

WHERE	((ast.ActionStateName = @actionState) OR (@actionState = 'pending' AND ast.ActionStateName NOT IN ('Applied','ApplyFailed')))
  AND 	ast.ActionStateName NOT IN ('CancelInProgress', 'CancelFailed', 'Cancelled') -- Cancels are not in pending or applied or failed states so disregard them

GO
/*
 * $Id: SoftwareVersionGetAllBySoftwareProductID.sql 52957 2004-01-26 22:57:41Z niteshk $
 *
 * Stored procedures to get list of software applications within a given license
 *
 */

IF EXISTS (
	SELECT * FROM dbo.sysobjects
	WHERE [name]= 'SoftwareVersionGetAllBySoftwareProductID' AND xtype = 'P'
)
	DROP PROCEDURE SoftwareVersionGetAllBySoftwareProductID
GO

CREATE PROCEDURE SoftwareVersionGetAllBySoftwareProductID
	@SoftwareProductID		int
AS
	SELECT	
		SoftwareID,
		SoftwareName,
		Version
		
	  FROM	
		ProductContainsSoftware pcs, 
		SoftwareVersion sv
		
	WHERE pcs.SoftwareProductID = @SoftwareProductID
 	  AND pcs.SoftwareVersionID = sv.SoftwareID
 	  
 	ORDER BY SoftwareName ASC, Version ASC
	
	RETURN @@ROWCOUNT
	
GO
/* 
 * $Id: OUDN_to_RDNandDomainDN.sql 84480 2007-07-24 06:34:27Z pca $
 * $Locker$
 *
 * DESCRIPTION: Stored Procedure: OUDN_to_RDNandDomainDN
 *	Input:
 * 		- @oudn : The full DN for the OU
 *	Returns:
 *		- Output parameter, @ourdn : The DN minus the DC part
 *		- Outpur parameter, @domaindn : The DC part of the DN	
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE ManageSoft
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'OUDN_to_RDNandDomainDN' AND xtype = 'P'
)
        DROP PROCEDURE OUDN_to_RDNandDomainDN
GO

CREATE PROCEDURE OUDN_to_RDNandDomainDN
	@oudn nvarchar(800),
	@ourdn nvarchar(800) OUTPUT,
	@domaindn nvarchar(800) OUTPUT
AS

DECLARE @index INT 
DECLARE @length INT

SET @oudn = LOWER(@oudn)
SET @index = PATINDEX('%dc=%', @oudn)
SET @domaindn = SUBSTRING(@oudn, @index, 800)

IF (@index = 2) -- there was only a % at the start
	SET @length = @index-1
ELSE IF (@index = 1) -- Domain DN is the only part
	SET @length = -1 
ELSE IF (@index = 0)
	SET @length = 1
ELSE IF (@index > 2)
	SET @length = @index-2

IF (@length > -1)
	SET @ourdn = SUBSTRING(@oudn, 1, @length)
ELSE
	SET @ourdn = ''

GO

CopyPermission 'OUDN_to_RDNandDomainDN', 'mgsOSBreakdown'
GO

/*
 * $Id: SoftwareLibraryDetails.sql 84480 2007-07-24 06:34:27Z pca $
 *
 * Stored procedures to get software library hierarchy
 *
 */

--PackageVersionGetAllDetailed
IF EXISTS (
	SELECT * FROM sysobjects WHERE xtype = 'P'
	AND name = 'PackageVersionGetAllDetailed'
)
	DROP PROCEDURE PackageVersionGetAllDetailed
GO

CREATE PROCEDURE PackageVersionGetAllDetailed
AS
	SELECT	pv.PackageVersionID,
		pf.PackageName,
		pv.Version,
		pp.PackageFullName
	FROM	PackageVersion AS pv, PackageFamily AS pf, PackagePath AS pp
	WHERE	pv.PackageFamilyID = pf.PackageFamilyID
	  AND	pv.PackagePathID = pp.PackagePathID
	  AND	pp.PackageFullName IS NOT NULL
	  AND	NOT EXISTS
		(
			SELECT	1
			FROM	PackageVersion AS pv2, PackagePath AS pp2
			WHERE	pv2.PackagePathID = pp2.PackagePathID
			  AND	pp2.PackageFullName = pp.PackageFullName
			  AND	pv2.PackageVersionID > pv.PackageVersionID
		)
GO

-- PackageVersionGetAllByPackageType
IF EXISTS (
	SELECT * FROM sysobjects WHERE xtype = 'P'
	AND name = 'PackageVersionGetAllByPackageType'
)
	DROP PROCEDURE PackageVersionGetAllByPackageType
GO

CREATE PROCEDURE PackageVersionGetAllByPackageType
	@PackagePathTypeID	int
AS
	SELECT	DISTINCT pp.PackagePathID,
		pp.PackageFullName,
		pp.ParentPathID,
		pp.PackagePathTypeID,
		pv.PackageVersionID,
		pv.Title,
		pf.PackageName,
		pv.Version,
		pp.PackageFullName
	FROM	PackageVersion AS pv, 
		PackageFamily AS pf, 
		PackagePath AS pp, 
		PackagePathType as ppt, 
		MediaContainsPackageVersion as mcpv
	WHERE	pp.PackagePathTypeID = @PackagePathTypeID
	  AND	pv.PackageFamilyID = pf.PackageFamilyID
	  AND	pp.PackagePathID = pv.PackagePathID
	  AND	mcpv.PackageVersionID = pv.PackageVersionID
	  AND	mcpv.MediaID = 1
	  AND	pp.PackageFullName IS NOT NULL
GO



IF EXISTS (
	SELECT * FROM sysobjects WHERE xtype = 'P'
	AND name = 'PackageGetRootByPackageType'
)
	DROP PROCEDURE PackageGetRootByPackageType
GO

-- PackageGetRootByPackageType
IF EXISTS (
	SELECT * FROM sysobjects WHERE xtype = 'P'
	AND name = 'PackageGetRootByPackageType'
)
	DROP PROCEDURE PackageGetRootByPackageType
GO

CREATE PROCEDURE PackageGetRootByPackageType
	@PackageFullName	nvarchar(256)
AS
	SELECT	pp.PackagePathID, pp.PackagePathTypeID, pp.PackageFullName
	FROM	PackagePath AS pp
	WHERE	pp.ParentPathID is NULL
	  AND 	pp.PackageFullName = @PackageFullName
	  AND	EXISTS
		(
			SELECT *
			FROM	MediaContainsPackagePath
			WHERE	PackagePathID = pp.PackagePathID
		)
GO


IF EXISTS (
	SELECT * FROM sysobjects WHERE xtype = 'P'
	AND name = 'PackageExistInMediaContainsPackagePath'
)
	DROP PROCEDURE PackageExistInMediaContainsPackagePath
GO

CREATE PROCEDURE PackageExistInMediaContainsPackagePath
	@PackagePathID	int
AS
	SELECT	pp.PackagePathID, pp.PackagePathTypeID, pp.PackageFullName, pp.ParentPathID
	FROM	PackagePath AS pp
	WHERE	pp.ParentPathID = @PackagePathID
	  AND 	pp.PackageFullName IS NOT NULL
	  AND	EXISTS
		(
			SELECT *
			FROM	MediaContainsPackagePath
			WHERE	PackagePathID = pp.PackagePathID
		)			
GO


IF EXISTS (
	SELECT * FROM sysobjects WHERE xtype = 'P'
	AND name = 'PackageDetailsGetByPackagePath'
)
	DROP PROCEDURE PackageDetailsGetByPackagePath
GO

CREATE PROCEDURE PackageDetailsGetByPackagePath
	@PackagePathID	int
AS
	SELECT	DISTINCT pp.PackageFullName,
		pp.ParentPathID,
		pp.PackagePathTypeID,
		pv.PackageVersionID,
		pv.Title,
		pf.PackageName,
		pv.Version,
		pp.PackageFullName
	FROM	PackageVersion AS pv, 
		PackageFamily AS pf, 
		PackagePath AS pp, 
		PackagePathType as ppt, 
		MediaContainsPackageVersion as mcpv
	WHERE	pp.PackagePathID = @PackagePathID
	  AND	pv.PackageFamilyID = pf.PackageFamilyID
	  AND	pp.PackagePathID = pv.PackagePathID
	  AND	mcpv.PackageVersionID = pv.PackageVersionID
	  AND	mcpv.MediaID = 1
	  AND	pp.PackageFullName IS NOT NULL
GO

/*
 * $Id: BIOS.sql 56540 2004-07-13 05:09:26Z kbui $
 *
 * Stored procedures to produce reports on BIOS info.
 */

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerHavingSerialNumber')
	DROP PROCEDURE ComputerHavingSerialNumber
GO
CREATE PROCEDURE ComputerHavingSerialNumber
	@RDomDN              nvarchar(101) = '%',
	@ROUDN               nvarchar(401) = '%',
	@ComputerCN          nvarchar(64) = '%',
	@BIOSManufacturer    nvarchar(500) = '%',
	@SerialNumber        nvarchar(500) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cb.Manufacturer AS BIOSManufacturer,
		cb.SerialNumber,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerBios AS cb
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cb.ComputerID
	WHERE	dbo.LikeNullable(cb.SerialNumber, @SerialNumber) = 1
	  AND	dbo.LikeNullable(cb.Manufacturer, @BIOSManufacturer) = 1
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerLackingSerialNumber')
	DROP PROCEDURE ComputerLackingSerialNumber
GO
CREATE PROCEDURE ComputerLackingSerialNumber
	@RDomDN	            nvarchar(101) = '%',
	@ROUDN              nvarchar(401) = '%',
	@ComputerCN         nvarchar(64) = '%',
	@BIOSManufacturer   nvarchar(500) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cb.Manufacturer AS BIOSManufacturer,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerBios AS cb
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cb.ComputerID
	WHERE	cb.SerialNumber IS NULL
	  AND	dbo.LikeNullable(cb.Manufacturer, @BIOSManufacturer) = 1
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByBIOSManufacturer')
	DROP PROCEDURE ComputerCountByBIOSManufacturer
GO
CREATE PROCEDURE ComputerCountByBIOSManufacturer
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@BIOSManufacturer	nvarchar(500) = '%'
AS
	SELECT	COUNT(cd.ComputerID) as ComputerCount,
		cb.Manufacturer AS BIOSManufacturer
	FROM	ComputerBios AS cb
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = cb.ComputerID
	WHERE	dbo.LikeNullable(cb.Manufacturer, @BIOSManufacturer) = 1
	GROUP BY cb.Manufacturer
GO

-- Advanced Configuration and Power Interface
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerHavingACPI')
	DROP PROCEDURE ComputerHavingACPI
GO
CREATE PROCEDURE ComputerHavingACPI
	@RDomDN	nvarchar(101) = '%',
	@ROUDN	nvarchar(401) = '%',
	@ComputerCN    nvarchar(64) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerBios AS cb
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cb.ComputerID
	WHERE	cb.ACPI = 1
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerLackingACPI')
	DROP PROCEDURE ComputerLackingACPI
GO
CREATE PROCEDURE ComputerLackingACPI
	@RDomDN	nvarchar(101) = '%',
	@ROUDN	nvarchar(401) = '%',
	@ComputerCN    nvarchar(64) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerBios AS cb
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cb.ComputerID
	WHERE	cb.ACPI = 0
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerUnknownACPI')
	DROP PROCEDURE ComputerUnknownACPI
GO
CREATE PROCEDURE ComputerUnknownACPI
	@RDomDN	nvarchar(101) = '%',
	@ROUDN	nvarchar(401) = '%',
	@ComputerCN    nvarchar(64) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerBios AS cb
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cb.ComputerID
	WHERE	cb.ACPI IS NULL
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByACPI')
	DROP PROCEDURE ComputerCountByACPI
GO
CREATE PROCEDURE ComputerCountByACPI
	@RDomDN	nvarchar(101) = '%',
	@ROUDN	nvarchar(401) = '%'
AS
	SELECT	SUM(CASE WHEN cb.ACPI = 1 THEN 1 ELSE 0 END) AS Supported,
		SUM(CASE WHEN cb.ACPI = 0 THEN 1 ELSE 0 END) AS Unsupported,
		SUM(CASE WHEN cb.ACPI IS NULL THEN 1 ELSE 0 END) AS Unknown
	FROM	ComputerBios AS cb
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = cb.ComputerID
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerHavingBootableCD')
	DROP PROCEDURE ComputerHavingBootableCD
GO
CREATE PROCEDURE ComputerHavingBootableCD
	@RDomDN	nvarchar(101) = '%',
	@ROUDN	nvarchar(401) = '%',
	@ComputerCN    nvarchar(64) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerBios AS cb
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cb.ComputerID
	WHERE	cb.BootCD = 1
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerLackingBootableCD')
	DROP PROCEDURE ComputerLackingBootableCD
GO
CREATE PROCEDURE ComputerLackingBootableCD
	@RDomDN	nvarchar(101) = '%',
	@ROUDN	nvarchar(401) = '%',
	@ComputerCN    nvarchar(64) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerBios AS cb
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cb.ComputerID
	WHERE	cb.BootCD = 0
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerUnknownBootableCD')
	DROP PROCEDURE ComputerUnknownBootableCD
GO
CREATE PROCEDURE ComputerUnknownBootableCD
	@RDomDN	nvarchar(101) = '%',
	@ROUDN	nvarchar(401) = '%',
	@ComputerCN    nvarchar(64) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerBios AS cb
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cb.ComputerID
	WHERE	cb.BootCD IS NULL
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByBootableCD')
	DROP PROCEDURE ComputerCountByBootableCD
GO
CREATE PROCEDURE ComputerCountByBootableCD
	@RDomDN	nvarchar(101) = '%',
	@ROUDN	nvarchar(401) = '%'
AS
	SELECT	SUM(CASE WHEN cb.BootCD = 1 THEN 1 ELSE 0 END) AS Supported,
		SUM(CASE WHEN cb.BootCD = 0 THEN 1 ELSE 0 END) AS Unsupported,
		SUM(CASE WHEN cb.BootCD IS NULL THEN 1 ELSE 0 END) AS Unknown
	FROM	ComputerBios AS cb
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = cb.ComputerID
GO
/*
 * $Id: ComputerActivity.sql 84480 2007-07-24 06:34:27Z pca $
 *
 * Stored procedures to produce reports on Computer System info.
 */

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByDomainRole')
	DROP PROCEDURE ComputerByDomainRole
GO
CREATE PROCEDURE ComputerByDomainRole
	@RDomDN		nvarchar(101) = '%',
	@ROUDN		nvarchar(401) = '%',
	@ComputerCN	nvarchar(64) = '%',
	@DomainRole	nvarchar(101) = '%',
	@NT4DomainName	nvarchar(101) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cs.Domain AS NT4DomainName,
		cs.DomainRole,
		cd.OURDN AS OU,
		cd.DomainDN AS Domain
	FROM	(SELECT cd.*
		 FROM	ComputerDirectory AS cd
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		LEFT OUTER JOIN
		ComputerSystem AS cs
		ON cd.ComputerID = cs.ComputerID
	WHERE	dbo.LikeNullable(DomainRole, @DomainRole) = 1
	  AND	dbo.LikeNullable(cs.Domain, @NT4DomainName) = 1
	ORDER BY ComputerCN
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByDomainRole')
	DROP PROCEDURE ComputerCountByDomainRole
GO
CREATE PROCEDURE ComputerCountByDomainRole
	@RDomDN		nvarchar(101) = '%',
	@ROUDN		nvarchar(401) = '%',
	@DomainRole	nvarchar(101) = '%'
AS
	SELECT	cs.Domain AS NT4DomainName,
		cs.DomainRole,
		cd.DomainDNReverse AS RDomDN,
		COUNT(*) AS ComputerCount
	FROM	(SELECT cd.*
		 FROM	ComputerDirectory AS cd
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		LEFT OUTER JOIN
		ComputerSystem AS cs
		ON cd.ComputerID = cs.ComputerID
	WHERE	dbo.LikeNullable(DomainRole, @DomainRole) = 1
	GROUP BY cs.Domain, DomainRole, DomainDNReverse
	ORDER BY cs.Domain, DomainRole, DomainDNReverse
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByDomain')
	DROP PROCEDURE ComputerCountByDomain
GO
CREATE PROCEDURE ComputerCountByDomain
	@RDomDN		nvarchar(101) = '%'
AS
	SELECT	DomainDN AS Domain,
			DomainDNReverse AS RDomDN,
			COUNT(*) AS ComputerCount
	FROM	ComputerDirectory
	WHERE	DomainDNReverse LIKE @RDomDN
	GROUP BY DomainDN, DomainDNReverse
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByInventoryDate')
	DROP PROCEDURE ComputerByInventoryDate
GO
CREATE PROCEDURE ComputerByInventoryDate
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN	    nvarchar(64) = '%',
	@InventoryAgeMin	int = NULL,
	@InventoryAgeMax	int = 0,
	@InventoryDateMin	datetime = NULL,
	@InventoryDateMax	datetime = 0
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		i.InventoryDate,
		i.InventoryAge
	FROM	(SELECT cd.*
		 FROM	ComputerDirectory AS cd
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		LEFT OUTER JOIN
		(SELECT	ComputerID,
			MAX(CASE WHEN SWDate > HWDate THEN SWDate ELSE HWDate END)
			AS InventoryDate,
			DATEDIFF(day, MAX(CASE WHEN SWDate > HWDate THEN SWDate ELSE HWDate END), getdate())
			AS InventoryAge
		 FROM	InventoryReport
		 GROUP BY ComputerID
		) AS i
		ON cd.ComputerID = i.ComputerID
	WHERE dbo.RangeMatchDate(
			i.InventoryDate,
			@InventoryDateMin,
			@InventoryDateMax
		) = 1
	  AND	dbo.RangeMatchInt(
	  		DATEDIFF(day, i.InventoryDate, getdate()),
			@InventoryAgeMin,
			@InventoryAgeMax
		) = 1
	ORDER BY i.InventoryAge DESC, cd.ComputerCN
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByInventoryDateCategory')
	DROP PROCEDURE ComputerByInventoryDateCategory
GO
CREATE PROCEDURE ComputerByInventoryDateCategory
	@RDomDN		nvarchar(101) = '%',
	@ROUDN		nvarchar(401) = '%'
AS
	SELECT	CASE
		WHEN InventoryAgeMin < 0
			THEN 'FUTURE'
		WHEN InventoryAgeMin < 28
			THEN STR(InventoryAgeMin/7, 1)+'+ week(s)'
		ELSE REPLACE(STR((InventoryAgeMin+30)*12/365, 4), ' ', '')+'+ month(s)'
		END AS InventoryAgeCategory,
		MIN(LastDate) AS InventoryDateMin,
		i.InventoryAgeMin,
		i.InventoryAgeMax,
		COUNT(cd.ComputerID) AS ComputerCount
	FROM	(SELECT *
		 FROM	ComputerDirectory AS cd
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		LEFT OUTER JOIN
		(SELECT	*,
			CASE
			WHEN DaysSinceLastInventory IS NULL
				THEN NULL
			WHEN DaysSinceLastInventory < 0
				THEN -10000000
			WHEN DaysSinceLastInventory < 28
				THEN DaysSinceLastInventory/7*7
			WHEN DaysSinceLastInventory < 61
				THEN 28
			ELSE (DaysSinceLastInventory*12)/365*365/12+1
			END AS InventoryAgeMin,
			CASE
			WHEN DaysSinceLastInventory IS NULL
				THEN NULL
			WHEN DaysSinceLastInventory < 0
				THEN 0
			WHEN DaysSinceLastInventory < 28
				THEN DaysSinceLastInventory/7*7+6
			WHEN DaysSinceLastInventory < 61
				THEN 60
			ELSE ((DaysSinceLastInventory*12)/365+1)*365/12
			END AS InventoryAgeMax
		 FROM	(SELECT	ComputerID,
				MAX(CASE WHEN SWDate > HWDate THEN SWDate ELSE HWDate END)
				AS LastDate,
				DATEDIFF(day, MAX(CASE WHEN SWDate > HWDate THEN SWDate ELSE HWDate END), getdate())
				AS DaysSinceLastInventory
			 FROM	InventoryReport
			 GROUP BY ComputerID
			) AS i
		) AS i
		ON cd.ComputerID = i.ComputerID
	GROUP BY i.InventoryAgeMin, i.InventoryAgeMax
	ORDER BY MIN(LastDate), MAX(i.DaysSinceLastInventory)
GO
/*
 * $Id: ComputerModel.sql 84480 2007-07-24 06:34:27Z pca $
 *
 * Stored procedures to produce reports on Computer System info.
 */

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByManufacturer')
	DROP PROCEDURE ComputerByManufacturer
GO
CREATE PROCEDURE ComputerByManufacturer
	@RDomDN		nvarchar(101) = '%',
	@ROUDN		nvarchar(401) = '%',
	@ComputerCN nvarchar(64) = '%',
	@Manufacturer	nvarchar(500) = '%',
	@Model		nvarchar(500) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cs.Manufacturer,
		cs.Model,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerSystem AS cs
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cs.ComputerID
	WHERE	dbo.LikeNullable(cs.Manufacturer, @Manufacturer) = 1
	  AND	dbo.LikeNullable(cs.Model, @Model) = 1
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByManufacturer')
	DROP PROCEDURE ComputerCountByManufacturer
GO
CREATE PROCEDURE ComputerCountByManufacturer
	@RDomDN	nvarchar(101) = '%',
	@ROUDN	nvarchar(401) = '%',
	@Manufacturer	nvarchar(500) = '%'
AS
	SELECT	Count(DISTINCT cd.ComputerID) AS ComputerCount,
		cs.Manufacturer
	FROM	ComputerSystem AS cs
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = cs.ComputerID
	WHERE	dbo.LikeNullable(cs.Manufacturer, @Manufacturer) = 1
	GROUP BY cs.Manufacturer
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByManufacturerModel')
	DROP PROCEDURE ComputerCountByManufacturerModel
GO
CREATE PROCEDURE ComputerCountByManufacturerModel
	@RDomDN	nvarchar(101) = '%',
	@ROUDN	nvarchar(401) = '%',
	@Manufacturer	nvarchar(500) = '%',
	@Model	nvarchar(500) = '%'
AS
	SELECT	Count(DISTINCT cd.ComputerID) AS ComputerCount,
		cs.Manufacturer,
		cs.Model
	FROM	ComputerSystem AS cs
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = cs.ComputerID
	WHERE	dbo.LikeNullable(cs.Manufacturer, @Manufacturer) = 1
	  AND	dbo.LikeNullable(cs.Model, @Model) = 1
	GROUP BY cs.Manufacturer, cs.Model
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByChassisType')
	DROP PROCEDURE ComputerByChassisType
GO
CREATE PROCEDURE ComputerByChassisType
	@RDomDN		nvarchar(101) = '%',
	@ROUDN		nvarchar(401) = '%',
	@ComputerCN	nvarchar(64) = '%',
	@ChassisTypes	nvarchar(101) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		ce.ChassisTypes,
		cd.OURDN AS OU,
		cd.DomainDN AS Domain
	FROM	(SELECT cd.*
		 FROM	ComputerDirectory AS cd
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		LEFT OUTER JOIN
		ComputerSystemEnclosure AS ce
		ON cd.ComputerID = ce.ComputerID
	WHERE	dbo.LikeNullable(ce.ChassisTypes, @ChassisTypes) = 1
	ORDER BY ComputerCN
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByChassisType')
	DROP PROCEDURE ComputerCountByChassisType
GO
CREATE PROCEDURE ComputerCountByChassisType
	@RDomDN		nvarchar(101) = '%',
	@ROUDN		nvarchar(401) = '%',
	@ChassisTypes	nvarchar(101) = '%'
AS
	SELECT	ce.ChassisTypes,
		COUNT(*) AS ComputerCount
	FROM	(SELECT cd.*
		 FROM	ComputerDirectory AS cd
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		LEFT OUTER JOIN
		ComputerSystemEnclosure AS ce
		ON cd.ComputerID = ce.ComputerID
	WHERE	dbo.LikeNullable(ce.ChassisTypes, @ChassisTypes) = 1
	GROUP BY ce.ChassisTypes
	ORDER BY ce.ChassisTypes
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByMappedNetworkDrive')
	DROP PROCEDURE ComputerByMappedNetworkDrive
GO
CREATE PROCEDURE ComputerByMappedNetworkDrive
	@RDomDN		NVARCHAR(101) = '%',
	@ROUDN		NVARCHAR(401) = '%',
	@ComputerCN	NVARCHAR(200) = '%',
	@MappedDrive	NVARCHAR(20) = '%'
AS
SELECT	cd.ComputerID,
	cd.ComputerCN, 
	LogicalDisk.HardwareName AS MappedDrive, 
	LogicalDisk.ProviderName AS MappedDriveDetails, 
	LogicalDisk.FileSystem, 
	LogicalDisk.[Size] AS SizeBytes, 
	LogicalDisk.FreeSpace AS FreeSpaceBytes,
	cd.OURDN AS OU,
	cd.DomainDN AS Domain

FROM	(SELECT cd.*
	 FROM	ComputerDirectory AS cd
	 WHERE	DomainDNReverse LIKE @RDomDN
	   AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
	   AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
	) AS cd
	LEFT OUTER JOIN	LogicalDisk 
	ON cd.ComputerID = LogicalDisk.ComputerID	

WHERE	LogicalDisk.[Description] LIKE N'Network Connection'
  AND	dbo.LikeNullable(LogicalDisk.ProviderName, @MappedDrive) = 1

GO
/*
 * $Id: ComputerSummary.sql 88956 2008-08-18 06:51:01Z tma $
 *
 * Stored procedures to produce summary of one computer
 */

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerSummary')
	DROP PROCEDURE ComputerSummary
GO
CREATE PROCEDURE ComputerSummary
	@ComputerID	int
AS
	/* Directory */
		SELECT	0 AS CategoryID,
			'Identification' AS Category,
			'ComputerCN' AS Property,
			(SELECT ComputerCN
			 FROM	ComputerDirectory
			 WHERE	ComputerID = @ComputerID
			) AS Value
	UNION	SELECT	1 AS CategoryID,
			'Identification' AS Category,
			'OrganizationalUnit' AS Property,
			(SELECT OURDN
			 FROM	ComputerDirectory
			 WHERE	ComputerID = @ComputerID
			) AS Value
	UNION	SELECT	2 AS CategoryID,
			'Identification' AS Category,
			'DomainDN' AS Property,
			(SELECT DomainDN
			 FROM	ComputerDirectory
			 WHERE	ComputerID = @ComputerID
			) AS Value
	/* Domain */
	UNION	SELECT	3 AS CategoryID,
			'Role' AS Category,
			'NT4DomainName' AS Property,
			(SELECT Domain
			 FROM	ComputerSystem
			 WHERE	ComputerID = @ComputerID
			) AS Value
	UNION	SELECT	4 AS CategoryID,
			'Role' AS Category,
			'DomainRole' AS Property,
			(SELECT DomainRole
			 FROM	ComputerSystem
			 WHERE	ComputerID = @ComputerID
			) AS Value

	/* System model and Manufacturer */
	UNION	SELECT	5 AS CategoryID,
			'Type' AS Category,
			'Manufacturer' AS Property,
			(SELECT Manufacturer
			 FROM	ComputerSystem
			 WHERE	ComputerID = @ComputerID
			) AS Value
	UNION	SELECT	6 AS CategoryID,
			'Type' AS Category,
			'Model' AS Property,
			(SELECT Model
			 FROM	ComputerSystem
			 WHERE	ComputerID = @ComputerID
			) AS Value

	/* System Chassis Type */
	UNION	SELECT	7 AS CategoryID,
			'Type' AS Category,
			'ChassisType' AS Property,
			ChassisTypes AS Value
		FROM	(SELECT ChassisTypes
			 FROM	ComputerSystemEnclosure
			 WHERE	ComputerID = @ComputerID
			) AS chassis
	/* BIOS */
	UNION	SELECT	10 AS CategoryID,
			'BIOS' AS Category,
			'SerialNumber' AS Property,
			(SELECT SerialNumber
			 FROM	ComputerBIOS
			 WHERE	ComputerID = @ComputerID
			) AS Value
/*	UNION	SELECT	10 AS CategoryID,
			'BIOS' AS Category,
			'BIOSManufacturer' AS Property,
			(SELECT Manufacturer
			 FROM	ComputerBIOS
			 WHERE	ComputerID = @ComputerID
			) AS Value
	UNION	SELECT	10 AS CategoryID,
			'BIOS' AS Category,
			'SupportsACPI' AS Property,
			(SELECT CASE WHEN ACPI = 1 THEN '1' ELSE '0' END
			 FROM	ComputerBios
			 WHERE	ComputerID = @ComputerID
			) AS Value
	UNION	SELECT	10 AS CategoryID,
			'BIOS' AS Category,
			'BootableCD' AS Property,
			(SELECT CASE WHEN BootCD = 1 THEN '1' ELSE '0' END
			 FROM	ComputerBios
			 WHERE	ComputerID = @ComputerID
			) AS Value
*/

	/* OperatingSystem */
	UNION	SELECT	20 AS CategoryID,
			'OperatingSystem' AS Category,
			'OperatingSystem' AS Property,
			(SELECT HardwareName
			 FROM	ComputerOperatingSystem
			 WHERE	ComputerID = @ComputerID
			) AS Value
	UNION	SELECT	21 AS CategoryID,
			'OperatingSystem' AS Category,
			'OSServicePack' AS Property,
			(SELECT CSDVersion
			 FROM	ComputerOperatingSystem
			 WHERE	ComputerID = @ComputerID
			) AS Value

	/* Memory */
	UNION	SELECT	30 AS CategoryID,
			'Memory' AS Category,
			'MemoryBytes' AS Property,
			(SELECT REPLACE(STR(
					CAST(TotalPhysicalMemory/1048576 AS int)
				, 20), ' ', '') + 'MB'
			 FROM	ComputerSystem
			 WHERE	ComputerID = @ComputerID
			) AS Value
/*	UNION	SELECT	31 AS CategoryID,
			'Memory' AS Category,
			'PhysicalMemoryBytes' AS Property,
			(SELECT REPLACE(STR(
					CAST(SUM(CASE WHEN Capacity IS NOT NULL THEN Capacity ELSE 0 END)/1048576 AS INT)
				, 20), ' ', '') + 'MB'
			 FROM	PhysicalMemory
			 WHERE	ComputerID = @ComputerID
			) AS Value
	UNION	SELECT	32 AS CategoryID,
			'Memory' AS Category,
			'PhysicalMemoryCardCount' AS Property,
			(SELECT REPLACE(STR(
					SUM(CASE WHEN ComputerID IS NOT NULL THEN 1 ELSE 0 END)
				, 20), ' ', '')
			 FROM	PhysicalMemory
			 WHERE	ComputerID = @ComputerID
			) AS Value
	UNION	SELECT	33 AS CategoryID,
			'Memory' AS Category,
			'PhysicalMemoryType' AS Property,	-- Assume it's all the same type
			(SELECT	MAX(CASE WHEN MemoryType IS NOT NULL THEN MemoryType ELSE '' END)
			 FROM	PhysicalMemory
			 WHERE	ComputerID = @ComputerID
			) AS Value
	UNION	SELECT	34 AS CategoryID,
			'Memory' AS Category,
			'PhysicalMemorySpeed' AS Property,
			(SELECT	REPLACE(STR(
					MAX(CASE WHEN Speed IS NOT NULL THEN Speed ELSE 0 END)
				, 20), ' ', '')
			 FROM	PhysicalMemory
			 WHERE	ComputerID = @ComputerID
			) AS Value
*/

	/* Processor */
	UNION	SELECT	40 AS CategoryID,
			'Processor' AS Category,
			'ProcessorType' AS Property,
			(CASE WHEN EXISTS (
					SELECT NumberOfProcessors
					FROM   ComputerSystem
					WHERE  ComputerID = @ComputerID
					  AND	NumberOfProcessors > 1
				)
			THEN	'('+
				(SELECT TOP 1 REPLACE(STR(NumberOfProcessors,20), ' ', '')
				 FROM	ComputerSystem
				 WHERE	ComputerID = @ComputerID
				)+
				'x) '
			ELSE	''
			END)
			+
			(SELECT TOP 1 dbo.CIMProcessorType(
					MAX(Name),
					MAX(Description),
					MAX(Manufacturer),
					MAX(Version)
				)
			 FROM	ComputerProcessor
			 WHERE	ComputerID = @ComputerID
			)
			AS Value
/*	UNION	SELECT	41 AS CategoryID,
			'Processor' AS Category,
			'NumberOfProcessors' AS Property,
			(SELECT TOP 1 REPLACE(STR(NumberOfProcessors,20), ' ', '')
			 FROM	ComputerSystem
			 WHERE	ComputerID = @ComputerID
			) AS Value
*/	UNION	SELECT	42 AS CategoryID,
			'Processor' AS Category,
			'MaxClockSpeed' AS Property,
			(SELECT TOP 1
				REPLACE(STR(MaxClockSpeed,20), ' ', '') + 'MHz'
			 FROM	ComputerProcessor
			 WHERE	ComputerID = @ComputerID
			) AS Value

	/* System Partition */
	UNION	SELECT	50 AS CategoryID,
			'Partitions' AS Category,
			'SystemPartitionSizeBytes' AS Property,
			(SELECT	REPLACE(STR(
					CAST(ld.Size/1048576 AS INT)
				, 20), ' ', '') + 'MB'
			 FROM	LogicalDisk as ld,
				ComputerOperatingSystem as cs
			 WHERE	ld.ComputerID = @ComputerID
			   AND	cs.ComputerID = @ComputerID
			   AND	ISNULL( ISNULL(	LEFT(cs.SystemDirectory, 2),
				                LEFT(cs.WindowsDirectory, 2)),
			                cs.SystemDevice
				) = ld.HardwareName
			) AS Value
	UNION	SELECT	51 AS CategoryID,
			'Partitions' AS Category,
			'SystemPartitionFreeBytes' AS Property,
			(SELECT	REPLACE(STR(
					CAST(ld.FreeSpace/1048576 AS INT)
				, 20), ' ', '') + 'MB'
			 FROM	LogicalDisk as ld,
				ComputerOperatingSystem as cs
			 WHERE	ld.ComputerID = @ComputerID
			   AND	cs.ComputerID = @ComputerID
			   AND	ISNULL( ISNULL(	LEFT(cs.SystemDirectory, 2),
				                LEFT(cs.WindowsDirectory, 2)),
			                cs.SystemDevice
				) = ld.HardwareName
			) AS Value
	UNION	SELECT	52 AS CategoryID,
			'Partitions' AS Category,
			'SystemPartitionFileSystem' AS Property,
			(SELECT	ld.FileSystem
			 FROM	LogicalDisk as ld,
				ComputerOperatingSystem as cs
			 WHERE	ld.ComputerID = @ComputerID
			   AND	cs.ComputerID = @ComputerID
			   AND	ISNULL( ISNULL(	LEFT(cs.SystemDirectory, 2),
				                LEFT(cs.WindowsDirectory, 2)),
			                cs.SystemDevice
				) = ld.HardwareName
			) AS Value
/*	UNION	SELECT	53 AS CategoryID,
			'Partitions' AS Category,
			'PartitionCount' AS Property,
			(SELECT	REPLACE(STR(
					COUNT(CASE WHEN ComputerID IS NULL THEN 0 ELSE 1 END)
				, 20), ' ', '')
			 FROM	LogicalDisk
			 WHERE	ComputerID = @ComputerID
			   AND	Description NOT LIKE '%Floppy%'
			   AND	Description NOT LIKE 'Removable%'
			   AND	Description <> 'Network Connection'
			   AND	Description <> 'CD-ROM Disc'
			   AND	Description <> 'RAM Disk'
			) AS Value
*/	/* Physical disk drives */
/*	UNION	SELECT	60 AS CategoryID,
			'Drives' AS Category,
			'DiskDriveCount' AS Property,
			REPLACE(STR(
				COUNT(*)
			, 20), ' ', '') AS Value
		FROM	DiskDrive
		WHERE	ComputerID = @ComputerID
		  AND	InterfaceType <> 'USB'
*/	UNION	SELECT	61 AS CategoryID,
			'Drives' AS Category,
			'DiskSizeBytes' AS Property,
			REPLACE(STR(
				CAST(Size/1048576 AS INT)
			, 20), ' ', '') + 'MB'
			+ CASE WHEN Model IS NOT NULL
				THEN ' ('+Model+')'
				ELSE ''
			END
			AS Value
		FROM	DiskDrive
		WHERE	ComputerID = @ComputerID
		  AND	ISNULL(InterfaceType,'') <> 'USB'
	/* CDROM */
/*	UNION	SELECT	70 AS CategoryID,
			'Drives' AS Category,
			'HasCDWriter' AS Property,
			CASE WHEN EXISTS(
				SELECT	*
				FROM	CDROMDrive
				WHERE	ComputerID = @ComputerID
				  AND (	Writable <> 0
				     OR HardwareName LIKE '%[-+ ]RW%'
				     OR HardwareName LIKE '%Writer%'
				  )
			) THEN '1' ELSE '0' END AS Value
	UNION	SELECT	71 AS CategoryID,
			'Drives' AS Category,
			'HasDVDDrive' AS Property,
			CASE WHEN EXISTS(
				SELECT	*
				FROM	CDROMDrive
				WHERE	ComputerID = @ComputerID
				  AND	HardwareName LIKE '%DVD%'
			) THEN '1' ELSE '0' END AS Value
*/	/* Network */
	UNION	SELECT	80 AS CategoryID,
			'Network' AS Category,
			'IPAddress' AS Property,
			IPAddress
			+ ' (net '
			+ dbo.IPAddressToString(IPNetworkAddr)
			+ '/' + REPLACE(STR(IPNetworkSize, 3), ' ', '')
			+ ')'
			AS Value
		FROM	(	-- Many adapters are listed multiple times, de-dup.
			SELECT	IPAddress,
				dbo.IPNetworkSize(dbo.IPAddressFromString(IPSubnet))
				AS IPNetworkSize,
				(dbo.IPAddressFromString(IPAddress) & dbo.IPAddressFromString(IPSubnet))
				AS IPNetworkAddr,
				MACAddress
			 FROM	NetworkAdapterConfiguration
			 WHERE	ComputerID = @ComputerID
			   AND	IPSubnet IS NOT NULL
			 GROUP BY ComputerID,
				IPAddress, IPSubnet, MACAddress
			) AS net_a
/*
	UNION	SELECT	81 AS CategoryID,
			'Network' AS Category,
			'IPNetwork' AS Property,
			dbo.IPAddressToString(IPNetworkAddr) + '/' +
				REPLACE(STR(IPNetworkSize, 3), ' ', '')
			AS Value
		FROM	(	-- Many adapters are listed multiple times, de-dup.
			SELECT	IPAddress,
				dbo.IPNetworkSize(dbo.IPAddressFromString(IPSubnet))
				AS IPNetworkSize,
				(dbo.IPAddressFromString(IPAddress) & dbo.IPAddressFromString(IPSubnet))
				AS IPNetworkAddr,
				MACAddress
			 FROM	NetworkAdapterConfiguration
			 WHERE	ComputerID = @ComputerID
			   AND	IPSubnet IS NOT NULL
			 GROUP BY ComputerID,
				IPAddress, IPSubnet, MACAddress
			) AS net_b
*/

	UNION	SELECT	82 AS CategoryID,
			'Network' AS Category,
			'MACAddress' AS Property,
			MACAddress AS Value
		FROM	(	-- Many adapters are listed multiple times, de-dup.
			SELECT	IPAddress,
				dbo.IPNetworkSize(dbo.IPAddressFromString(IPSubnet))
				AS IPNetworkSize,
				(dbo.IPAddressFromString(IPAddress) & dbo.IPAddressFromString(IPSubnet))
				AS IPNetworkAddr,
				MACAddress
			 FROM	NetworkAdapterConfiguration
			 WHERE	ComputerID = @ComputerID
			   AND	IPSubnet IS NOT NULL
			 GROUP BY ComputerID,
				IPAddress, IPSubnet, MACAddress
			) AS net_c

	/* Inventory */
	/* The following are commented by Tim at 2006-04-07 due to transforming  LastInventory formater to "YYYY-MM-DDThh:mm:ss:fff"
	*UNION	SELECT	90 AS CategoryID,
	*		'Inventory' AS Category,
	*		'LastInventory' AS Property,
	*		(SELECT	CONVERT(NVARCHAR, MAX(CASE WHEN SWDate > HWDate THEN SWDate ELSE HWDate END))
	*		 FROM	InventoryReport
	*		 WHERE	ComputerID = @ComputerID
	*		   AND	UserID = 1
	*		) AS Value
	*/
	/*The following are added by Tim at 2006-04-07*/		
	UNION	SELECT	90 AS CategoryID,
			'Inventory' AS Category,
			'LastInventory' AS Property,
			(SELECT	CONVERT(NVARCHAR, MAX(CASE WHEN SWDate > HWDate THEN SWDate ELSE HWDate END),126)
			 FROM	InventoryReport
			 WHERE	ComputerID = @ComputerID
			   AND	UserID = 1
			) AS Value
/*	UNION	SELECT	90 AS CategoryID,
			'Inventory' AS Category,
			'LastSoftwareInventory' AS Property,
			(SELECT	CONVERT(NVARCHAR, SWDate)
			 FROM	InventoryReport
			 WHERE	ComputerID = @ComputerID
			   AND	UserID = 1
			) AS Value
	UNION	SELECT	90 AS CategoryID,
			'Inventory' AS Category,
			'LastHardwareInventory' AS Property,
			(SELECT	CONVERT(NVARCHAR, HWDate)
			 FROM	InventoryReport
			 WHERE	ComputerID = @ComputerID
			   AND	UserID = 1
			) AS Value
	UNION	SELECT	90 AS CategoryID,
			'Inventory' AS Category,
			'LastUserInventory' AS Property,
			(SELECT	CONVERT(NVARCHAR, MAX(CASE WHEN SWDate > HWDate THEN SWDate ELSE HWDate END))
			 FROM	InventoryReport
			 WHERE	ComputerID = @ComputerID
			   AND	UserID <> 1
			) AS Value
	UNION	SELECT	90 AS CategoryID,
			'Inventory' AS Category,
			'InventoryAge' AS Property,
			(SELECT	REPLACE(STR(
				DATEDIFF(day, MAX(CASE WHEN SWDate > HWDate THEN SWDate ELSE HWDate END), getdate())
			, 20), ' ', '')
			 FROM	InventoryReport
			 WHERE	ComputerID = @ComputerID
			) AS Value
*/
	OPTION(ROBUST PLAN)

GO
/*
 * $Id: MediaController.sql 55704 2004-06-16 00:53:46Z pca $
 *
 * Stored procedures to produce reports on Computer Media Controller info.
 */

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByVideoController')
	DROP PROCEDURE ComputerByVideoController
GO
CREATE PROCEDURE ComputerByVideoController
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%',
	@VideoControllerType		nvarchar(200) = '_%'
AS
	SELECT	ComputerID,
		ComputerCN,
		VideoControllerType,
		AdapterRAMBytes
	FROM	(SELECT	cd.ComputerID,
			cd.ComputerCN,
			vc.HardwareName AS VideoControllerType,
			vc.AdapterRAM as AdapterRAMBytes
		FROM	VideoController as vc
			RIGHT OUTER JOIN
			(SELECT * FROM ComputerDirectory
			 WHERE	DomainDNReverse LIKE @RDomDN
			  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
			  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
			) AS cd
			ON cd.ComputerID = vc.ComputerID
		) as cd
	WHERE	dbo.LikeNullable(VideoControllerType, @VideoControllerType) = 1
	ORDER BY ComputerCN
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByVideoControllerType')
	DROP PROCEDURE ComputerCountByVideoControllerType
GO
CREATE PROCEDURE ComputerCountByVideoControllerType
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@VideoControllerType		nvarchar(200) = '%'
AS
	SELECT	VideoControllerType,
		AdapterRAMBytes,
		COUNT(DISTINCT ComputerID) AS ComputerCount
	FROM	(SELECT	cd.ComputerID,
			vc.HardwareName AS VideoControllerType,
			vc.AdapterRAM as AdapterRAMBytes
		FROM	VideoController as vc
			RIGHT OUTER JOIN
			(SELECT * FROM ComputerDirectory
			 WHERE	DomainDNReverse LIKE @RDomDN
			  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
			) AS cd
			ON cd.ComputerID = vc.ComputerID
		) as CD
	WHERE	dbo.LikeNullable(VideoControllerType, @VideoControllerType) = 1
	GROUP BY VideoControllerType, AdapterRAMBytes
	ORDER BY VideoControllerType, AdapterRAMBytes
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerBySoundDevice')
	DROP PROCEDURE ComputerBySoundDevice
GO
CREATE PROCEDURE ComputerBySoundDevice
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%',
	@SoundDeviceType	nvarchar(200) = '_%'
AS
	SELECT	ComputerID,
		ComputerCN,
		SoundDeviceType
	FROM	(SELECT	cd.ComputerID,
			cd.ComputerCN,
			vc.HardwareName AS SoundDeviceType
		FROM	Win32_SoundDevice as vc
			RIGHT OUTER JOIN
			(SELECT * FROM ComputerDirectory
			 WHERE	DomainDNReverse LIKE @RDomDN
			  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
			  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
			) AS cd
			ON cd.ComputerID = vc.ComputerID
		) as cd
	WHERE	dbo.LikeNullable(SoundDeviceType, @SoundDeviceType) = 1
	ORDER BY ComputerCN
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountBySoundDeviceType')
	DROP PROCEDURE ComputerCountBySoundDeviceType
GO
CREATE PROCEDURE ComputerCountBySoundDeviceType
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@SoundDeviceType	nvarchar(200) = '%'
AS
	SELECT	SoundDeviceType,
		COUNT(DISTINCT ComputerID) AS ComputerCount
	FROM	(SELECT	cd.ComputerID,
			vc.HardwareName AS SoundDeviceType
		FROM	Win32_SoundDevice as vc
			RIGHT OUTER JOIN
			(SELECT * FROM ComputerDirectory
			 WHERE	DomainDNReverse LIKE @RDomDN
			  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
			) AS cd
			ON cd.ComputerID = vc.ComputerID
		) as CD
	WHERE	dbo.LikeNullable(SoundDeviceType, @SoundDeviceType) = 1
	GROUP BY SoundDeviceType
	ORDER BY SoundDeviceType
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountBySoundDevice')
	DROP PROCEDURE ComputerCountBySoundDevice
GO
CREATE PROCEDURE ComputerCountBySoundDevice
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%'
AS
	SELECT	SUM(CASE WHEN vc.HardwareName IS NULL THEN 0 ELSE 1 END) AS Supported,
		SUM(CASE WHEN vc.HardwareName IS NULL THEN 1 ELSE 0 END) AS Unsupported
	FROM	Win32_SoundDevice as vc
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = vc.ComputerID
GO
/*
 * $Id: Memory.sql 56572 2004-07-14 03:03:45Z niteshk $
 *
 * Stored procedures to produce reports on Memory info.
 */

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByMemory')
	DROP PROCEDURE ComputerByMemory
GO
CREATE PROCEDURE ComputerByMemory
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%',
	@MemoryBytesMin		bigint = NULL,
	@MemoryBytesMax		bigint = 0
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cs.TotalPhysicalMemory AS MemoryBytes,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerSystem AS cs
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cs.ComputerID
	WHERE	dbo.RangeMatchBigint(cs.TotalPhysicalMemory, @MemoryBytesMin, @MemoryBytesMax) = 1
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountHavingMemory')
	DROP PROCEDURE ComputerCountHavingMemory
GO
CREATE PROCEDURE ComputerCountHavingMemory
	@RDomDN		nvarchar(101) = '%',
	@ROUDN		nvarchar(401) = '%',
	@MemoryBytesMin bigint = 0,
	@MemoryBytesMax bigint = NULL
AS
	SELECT	SUM(CASE WHEN cs.TotalPhysicalMemory >= @MemoryBytesMin
			 AND (cs.TotalPhysicalMemory <= @MemoryBytesMax)
			THEN 1 ELSE 0 END
		) AS MemoryInRange,
		SUM(CASE WHEN cs.TotalPhysicalMemory < @MemoryBytesMin
			 OR (cs.TotalPhysicalMemory > @MemoryBytesMax)
			THEN 1 ELSE 0 END
		) AS MemoryOutOfRange,
		SUM(CASE WHEN cs.TotalPhysicalMemory IS NULL
			THEN 1 ELSE 0 END
		) AS MemoryUnknown
	FROM	ComputerSystem AS cs
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = cs.ComputerID
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByMemory')
	DROP PROCEDURE ComputerCountByMemory
GO
CREATE PROCEDURE ComputerCountByMemory
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@CategoryIncr		bigint = 67108864
AS
	SELECT	MemoryCategory AS MemoryBytesMin,
		MemoryCategory+@CategoryIncr-1 AS MemoryBytesMax,
		Count(*) AS ComputerCount
	FROM	(SELECT	*,
			(TotalPhysicalMemory+1)/@CategoryIncr*@CategoryIncr AS MemoryCategory
		 FROM	ComputerSystem
		) AS cp
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = cp.ComputerID
	GROUP BY MemoryCategory
	ORDER BY MemoryCategory
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByMemoryType')
	DROP PROCEDURE ComputerByMemoryType
GO
CREATE PROCEDURE ComputerByMemoryType
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%',
	@MemoryType		nvarchar(64) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		CASE
		WHEN SUM(CASE WHEN pm.Capacity IS NOT NULL THEN pm.Capacity ELSE 0 END) = 0
		THEN NULL
		ELSE SUM(CASE WHEN pm.Capacity IS NOT NULL THEN pm.Capacity ELSE 0 END)
		END AS MemoryBytes,
		CASE
		WHEN SUM(CASE WHEN pm.ComputerID IS NOT NULL THEN 1 ELSE 0 END) = 0
		THEN NULL
		ELSE SUM(CASE WHEN pm.ComputerID IS NOT NULL THEN 1 ELSE 0 END)
		END AS MemoryCardCount,
		CASE
		WHEN MAX(CASE WHEN pm.MemoryType IS NOT NULL THEN pm.MemoryType ELSE '' END) = ''
		THEN NULL
		ELSE MAX(CASE WHEN pm.MemoryType IS NOT NULL THEN pm.MemoryType ELSE '' END)
		END AS MemoryType,	-- Assume it's all the same type
		CASE
		WHEN MAX(CASE WHEN pm.Speed IS NOT NULL THEN pm.Speed ELSE 0 END) = 0
		THEN NULL
		ELSE MAX(CASE WHEN pm.Speed IS NOT NULL THEN pm.Speed ELSE 0 END)
		END AS MemorySpeed,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	PhysicalMemory AS pm
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = pm.ComputerID
	WHERE	dbo.LikeNullable(MemoryType, @MemoryType) = 1
	GROUP BY cd.ComputerID, cd.ComputerCN, cd.OURDN, cd.DomainDN
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerLackingMemory')
	DROP PROCEDURE ComputerLackingMemory
GO
CREATE PROCEDURE ComputerLackingMemory
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cs.TotalPhysicalMemory AS MemoryBytes,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerSystem AS cs
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cs.ComputerID
	WHERE	cs.TotalPhysicalMemory IS NULL
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerOutsideMemoryRange')
	DROP PROCEDURE ComputerOutsideMemoryRange
GO
CREATE PROCEDURE ComputerOutsideMemoryRange
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%',
	@MemoryBytesMin		bigint = NULL,
	@MemoryBytesMax		bigint = 0
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		cs.TotalPhysicalMemory AS MemoryBytes,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerSystem AS cs
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cs.ComputerID
	WHERE	dbo.RangeMatchBigint(cs.TotalPhysicalMemory, @MemoryBytesMin, @MemoryBytesMax) = 0
	  AND	cs.TotalPhysicalMemory IS NOT NULL
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByMemoryType')
	DROP PROCEDURE ComputerCountByMemoryType
GO
CREATE PROCEDURE ComputerCountByMemoryType
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@MemoryType		nvarchar(64) = '%'
AS
	SELECT	CASE
		WHEN pm.MemoryType IS NULL
			THEN NULL	-- Computer or memory with unknown type
		WHEN pm.MemoryType NOT LIKE @MemoryType
			THEN ''		-- Type other than @MemoryType
		ELSE	pm.MemoryType	-- Requested MemoryType(s)
		END AS MemoryType,
		COUNT(*) AS MemoryCardCount,
		COUNT(DISTINCT cd.ComputerID) AS ComputerCount
	FROM	PhysicalMemory AS pm
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = pm.ComputerID
	GROUP BY CASE
		WHEN pm.MemoryType IS NULL
			THEN NULL
		WHEN pm.MemoryType NOT LIKE @MemoryType
			THEN ''
		ELSE	pm.MemoryType
		END
GO
/*
 * $Id: NetworkAdapter.sql 95576 2010-01-21 02:54:16Z rlowery $
 *
 * Stored procedures to produce reports on Network adapter info.
 *
 * The IPAddress parameter may either be an SQL LIKE match value
 * to be matched against the IPAddress field, or a network address
 * in the form ABC.DEF.GHI.JKL/MN, to be matched against the IPNetwork
 * field.
 */

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByNetwork')
	DROP PROCEDURE ComputerByNetwork
GO
CREATE PROCEDURE ComputerByNetwork
	@RDomDN		nvarchar(101) = '%',
	@ROUDN		nvarchar(401) = '%',
	@ComputerCN	nvarchar(64) = '%',
	@IPAddress	nvarchar(256) = '%'
AS
	IF @IPAddress IS NULL
	BEGIN
		SELECT cd.ComputerID,
			cd.ComputerCN,
			NULL AS IPAddress,
			NULL AS IPNetwork,
			NULL AS DefaultIPGateway,
			NULL AS DNSHostName,
			NULL AS DNSDomain,
			NULL AS MACAddress,
			NULL AS NetworkAdapterModel,
			cd.OURDN AS OrganizationalUnit,
			cd.DomainDN AS DomainDN
		FROM	ComputerDirectory AS cd
		WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		  AND NOT EXISTS(
			SELECT * FROM NetworkAdapterConfiguration AS w
			WHERE	cd.ComputerID = w.ComputerID
			  AND	w.IPAddress IS NOT NULL
			  AND	w.IPSubnet IS NOT NULL
		)
		RETURN
	END

	SELECT	cd.ComputerID,
		cd.ComputerCN,
		wnc.IPAddress,
		wnc.IPNetwork,
		wnc.DefaultIPGateway,
		wnc.DNSHostName,
		wnc.DNSDomain,
		wnc.MACAddress,
		wnc.NetworkAdapterModel,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	(	-- Many adapters are listed multiple times, de-dup.
		SELECT	ComputerID,
			IPAddress,
			IPSubnet AS IPSubnetMask,
			MAX(IPNetworkInt) AS IPNetworkInt,
			MAX(IPNetworkSize) AS IPNetworkSize,
			MAX(IPNetwork) AS IPNetwork,
			MAX(DefaultIPGateway) AS DefaultIPGateway,
			MAX(DNSHostName) AS DNSHostName,
			MAX(DNSDomain) AS DNSDomain,
			MAX(MACAddress) AS MACAddress,
			MIN(ISNULL(HardwareName, '')) AS NetworkAdapterModel
		 FROM	(SELECT	*,
				(dbo.IPAddressFromString(IPAddress) & dbo.IPAddressFromString(IPSubnet))
				AS IPNetworkInt,
				dbo.IPNetworkSize(dbo.IPAddressFromString(IPSubnet))
				AS IPNetworkSize,
				dbo.IPAddressToString(
					dbo.IPAddressFromString(IPAddress)
					& dbo.IPAddressFromString(IPSubnet)
				)
				+ '/' + REPLACE(STR(dbo.IPNetworkSize(dbo.IPAddressFromString(IPSubnet)), 3), ' ', '')
				AS IPNetwork
		 	 FROM NetworkAdapterConfiguration
			) AS w
		 WHERE	CASE
		 	WHEN CHARINDEX('/', @IPAddress) > 0 -- searching for computers in a subnet?
			THEN IPNetwork
			ELSE IPAddress
			END LIKE @IPAddress
		   AND	IPSubnet IS NOT NULL
		 GROUP BY ComputerID, IPAddress, IPSubnet
		) AS wnc
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = wnc.ComputerID
	WHERE	CASE
		WHEN CHARINDEX('/', @IPAddress) > 0 -- searching for computers in a subnet?
		THEN IPNetwork
		ELSE IPAddress
		END LIKE @IPAddress
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByNetwork')
	DROP PROCEDURE ComputerCountByNetwork
GO
CREATE PROCEDURE ComputerCountByNetwork
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@IPAddress		nvarchar(256) = '%'
AS
	SELECT	wnc.IPNetwork,
		dbo.IPAddressToString(MAX(wnc.IPNetworkInt)) AS IPNetworkAddr,
		wnc.IPNetwork AS IPAddress,	-- Filter value for drill-down
		MAX(wnc.IPNetworkSize) AS IPNetworkSize,
		MAX(wnc.IPNetworkInt) AS IPNetworkInt,
		CASE
		WHEN	wnc.IPNetwork IS NULL THEN NULL
		ELSE	SUM(CASE WHEN wnc.ComputerID IS NOT NULL THEN 1 ELSE 0 END)
		END AS AdapterCount,
		Count(DISTINCT cd.ComputerID) AS ComputerCount
	FROM	(	-- Many adapters are listed multiple times, de-dup.
		SELECT	ComputerID,
			MAX(IPNetworkInt) AS IPNetworkInt,
			MAX(IPNetworkSize) AS IPNetworkSize,
			IPNetwork
		 FROM	(SELECT	*,
				(dbo.IPAddressFromString(IPAddress) & dbo.IPAddressFromString(IPSubnet))
				AS IPNetworkInt,
				dbo.IPNetworkSize(dbo.IPAddressFromString(IPSubnet))
				AS IPNetworkSize,
				dbo.IPAddressToString(
					dbo.IPAddressFromString(IPAddress)
					& dbo.IPAddressFromString(IPSubnet)
				)
				+ '/' + REPLACE(STR(dbo.IPNetworkSize(dbo.IPAddressFromString(IPSubnet)), 3), ' ', '')
				AS IPNetwork
		 	 FROM NetworkAdapterConfiguration
			 WHERE	IPAddress IS NOT NULL
			) AS wnac
		 WHERE	CASE
			WHEN	CHARINDEX('/', @IPAddress) > 0 -- searching for computers in a subnet?
			THEN	IPNetwork
			ELSE	IPAddress
			END LIKE @IPAddress
		   AND	IPNetwork IS NOT NULL
		 GROUP BY ComputerID, IPNetwork
		) AS wnc
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = wnc.ComputerID
	GROUP BY wnc.IPNetwork
	ORDER BY MAX(wnc.IPNetworkInt), MAX(wnc.IPNetworkSize)
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByNetworkAdapterManufacturer')
	DROP PROCEDURE ComputerByNetworkAdapterManufacturer
GO
CREATE PROCEDURE ComputerByNetworkAdapterManufacturer
	@RDomDN				nvarchar(101) = '%',
	@ROUDN				nvarchar(401) = '%',
	@ComputerCN			nvarchar(64) = '%',
	@NetworkAdapterManufacturer	nvarchar(401) = '%',
	@NetworkAdapterModel		nvarchar(401) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		na.HardwareName AS NetworkAdapterModel,
		na.MACAddress,
		na.Manufacturer AS NetworkAdapterManufacturer,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	NetworkAdapter AS na
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = na.ComputerID
	WHERE	dbo.LikeNullable(na.Manufacturer, @NetworkAdapterManufacturer) = 1
	  AND	dbo.LikeNullable(HardwareName, @NetworkAdapterModel) = 1
	  AND	MACAddress IS NOT NULL
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'NetworkAdapterCountByModel')
	DROP PROCEDURE NetworkAdapterCountByModel
GO
CREATE PROCEDURE NetworkAdapterCountByModel
	@RDomDN				nvarchar(101) = '%',
	@ROUDN				nvarchar(401) = '%',
	@NetworkAdapterManufacturer	nvarchar(401) = '%',
	@NetworkAdapterModel		nvarchar(401) = '%'
AS
	SELECT	na.Manufacturer AS NetworkAdapterManufacturer,
		na.HardwareName AS NetworkAdapterModel,
		COUNT(*) as NetworkAdapterModelCount		
	FROM	NetworkAdapter AS na
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = na.ComputerID
	WHERE	dbo.LikeNullable(na.Manufacturer, @NetworkAdapterManufacturer) = 1
	  AND	dbo.LikeNullable(HardwareName, @NetworkAdapterModel) = 1
	  AND	MACAddress IS NOT NULL
	GROUP BY na.Manufacturer, na.HardwareName
	ORDER BY na.Manufacturer, na.HardwareName
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountHavingNetworkAdapterManufacturer')
	DROP PROCEDURE ComputerCountHavingNetworkAdapterManufacturer
GO
CREATE PROCEDURE ComputerCountHavingNetworkAdapterManufacturer
	@RDomDN				nvarchar(101) = '%',
	@ROUDN				nvarchar(401) = '%',
	@NetworkAdapterManufacturer	nvarchar(401) = '%',
	@NetworkAdapterModel		nvarchar(401) = '%'
AS
	SELECT	SUM(CASE WHEN na.ComputerID IS NULL THEN 0 ELSE 1 END
		) AS ComputerCountHavingNetworkAdapter,
		SUM(CASE WHEN na.ComputerID IS NULL THEN 1 ELSE 0 END
		) AS ComputerCountNotHavingNetworkAdapter
	FROM	(SELECT DISTINCT ComputerID
		 FROM	NetworkAdapter
		WHERE	dbo.LikeNullable(Manufacturer, @NetworkAdapterManufacturer) = 1
		  AND	dbo.LikeNullable(HardwareName, @NetworkAdapterModel) = 1
		) AS na
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = na.ComputerID
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerLackingNetworkAdapterManufacturer')
	DROP PROCEDURE ComputerLackingNetworkAdapterManufacturer
GO
CREATE PROCEDURE ComputerLackingNetworkAdapterManufacturer
	@RDomDN				nvarchar(101) = '%',
	@ROUDN				nvarchar(401) = '%',
	@ComputerCN			nvarchar(64) = '%'
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		na.HardwareName AS NetworkAdapterModel,
		na.MACAddress,
		na.Manufacturer AS NetworkAdapterManufacturer,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	NetworkAdapter AS na
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = na.ComputerID
	WHERE	dbo.LikeNullable(na.Manufacturer, NULL) = 1
	  AND	dbo.LikeNullable(HardwareName, NULL) = 1
GO
/*
 * $Id: OperatingSystem.sql 84480 2007-07-24 06:34:27Z pca $
 *
 * Stored procedures to produce reports on OperatingSystem info.
 */

/*
 * Calculate the set of operating systems recursively in the category.
 * The #OperatingSystems temporary table must exist, and can be pre-
 * primed with any number of categories, OR you may pass a category.
 *
 * You can also pass a negative OSID or category to get "all-but" behaviour.
 */
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'OperatingsystemsInCategory')
	DROP PROCEDURE OperatingSystemsInCategory
GO
CREATE PROCEDURE OperatingSystemsInCategory
	@OSID int = NULL
AS
	SET NOCOUNT ON
	IF @OSID < 0
	BEGIN
		CREATE TABLE #ExcludeOS(OperatingSystemID int)
		INSERT #ExcludeOS(OperatingSystemID)
			VALUES (-@OSID)	 -- Prime the result set if necessary
		WHILE @@ROWCOUNT <> 0
		BEGIN
			INSERT #ExcludeOS
				SELECT	OperatingSystemID
				FROM	OperatingSystem AS o
				WHERE  EXISTS(
					SELECT *
					FROM	#ExcludeOS AS s
					WHERE	s.OperatingSystemID = o.Category
					  OR	(s.OperatingSystemID = 0 AND o.Category IS NULL)
				) AND NOT EXISTS (
					SELECT * FROM #ExcludeOS AS s
					WHERE s.OperatingSystemID = o.OperatingSystemID
				)
		END
		INSERT #OperatingSystems
			SELECT OperatingSystemID
			FROM	OperatingSystem AS os
			WHERE NOT EXISTS(
					SELECT * FROM #ExcludeOS AS ex
					WHERE os.OperatingSystemID = ex.OperatingSystemID
				)
			DROP TABLE #ExcludeOS
	END ELSE BEGIN
		IF @OSID IS NOT NULL
			INSERT #OperatingSystems(OperatingSystemID)
				VALUES (@OSID)	 -- Prime the result set if necessary
		WHILE @@ROWCOUNT <> 0
		BEGIN
			INSERT #OperatingSystems
				SELECT	OperatingSystemID
				FROM	OperatingSystem AS o
				WHERE  EXISTS(
					SELECT *
					FROM	#OperatingSystems AS s
					WHERE	s.OperatingSystemID = o.Category
					  OR	(s.OperatingSystemID = 0 AND o.Category IS NULL)
				) AND NOT EXISTS (
					SELECT * FROM #OperatingSystems AS s
					WHERE s.OperatingSystemID = o.OperatingSystemID
				)
		END
	END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByOperatingSystemServicePack')
	DROP PROCEDURE ComputerByOperatingSystemServicePack
GO
CREATE PROCEDURE ComputerByOperatingSystemServicePack
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%',
	@OSID			int = 0,
	@OSServicePack		nvarchar(500) = '%'
AS
	CREATE TABLE #OperatingSystems(OperatingSystemID int)
	EXEC OperatingSystemsInCategory @OSID
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		os.OperatingSystemName AS OperatingSystem,
		cd.OperatingSystemID AS OSID,
		CASE
		WHEN c_os.CSDVersion IS NULL AND c_os.CSDUnselected IS NOT NULL THEN 'GoldSP'
		ELSE c_os.CSDVersion
		END AS OSServicePack,
		cd.OURDN AS OU,
		cd.DomainDN AS Domain
	FROM	ComputerDirectory AS cd
		LEFT OUTER JOIN
		OperatingSystem AS os
		ON cd.OperatingSystemID = os.OperatingSystemID
		LEFT OUTER JOIN
		(SELECT	*,
			1-dbo.LikeNullable(CSDVersion, NULL) AS CSDUnselected
		 FROM ComputerOperatingSystem
		) AS c_os
		ON cd.ComputerID = c_os.ComputerID
	WHERE	cd.DomainDNReverse LIKE @RDomDN
	  AND	dbo.LikeNullable(cd.OURDNReverse, @ROUDN) = 1
	  AND	dbo.LikeNullable(cd.ComputerCN, @ComputerCN) = 1
	  AND	(
		(@OSServicePack = 'GoldSP' AND c_os.CSDVersion IS NULL AND c_os.CSDUnselected = 0)
		OR
		(@OSServicePack IS NULL AND c_os.CSDUnselected IS NULL)
		OR
		(@OSServicePack IS NOT NULL AND dbo.LikeNullable(c_os.CSDVersion, @OSServicePack) = 1) 
		)
	  AND	(@OSID = 0
	     OR	(@OSID IS NULL AND cd.OperatingSystemID IS NULL)
	     OR EXISTS(
	     	SELECT * FROM #OperatingSystems AS os
		WHERE os.OperatingSystemID = cd.OperatingSystemID
		))
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByOperatingSystem')
	DROP PROCEDURE ComputerCountByOperatingSystem
GO
CREATE PROCEDURE ComputerCountByOperatingSystem
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@OSID			int = 0,
	@OSServicePack		nvarchar(500) = '%'
AS
	IF @OSServicePack = ''
		SET @OSServicePack = '%'
	CREATE TABLE #OperatingSystems(OperatingSystemID int)
	EXEC OperatingSystemsInCategory @OSID
	SELECT	CASE
		WHEN cd.OperatingSystemID IS NULL THEN NULL
		WHEN cd.Unselected = 1 and @OSID < 0 THEN SelectedOSName
		WHEN cd.Unselected = 1 THEN 'All but '+SelectedOSName
		ELSE cd.OperatingSystemName
		END AS OperatingSystem,
		CASE
		WHEN cd.OperatingSystemID IS NULL THEN NULL
		WHEN cd.Unselected = 1 THEN -@OSID
		ELSE cd.OperatingSystemID END AS OSID,
		CASE
		WHEN cd.Unselected = 1 THEN NULL
		ELSE COUNT(DISTINCT CSDVersion)
		END AS OSServicePackCount,
		COUNT(cd.ComputerID) AS ComputerCount
	FROM	(SELECT cd.*,
			os.OperatingSystemName,
			ISNULL(
				(SELECT	OperatingSystemName
				 FROM	OperatingSystem
				 WHERE	OperatingSystemID = -@OSID
				    OR	OperatingSystemID = @OSID
				),
				'unknown'
			) AS SelectedOSName,
			CASE
			WHEN (@OSID = 0	-- All, NULL, or in temp table:
			     OR	(@OSID IS NULL AND cd.OperatingSystemID IS NULL)
			     OR EXISTS(
			     	SELECT * FROM #OperatingSystems AS os
				WHERE os.OperatingSystemID = cd.OperatingSystemID
				))
				THEN 0 ELSE 1 END
			AS Unselected
		 FROM	ComputerDirectory AS cd
			LEFT OUTER JOIN
			OperatingSystem AS os
			ON cd.OperatingSystemID = os.OperatingSystemID
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		LEFT OUTER JOIN
		(SELECT * FROM ComputerOperatingSystem
		 WHERE	dbo.LikeNullable(CSDVersion, @OSServicePack) = 1
		) AS c_os
		ON cd.ComputerID = c_os.ComputerID
	WHERE	cd.OperatingSystemID IS NULL	-- Exclude the "All but" category
	   OR	cd.Unselected <> 1
	GROUP BY cd.Unselected,
		CASE
		WHEN cd.OperatingSystemID IS NULL THEN NULL
		WHEN cd.Unselected = 1 and @OSID < 0 THEN SelectedOSName
		WHEN cd.Unselected = 1 THEN 'All but '+SelectedOSName
		ELSE cd.OperatingSystemName
		END,
		CASE
		WHEN cd.OperatingSystemID IS NULL THEN NULL
		WHEN cd.Unselected = 1 THEN -@OSID
		ELSE cd.OperatingSystemID
		END
	ORDER BY cd.Unselected DESC,
		CASE
		WHEN cd.OperatingSystemID IS NULL THEN NULL
		WHEN cd.Unselected = 1 and @OSID < 0 THEN SelectedOSName
		WHEN cd.Unselected = 1 THEN 'All but '+SelectedOSName
		ELSE cd.OperatingSystemName
		END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByOperatingSystemServicePack')
	DROP PROCEDURE ComputerCountByOperatingSystemServicePack
GO
CREATE PROCEDURE ComputerCountByOperatingSystemServicePack  
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@OSID			int = 0,
	@OSServicePack		nvarchar(500) = '%'
AS
	IF @OSServicePack = ''
		SET @OSServicePack = '%'
	CREATE TABLE #OperatingSystems(OperatingSystemID int)
	EXEC OperatingSystemsInCategory @OSID
	SELECT
		CASE
		WHEN cd.OperatingSystemID IS NULL THEN NULL
		WHEN (cd.Unselected = 1 OR c_os.CSDUnselected = 1)
		 AND @OSID < 0
		THEN SelectedOSName
		WHEN cd.Unselected = 1 OR c_os.CSDUnselected = 1
		THEN 'All but '+SelectedOSName
		ELSE cd.OperatingSystemName
		END AS OperatingSystem,
		CASE
		WHEN cd.OperatingSystemID IS NULL THEN NULL
		WHEN cd.Unselected = 1 OR c_os.CSDUnselected = 1
		THEN -@OSID
		ELSE cd.OperatingSystemID
		END AS OSID,
		CASE
		WHEN cd.Unselected = 1 OR c_os.CSDUnselected = 1
		THEN ''	-- Really want '%' wild-card here - check UI.
		WHEN c_os.CSDVersion IS NULL AND c_os.CSDUnselected IS NOT NULL THEN 'GoldSP'
		ELSE c_os.CSDVersion
		END AS OSServicePack,
		COUNT(cd.ComputerID) AS ComputerCount
	FROM	(SELECT cd.*,
			os.OperatingSystemName,
			ISNULL(
				(SELECT	OperatingSystemName FROM OperatingSystem
				 WHERE	OperatingSystemID = -@OSID
				    OR	OperatingSystemID = @OSID
				),
				'unknown'
			) AS SelectedOSName,
			CASE
			WHEN (@OSID = 0	-- All, NULL, or in temp table:
			     OR	(@OSID IS NULL AND cd.OperatingSystemID IS NULL)
			     OR EXISTS(
			     	SELECT * FROM #OperatingSystems AS os
				WHERE os.OperatingSystemID = cd.OperatingSystemID
				))
				THEN 0 ELSE 1 END
			AS Unselected
		 FROM	ComputerDirectory AS cd
			LEFT OUTER JOIN
			OperatingSystem AS os
			ON cd.OperatingSystemID = os.OperatingSystemID
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		LEFT OUTER JOIN
		(SELECT	*,
			1-dbo.LikeNullable(CSDVersion, @OSServicePack) AS CSDUnselected
		 FROM ComputerOperatingSystem
		) AS c_os
		ON cd.ComputerID = c_os.ComputerID
	WHERE	cd.OperatingSystemID IS NULL	-- Exclude the "All but" category
	   OR	(cd.Unselected = 0 AND (c_os.CSDUnselected = 0 OR c_os.CSDUnselected IS NULL))
	GROUP BY
		CASE
		WHEN cd.OperatingSystemID IS NULL THEN NULL
		WHEN (cd.Unselected = 1 OR c_os.CSDUnselected = 1)
		 AND @OSID < 0
		THEN SelectedOSName
		WHEN cd.Unselected = 1 OR c_os.CSDUnselected = 1
		THEN 'All but '+SelectedOSName
		ELSE cd.OperatingSystemName
		END,
		CASE
		WHEN cd.OperatingSystemID IS NULL THEN NULL
		WHEN cd.Unselected = 1 OR c_os.CSDUnselected = 1
		THEN -@OSID
		ELSE cd.OperatingSystemID
		END,
		CASE WHEN cd.Unselected = 1 OR c_os.CSDUnselected = 1
		THEN ''
		WHEN c_os.CSDVersion IS NULL AND c_os.CSDUnselected IS NOT NULL THEN 'GoldSP'
		ELSE c_os.CSDVersion
		END
	ORDER BY CASE
		WHEN cd.OperatingSystemID IS NULL THEN NULL
		WHEN (cd.Unselected = 1 OR c_os.CSDUnselected = 1)
		 AND @OSID < 0
		THEN SelectedOSName
		WHEN cd.Unselected = 1 OR c_os.CSDUnselected = 1
		THEN 'All but '+SelectedOSName
		ELSE cd.OperatingSystemName
		END,
		CASE WHEN cd.Unselected = 1 OR c_os.CSDUnselected = 1
		THEN ''
		WHEN c_os.CSDVersion IS NULL AND c_os.CSDUnselected IS NOT NULL THEN 'GoldSP'
		ELSE c_os.CSDVersion
		END
GO
/*
 * $Id: Performance.sql 56557 2004-07-13 09:01:38Z ryang $
 *
 * Stored procedures to produce reports on Processor info.
 */

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByProcessor')
	DROP PROCEDURE ComputerByProcessor
GO
CREATE PROCEDURE ComputerByProcessor
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%',
	@ProcessorCountMin	int = NULL,
	@ProcessorCountMax	int = 0,
	@MaxClockSpeedMin	int = NULL,
	@MaxClockSpeedMax	int = 0
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		dbo.CIMProcessorType(
			MAX(cp.Name),
			MAX(cp.Description),
			MAX(cp.Manufacturer),
			MAX(cp.Version)
		) as ProcessorType,
		cs.NumberOfProcessors AS ProcessorCount,
		MAX(cp.MaxClockSpeed) AS MaxClockSpeed,
		MAX(cp.CurrentClockSpeed) as CurrentClockSpeed,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	ComputerProcessor AS cp
		FULL OUTER JOIN
		ComputerSystem AS cs
		ON cp.ComputerID = cs.ComputerID
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cp.ComputerID
	WHERE	dbo.RangeMatchInt(
			cs.NumberOfProcessors,
			@ProcessorCountMin,
			@ProcessorCountMax
		) = 1
	AND	dbo.RangeMatchInt(
			cp.MaxClockSpeed,
			@MaxClockSpeedMin,
			@MaxClockSpeedMax
		) = 1
	GROUP BY cd.ComputerID, cd.ComputerCN, cs.NumberOfProcessors, cd.OURDN, cd.DomainDN
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByProcessorSpeed')
	DROP PROCEDURE ComputerCountByProcessorSpeed
GO
CREATE PROCEDURE ComputerCountByProcessorSpeed
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@CategoryIncr		int = 200
AS
	SELECT	SpeedCategory-@CategoryIncr/2 AS MaxClockSpeedMin,
		SpeedCategory+(@CategoryIncr-@CategoryIncr/2)-1
		AS MaxClockSpeedMax,
		Count(*) AS ComputerCount
	FROM	(SELECT	MAX(SpeedCategory) AS SpeedCategory
		FROM	(SELECT	*,
				(MaxClockSpeed+@CategoryIncr/2)/@CategoryIncr*@CategoryIncr
				AS SpeedCategory
			 FROM	ComputerProcessor
			) AS cp
			RIGHT OUTER JOIN
			(SELECT * FROM ComputerDirectory
			 WHERE	DomainDNReverse LIKE @RDomDN
			  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
			) AS cd
			ON cd.ComputerID = cp.ComputerID
		GROUP BY cd.ComputerID
		) AS ps
	GROUP BY SpeedCategory
	ORDER BY SpeedCategory
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByProcessorSpeedOS')
	DROP PROCEDURE ComputerByProcessorSpeedOS
GO
CREATE PROCEDURE ComputerByProcessorSpeedOS
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@OSID			int = 0,
	@ComputerCN		nvarchar(64) = '%',
	@MaxClockSpeedMin	int = NULL,
	@MaxClockSpeedMax	int = 0
AS
	CREATE TABLE #OperatingSystems(OperatingSystemID int)
	EXEC OperatingSystemsInCategory @OSID
	SELECT	cd.ComputerID,
		MAX(cd.ComputerCN) AS ComputerCN,
		(SELECT OperatingSystemName FROM OperatingSystem AS osname
		 WHERE osname.OperatingSystemID = MAX(cd.OperatingSystemID)
		) AS OperatingSystem,
		MAX(cd.OperatingSystemID) AS OSID,
		MAX(cp.MaxClockSpeed) AS MaxClockSpeed,
		MAX(cd.OURDN) AS OrganizationalUnit,
		MAX(DomainDN) AS DomainDN
	FROM	(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		LEFT OUTER JOIN
		ComputerProcessor AS cp
		ON cd.ComputerID = cp.ComputerID
	WHERE	(@OSID = 0 -- All, NULL or in temp table:
		OR (@OSID IS NULL AND cd.OperatingSystemID IS NULL)
		OR EXISTS(SELECT * FROM #OperatingSystems AS os
			  WHERE cd.OperatingSystemID = os.OperatingSystemID))
	  AND	dbo.RangeMatchInt(
	  		cp.MaxClockSpeed,
			@MaxClockSpeedMin,
			@MaxClockSpeedMax
		) = 1
	GROUP BY cd.ComputerID
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByProcessorSpeedOS')
	DROP PROCEDURE ComputerCountByProcessorSpeedOS
GO
CREATE PROCEDURE ComputerCountByProcessorSpeedOS
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@OSID			int = 0,
	@CategoryIncr		int = 200
AS
	CREATE TABLE #OperatingSystems(OperatingSystemID int)
	EXEC OperatingSystemsInCategory @OSID
	SELECT	ps.OperatingSystemName AS OperatingSystem,
		ps.OSID,
		ps.SpeedCategory AS MaxClockSpeedMin,
		ps.SpeedCategory+@CategoryIncr-1 AS MaxClockSpeedMax,
		Count(*) AS ComputerCount
	FROM	(SELECT	(MAX(MaxClockSpeed)+1)/@CategoryIncr*@CategoryIncr AS SpeedCategory,
			CASE
			WHEN MAX(cd.OperatingSystemID) IS NULL
				THEN NULL	-- Unknown
			WHEN MAX(os.OperatingSystemID) IS NULL
				THEN ''		-- Not selected
			ELSE (SELECT o.OperatingSystemName
				FROM OperatingSystem AS o
				WHERE o.OperatingSystemID = MAX(os.OperatingSystemID))
			END AS OperatingSystemName,
			CASE
			WHEN MAX(cd.OperatingSystemID) IS NULL
				THEN NULL	-- Unknown
			WHEN MAX(os.OperatingSystemID) IS NULL
				THEN -@OSID	-- Not selected
			ELSE	MAX(cd.OperatingSystemID)
			END AS OSID
		FROM	ComputerProcessor AS cp
			RIGHT OUTER JOIN
			(SELECT * FROM ComputerDirectory
			 WHERE	DomainDNReverse LIKE @RDomDN
			  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
			) AS cd
			ON cd.ComputerID = cp.ComputerID
			LEFT OUTER JOIN
			#OperatingSystems AS os
			ON cd.OperatingSystemID = os.OperatingSystemID
		GROUP BY cd.ComputerID
		) AS ps
	WHERE	ps.OperatingSystemName <> ''	-- Exclude the "Other" category
	   OR	ps.OperatingSystemName IS NULL
	GROUP BY ps.OperatingSystemName, ps.OSID, ps.SpeedCategory
	ORDER BY ps.SpeedCategory, ps.OperatingSystemName
GO
/*
 * $Id: Storage.sql 84480 2007-07-24 06:34:27Z pca $
 *
 * Stored procedures to produce reports on Storage info.
 */

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByPartitionCount')
	DROP PROCEDURE ComputerByPartitionCount
GO
CREATE PROCEDURE ComputerByPartitionCount
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@PartitionCountMin	int = NULL,
	@PartitionCountMax	int = 0
AS
	SELECT	pc.ComputerID,
		pc.ComputerCN,
		pc.PartitionCount
	FROM	(SELECT	cd.ComputerID,
			cd.ComputerCN,
			COUNT(CASE WHEN ld.ComputerID IS NULL THEN 0 ELSE 1 END)
			AS PartitionCount
		 FROM	(SELECT	*
			 FROM	LogicalDisk
			 WHERE	Description NOT LIKE '%Floppy%'
			   AND	Description NOT LIKE 'Removable%'
			   AND	Description <> 'Network Connection'
			   AND	Description <> 'CD-ROM Disc'
			   AND	Description <> 'RAM Disk'
			) AS ld
			RIGHT OUTER JOIN
			(SELECT * FROM ComputerDirectory
			 WHERE	DomainDNReverse LIKE @RDomDN
			  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
			) AS cd
			ON cd.ComputerID = ld.ComputerID
		GROUP BY cd.ComputerID,
			cd.ComputerCN
		) AS pc
	WHERE	dbo.RangeMatchInt(
			PartitionCount,
			@PartitionCountMin,
			@PartitionCountMax
		) = 1
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'DiskPartitionBySize')
	DROP PROCEDURE DiskPartitionBySize
GO
CREATE PROCEDURE DiskPartitionBySize
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%',
	@PartitionSizeBytesMin	bigint = NULL,
	@PartitionSizeBytesMax	bigint = 0,
	@PartitionFreeBytesMin	bigint = NULL,
	@PartitionFreeBytesMax	bigint = 0
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		ld.HardwareName AS Drive,
		ld.FreeSpace AS PartitionFreeBytes,
		ld.Size AS PartitionSizeBytes,
	--	ld.Description,		-- 'Local Fixed Disk'
		ld.FileSystem,		-- e.g. FAT, NTFS
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	(SELECT *
		 FROM	LogicalDisk
		 WHERE	Description NOT LIKE '%Floppy%'
		   AND	Description NOT LIKE 'Removable%'
		   AND	Description <> 'Network Connection'
		   AND	Description <> 'CD-ROM Disc'
		   AND	Description <> 'RAM Disk'
		   -- keep Local Fixed Disk, etc
		   AND	dbo.RangeMatchBigint(
				Size,
				@PartitionSizeBytesMin,
				@PartitionSizeBytesMax
			) = 1
		   AND	dbo.RangeMatchBigint(
				FreeSpace,
				@PartitionFreeBytesMin,
				@PartitionFreeBytesMax
			) = 1
		) AS ld
		INNER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = ld.ComputerID
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'DiskDriveBySizeRange')
	DROP PROCEDURE DiskDriveBySizeRange
GO
CREATE PROCEDURE DiskDriveBySizeRange
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%',
	@DiskModel		nvarchar(200) = '%',
	@DiskSizeBytesMin	bigint = NULL,
	@DiskSizeBytesMax	bigint = 0
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		dd.Size AS DiskSizeBytes,
	--	dd.Description,
	--	dd.Manufacturer,
		dd.Model AS DiskModel,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	DiskDrive AS dd
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		   AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		   AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = dd.ComputerID
	WHERE	dbo.LikeNullable(dd.Model, @DiskModel) = 1
	  AND	dbo.RangeMatchBigint(
			dd.Size,
			@DiskSizeBytesMin,
			@DiskSizeBytesMax
		) = 1
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'DiskDriveCountByModel')
	DROP PROCEDURE DiskDriveCountByModel
GO
CREATE PROCEDURE DiskDriveCountByModel
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%',
	@DiskModel		nvarchar(200) = '%'
AS
	SELECT	dd.Model AS DiskModel,
		MAX(dd.InterfaceType) as InterfaceType,
		CASE WHEN SUM(CASE WHEN dd.Size IS NULL THEN 0 ELSE 1 END) = 0
			THEN NULL		-- No sizes known
			WHEN MAX(dd.Size) <> MIN(dd.Size) THEN 0 -- Various sizes
			ELSE MAX(dd.Size)	-- One size
		END AS DiskSizeBytes,
		SUM(CASE WHEN ISNULL(dd.Model, dd.Size) IS NULL THEN 0 ELSE 1 END) AS DriveCount,
		SUM(CASE WHEN dd.Size IS NULL THEN 0 ELSE dd.Size END) AS AggregateSizeBytes
	FROM	DiskDrive AS dd
		INNER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		   AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		   AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = dd.ComputerID
	WHERE	dbo.LikeNullable(dd.Model, @DiskModel) = 1
	GROUP BY
		dd.Model,
		CASE WHEN dd.Model IS NULL THEN 0 ELSE dd.Size END
	ORDER BY dd.Model
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'DiskDriveCountBySizeCategory')
	DROP PROCEDURE DiskDriveCountBySizeCategory
GO
CREATE PROCEDURE DiskDriveCountBySizeCategory
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@CategoryIncr		bigint = 2147483647	-- 2 GiB
AS
	SELECT	COUNT(*) AS DiskDriveCount,
		dd.SizeCategory-@CategoryIncr+1 AS DiskSizeBytesMin,
		dd.SizeCategory AS DiskSizeBytesMax
	FROM	(SELECT	*,
			CAST((Size+@CategoryIncr-1)/@CategoryIncr AS int)*@CategoryIncr
			AS SizeCategory
		 FROM	DiskDrive
		) AS dd
		INNER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
		ON cd.ComputerID = dd.ComputerID
	GROUP BY dd.SizeCategory
	ORDER BY dd.SizeCategory
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'DiskDriveByComputerDiskCount')
	DROP PROCEDURE DiskDriveByComputerDiskCount
GO
CREATE PROCEDURE DiskDriveByComputerDiskCount
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@DiskDriveCountMin	int = 0
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		dd.Size AS DiskSizeBytes,
		dd.Model,
		dd.InterfaceType,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	DiskDrive as dd,
		(SELECT	ComputerID,
			COUNT(*) AS DriveCount,
			SUM(Size) AS TotalSpace
		FROM 	DiskDrive
		GROUP BY ComputerID HAVING COUNT(*) >= @DiskDriveCountMin
		) AS multi_drive_computers,
		(SELECT * FROM ComputerDirectory
		WHERE	DomainDNReverse LIKE @RDomDN
		AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd
	WHERE	cd.ComputerID = dd.ComputerID
	  AND	multi_drive_computers.ComputerID = dd.ComputerID
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerBySystemPartitionFree')
	DROP PROCEDURE ComputerBySystemPartitionFree
GO
CREATE PROCEDURE ComputerBySystemPartitionFree
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%',
	@FreeSpaceBytesMax	bigint = NULL,
	@FreeSpacePercentMax	int = NULL
AS
	SELECT	cd.ComputerID,
		cd.ComputerCN,
		ISNULL(WindowsDirectory, ISNULL(SystemDirectory, cs.SystemDevice))
		AS System,
		ld.FileSystem,
		ld.FreeSpace AS SystemPartitionFreeBytes,
		ld.Size AS SystemPartitionSizeBytes,
		(ld.FreeSpace*200/ld.Size+1)/2 AS SystemPartitionFreePercent,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	LogicalDisk AS ld
		INNER JOIN
		ComputerOperatingSystem AS cs
		ON 
		ld.Size > 0		-- to prevent divide by zero
		AND
		cs.ComputerID = ld.ComputerID
		AND ISNULL(	cs.SystemDevice,
			ISNULL(	LEFT(SystemDirectory, 2),
				LEFT(WindowsDirectory, 2)
				)
			) = ld.HardwareName
		RIGHT OUTER JOIN
		(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		   AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		   AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
		) AS cd
		ON cd.ComputerID = cs.ComputerID
	WHERE	(@FreeSpacePercentMax IS NULL OR (ld.FreeSpace*200/ld.Size+1)/2 <= @FreeSpacePercentMax)
	  AND	(@FreeSpaceBytesMax IS NULL OR ld.FreeSpace <= @FreeSpaceBytesMax)
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerByCDRom')
	DROP PROCEDURE ComputerByCDRom
GO
CREATE PROCEDURE ComputerByCDRom
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@ComputerCN		nvarchar(64) = '%',
	@CDROMType		nvarchar(200) = '_%',
	@Writable		bit = NULL,
	@DVDSupport		bit = NULL
AS
	SELECT	*
	FROM	(SELECT	cd.ComputerID,
			cd.ComputerCN,
			cdrom.HardwareName AS CDROMType,
			CASE
			WHEN  cdrom.ComputerID IS NULL
			THEN NULL
			WHEN cdrom.Writable <> 0
			  OR HardwareName LIKE '%[-+ ]RW%'
			  OR HardwareName LIKE '%Writer%'
			THEN 1
			ELSE 0
			END
			AS Writable,
			CASE WHEN cdrom.ComputerID IS NULL
			THEN NULL
			WHEN cdrom.HardwareName LIKE '%DVD%'
			THEN 1
			ELSE 0 END
			AS DVDSupport
		FROM	CDROMDrive as cdrom
			RIGHT OUTER JOIN
			(SELECT * FROM ComputerDirectory
			 WHERE	DomainDNReverse LIKE @RDomDN
			  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
			  AND	dbo.LikeNullable(ComputerCN, @ComputerCN) = 1
			) AS cd
			ON cd.ComputerID = cdrom.ComputerID
		) as cd
	WHERE	dbo.LikeNullable(CDROMType, @CDROMType) = 1
	  AND	(@Writable IS NULL OR Writable = @Writable)
	  AND	(@DVDSupport IS NULL OR DVDSupport = @DVDSupport)
	ORDER BY ComputerCN
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByCDRom')
	DROP PROCEDURE ComputerCountByCDRom
GO
CREATE PROCEDURE ComputerCountByCDRom
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@CDROMType		nvarchar(200) = '%'
AS
	SELECT	-- cdrom.HardwareName AS CDROMType,
		Writable,
		DVDSupport,
		COUNT(DISTINCT ComputerID) AS ComputerCount
	FROM	(SELECT	cd.ComputerID,
			cdrom.HardwareName AS CDROMType,
			CASE
			WHEN  cdrom.ComputerID IS NULL
			THEN NULL
			WHEN cdrom.Writable <> 0
			  OR HardwareName LIKE '%[-+ ]RW%'
			  OR HardwareName LIKE '%Writer%'
			THEN 1
			ELSE 0
			END
			AS Writable,
			CASE WHEN cdrom.ComputerID IS NULL
			THEN NULL
			WHEN cdrom.HardwareName LIKE '%DVD%'
			THEN 1
			ELSE 0 END
			AS DVDSupport
		FROM	CDROMDrive as cdrom
			RIGHT OUTER JOIN
			(SELECT * FROM ComputerDirectory
			 WHERE	DomainDNReverse LIKE @RDomDN
			  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
			) AS cd
			ON cd.ComputerID = cdrom.ComputerID
		) as CD
	WHERE	CDROMType LIKE @CDROMType
	GROUP BY Writable, DVDSupport
	ORDER BY Writable, DVDSupport
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerCountByCDRomType')
	DROP PROCEDURE ComputerCountByCDRomType
GO
CREATE PROCEDURE ComputerCountByCDRomType
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@CDROMType		nvarchar(200) = '%'
AS
	SELECT	CDROMType,
		Writable,
		DVDSupport,
		COUNT(DISTINCT ComputerID) AS ComputerCount
	FROM	(SELECT	cd.ComputerID,
			cdrom.HardwareName AS CDROMType,
			CASE
			WHEN  cdrom.ComputerID IS NULL
			THEN NULL
			WHEN cdrom.Writable <> 0
			  OR HardwareName LIKE '%[-+ ]RW%'
			  OR HardwareName LIKE '%Writer%'
			THEN 1
			ELSE 0
			END
			AS Writable,
			CASE WHEN cdrom.ComputerID IS NULL
			THEN NULL
			WHEN cdrom.HardwareName LIKE '%DVD%'
			THEN 1
			ELSE 0 END
			AS DVDSupport
		FROM	CDROMDrive as cdrom
			RIGHT OUTER JOIN
			(SELECT * FROM ComputerDirectory
			 WHERE	DomainDNReverse LIKE @RDomDN
			  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
			) AS cd
			ON cd.ComputerID = cdrom.ComputerID
		) as CD
	WHERE	dbo.LikeNullable(CDROMType, @CDROMType) = 1
	GROUP BY CDROMType, Writable, DVDSupport
	ORDER BY CDROMType, Writable, DVDSupport
GO
/*
 * $Id: Discovery.sql 84480 2007-07-24 06:34:27Z pca $
 *
 * Stored procedures to produce reports on Discovery info.
 */

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'NetworkDeviceCountByDeviceRole')
	DROP PROCEDURE NetworkDeviceCountByDeviceRole
GO
CREATE PROCEDURE NetworkDeviceCountByDeviceRole
	@DeviceType	NVARCHAR(50) = '%'
AS
SELECT 
	[DeviceRole],
	[DeviceType], 
	[DeviceCount] = SUM([DeviceCount])
  FROM
	(
		SELECT	nd.DeviceRole,
			[DeviceType] = dbo.NetworkDeviceType(nd.DeviceRole),
			[DeviceCount] = COUNT(*)
		  FROM	NetworkDevice AS nd		
		 GROUP BY nd.DeviceRole
		UNION
		SELECT * FROM NetworkDeviceTypeBaseCounts
	) AS Tab
 WHERE	Tab.[DeviceType] LIKE @DeviceType
 GROUP BY Tab.[DeviceRole], Tab.[DeviceType]
 ORDER BY Tab.[DeviceRole]
GO


IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'NetworkDeviceByDeviceRole')
	DROP PROCEDURE NetworkDeviceByDeviceRole
GO
CREATE PROCEDURE NetworkDeviceByDeviceRole
	@DeviceType	NVARCHAR(50) = '%'
AS
-- If @DeviceRole is passed in as NULL, all device types are returned
SELECT	DeviceID,
	ComputerID,
	DeviceName,
	DNSFullName,
	NTDomainName,
	IPAddress,
	DeviceRole = dbo.NetworkDeviceType(nd.DeviceRole),
	OperatingSystem,
	Inventory = CASE WHEN ComputerID IS NOT NULL THEN 'Details' ELSE NULL END
  FROM	NetworkDevice AS nd
 WHERE	(@DeviceType IS NOT NULL AND dbo.NetworkDeviceType(nd.DeviceRole) LIKE @DeviceType)
    OR	(@DeviceType IS NULL AND nd.DeviceRole IS NULL)
GO



IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'NetworkDeviceDetails')
	DROP PROCEDURE NetworkDeviceDetails
GO
CREATE PROCEDURE NetworkDeviceDetails
	@DeviceID	INT
AS
SELECT *
FROM
(
	SELECT
	PropertyID = 0,	
	Property = 'DeviceName',
	Value =	(SELECT DeviceName
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
	UNION
	SELECT	
	PropertyID = 1,
	Property = 'DNSFullName',
	Value =	(SELECT DNSFullName
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
	UNION
	SELECT
	PropertyID = 2,	
	Property = 'NTDomainName',
	Value =	(SELECT NTDomainName
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
	UNION
	SELECT
	PropertyID = 3,	
	Property = 'IPAddress',
	Value =	(SELECT IPAddress
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
	UNION
	SELECT	
	PropertyID = 4,
	Property = 'IPSubnet',
	Value =	(SELECT IPSubnet
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
	UNION
	SELECT	
	PropertyID = 5,
	Property = 'PhysicalAddress',
	Value =	(SELECT PhysicalAddress
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
	UNION
	SELECT
	PropertyID = 6,	
	Property = 'DeviceRole',
	Value =	(SELECT DeviceRole = dbo.NetworkDeviceType(DeviceRole)
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
	UNION
	SELECT
	PropertyID = 7,	
	Property = 'OperatingSystem',
	Value =	(SELECT OperatingSystem
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
	UNION 
	SELECT
	PropertyID = 8,	
	Property = 'IsManaged',
	Value =	(SELECT CASE WHEN IsManaged IS NULL OR IsManaged = 0 THEN 'No' ELSE 'Yes' END
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
	UNION
	SELECT
	PropertyID = 9,	
	Property = 'Description',
	Value =	(SELECT [Description]
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
	UNION
	SELECT
	PropertyID = 10,	
	Property = 'FirstDiscovered',
	Value =	CONVERT(NVARCHAR, 
		(SELECT FirstDiscovered
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		),126)
	UNION
	SELECT
	PropertyID = 11,
	Property = 'LastUpdate',
	Value =	CONVERT(NVARCHAR, 
		(SELECT LastUpdate
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		),126)
	UNION
	SELECT
	PropertyID = 12,	
	Property = 'LastDataSourceName',
	Value =	(SELECT LastDataSourceName
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
	UNION
	SELECT
	PropertyID = 13,	
	Property = 'LastDataSourceType',
	Value =	(SELECT LastDataSourceType
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
	UNION
	SELECT
	PropertyID = 14,	
	Property = 'ScannedOperatingSystem',
	Value =	(SELECT ScannedOperatingSystem
		   FROM	NetworkDevice
		  WHERE	DeviceID = @DeviceID
		)
) AS Tab
ORDER BY Tab.PropertyID
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'NetworkDeviceCountByOperatingSystem')
	DROP PROCEDURE NetworkDeviceCountByOperatingSystem
GO
CREATE PROCEDURE NetworkDeviceCountByOperatingSystem
	@OSID		INT = 0
AS
	CREATE TABLE #OperatingSystems(OperatingSystemID int)
	EXEC OperatingSystemsInCategory @OSID

	SELECT 
		Tab.OSID,
		Tab.OperatingSystem,
		COUNT(*) AS [DeviceCount]
	FROM
	(
		SELECT	nd.DeviceID, 
			nd.ComputerID,
			nd.DeviceName,
			os.OperatingSystemName AS OperatingSystem,
			nd.OperatingSystemID AS OSID,
			nd.DNSFullName,
			nd.NTDomainName
	
		FROM	NetworkDevice AS nd
			LEFT OUTER JOIN
			OperatingSystem AS os
			ON nd.OperatingSystemID = os.OperatingSystemID
	
		WHERE	(
			@OSID = 0
	           	OR	(@OSID IS NULL AND nd.OperatingSystemID IS NULL)
			OR	EXISTS(
		     		SELECT * FROM #OperatingSystems AS os
				WHERE os.OperatingSystemID = nd.OperatingSystemID
				)
			)
	) AS Tab
	GROUP BY Tab.OSID, Tab.OperatingSystem
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'NetworkDeviceByOperatingSystem')
	DROP PROCEDURE NetworkDeviceByOperatingSystem
GO
CREATE PROCEDURE NetworkDeviceByOperatingSystem
	@DeviceName		NVARCHAR(100) = '%',
	@OSID			INT = 0
AS
	CREATE TABLE #OperatingSystems(OperatingSystemID int)
	EXEC OperatingSystemsInCategory @OSID

	SELECT	nd.DeviceID,
		nd.ComputerID,
		nd.DeviceName,
		nd.DNSFullName,
		nd.NTDomainName,
		nd.IPAddress,
		nd.OperatingSystemID AS OSID,
		os.OperatingSystemName AS OperatingSystem,
		DeviceRole = dbo.NetworkDeviceType(nd.DeviceRole),
		Inventory = CASE WHEN ComputerID IS NOT NULL THEN 'Details' ELSE NULL END

	FROM	NetworkDevice AS nd
		LEFT OUTER JOIN
		OperatingSystem AS os
		ON nd.OperatingSystemID = os.OperatingSystemID

	WHERE	dbo.LikeNullable(nd.DeviceName, @DeviceName) = 1
	  AND	(
		@OSID = 0
           	OR	(@OSID IS NULL AND nd.OperatingSystemID IS NULL)
		OR	EXISTS(
	     		SELECT * FROM #OperatingSystems AS os
			WHERE os.OperatingSystemID = nd.OperatingSystemID
			)
		)

GO

/*
 * $Id: InstalledSoftware.sql 98788 2010-12-01 03:40:12Z pca $
 *
 * Stored procedures to produce reports on installed software
 */

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'ComputerBySoftware')
	DROP PROCEDURE ComputerBySoftware
GO
CREATE PROCEDURE ComputerBySoftware
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@SoftwareName		nvarchar(500) = '%',
	@Version	   	nvarchar(64) = '%'
AS
	SELECT	LTRIM(RTRIM(sv.SoftwareName)) AS SoftwareName,
		LTRIM(RTRIM(sv.Version)) AS Version,
		cd.ComputerID,
		cd.ComputerCN,
		cd.OURDN AS OrganizationalUnit,
		cd.DomainDN AS DomainDN
	FROM	(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd,
		SoftwareOccurrence AS so,
		SoftwareVersion AS sv
	WHERE	cd.ComputerID = so.ComputerID
	  AND	so.SoftwareID = sv.SoftwareID
	  AND	dbo.LikeNullable(LTRIM(RTRIM(sv.SoftwareName)), @SoftwareName) = 1
	  AND	dbo.LikeNullable(LTRIM(RTRIM(sv.Version)), @Version) = 1
	ORDER BY sv.SoftwareName, sv.Version, cd.ComputerCN
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'SoftwareVersionCountByComputer')
	DROP PROCEDURE SoftwareVersionCountByComputer
GO
CREATE PROCEDURE SoftwareVersionCountByComputer
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@SoftwareName		nvarchar(500) = '%',
	@Version	   	nvarchar(64) = '%',
	@ComputerCountMin	int = NULL,
	@ComputerCountMax	int = 0,
	@UserCountMin		int = NULL,
	@UserCountMax		int = 0
AS
	SELECT	LTRIM(RTRIM(sv.SoftwareName)) AS SoftwareName,
		LTRIM(RTRIM(sv.Version)) AS Version,
		COUNT(DISTINCT so.ComputerID) as ComputerCount,
		SUM(CASE WHEN so.UserID <> 1 THEN 1 ELSE 0 END) as UserInstallCount,
		COUNT(DISTINCT CASE WHEN so.UserID <> 1 THEN so.UserID ELSE NULL END) as UserCount
	FROM	(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd,
		SoftwareOccurrence AS so,
		SoftwareVersion AS sv
	WHERE	dbo.LikeNullable(LTRIM(RTRIM(sv.SoftwareName)), @SoftwareName) = 1
	  AND	dbo.LikeNullable(LTRIM(RTRIM(sv.Version)), @Version) = 1
	  AND	cd.ComputerID = so.ComputerID
	  AND	so.SoftwareID = sv.SoftwareID
	GROUP BY sv.SoftwareName, sv.Version
	HAVING	dbo.RangeMatchInt(
			COUNT(DISTINCT so.ComputerID),
			@ComputerCountMin,
			@ComputerCountMax
		) = 1
	  AND	dbo.RangeMatchInt(
	  		COUNT(DISTINCT CASE WHEN so.UserID <> 1 THEN so.UserID ELSE NULL END),
			@UserCountMin,
			@UserCountMax
		) = 1
	ORDER BY sv.SoftwareName, sv.Version
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'SoftwareCountByComputer')
	DROP PROCEDURE SoftwareCountByComputer
GO
CREATE PROCEDURE SoftwareCountByComputer
	@RDomDN			nvarchar(101) = '%',
	@ROUDN			nvarchar(401) = '%',
	@SoftwareName		nvarchar(500) = '%',
	@ComputerCountMin	int = NULL,
	@ComputerCountMax	int = 0,
	@UserCountMin		int = NULL,
	@UserCountMax		int = 0
AS
	SELECT	LTRIM(RTRIM(sv.SoftwareName)) AS SoftwareName,
		COUNT(DISTINCT sv.Version) AS VersionCount,
		COUNT(so.ComputerID) as ComputerInstallations,
		COUNT(DISTINCT so.ComputerID) as ComputerCount,
		SUM(CASE WHEN so.UserID <> 1 THEN 1 ELSE 0 END) as UserInstallCount,
		COUNT(DISTINCT CASE WHEN so.UserID <> 1 THEN so.UserID ELSE NULL END) as UserCount
	FROM	(SELECT * FROM ComputerDirectory
		 WHERE	DomainDNReverse LIKE @RDomDN
		  AND	dbo.LikeNullable(OURDNReverse, @ROUDN) = 1
		) AS cd,
		SoftwareOccurrence AS so,
		SoftwareVersion AS sv
	WHERE	dbo.LikeNullable(LTRIM(RTRIM(sv.SoftwareName)), @SoftwareName) = 1
	  AND	cd.ComputerID = so.ComputerID
	  AND	so.SoftwareID = sv.SoftwareID
	GROUP BY sv.SoftwareName
	HAVING	dbo.RangeMatchInt(
			COUNT(DISTINCT so.ComputerID),
			@ComputerCountMin,
			@ComputerCountMax
		) = 1
	  AND	dbo.RangeMatchInt(
	  		COUNT(DISTINCT CASE WHEN so.UserID <> 1 THEN so.UserID ELSE NULL END),
			@UserCountMin,
			@UserCountMax
		) = 1
	ORDER BY sv.SoftwareName
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'OracleUsersByApplication')
	DROP PROCEDURE OracleUsersByApplication
GO
CREATE PROCEDURE OracleUsersByApplication
	@ServiceProviderApplicationOracleID int = null
AS
	SELECT ServiceProviderApplicationOracleID,
	       UserID,
	       UserName,
	       Description,
	       EMail
	FROM ServiceProviderApplicationUserOracle
	WHERE ((@ServiceProviderApplicationOracleID IS NULL) or (ServiceProviderApplicationOracleID = @ServiceProviderApplicationOracleID))
	ORDER BY UserName
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'OracleApplicationsByProvider')
	DROP PROCEDURE OracleApplicationsByProvider
GO
CREATE PROCEDURE OracleApplicationsByProvider
AS
	SELECT ServiceProviderName.Name AS ProviderName,
	       apps.ApplicationID,
	       apps.Name AS AppName,
	       apps.Users,
	       apps.ServiceProviderApplicationOracleID
	FROM ServiceProviderApplicationOracle AS Apps
	INNER JOIN ServiceProvider ON apps.ServiceProviderID = ServiceProvider.ServiceProviderID
	INNER JOIN ServiceProviderName ON ServiceProvider.ServiceProviderNameID = ServiceProviderName.ServiceProviderNameID
	ORDER BY ProviderName, AppName
GO

/*
 * $Id: Rights.sql 85117 2007-10-01 01:12:59Z cdouglas $
 *
 * Stored procedures for Rights API.
 */

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'OrganizationGetChildrenByOUID')
	DROP PROCEDURE OrganizationGetChildrenByOUID
GO
CREATE PROCEDURE OrganizationGetChildrenByOUID
	@ParentId	int
AS
	SELECT	OrganizationID,
		RDN,
		o.GUID,
		DomainID,
		RDNReverse,
		IsUnknown,
		IsDomain,
		BlockInheritance
	FROM	Organization o,
		(SELECT	o.OrganizationID as OUID,
			CASE
			    WHEN RDN IS NULL THEN	-- Unknown OU in this domain
				'<NULL>,'+d.DN		-- or the universal domain
			    WHEN RDN = '' THEN
			    	d.DN			-- DomainDN for the domain
			    ELSE
			    	o.RDN+','+d.DN		-- Ordinary OU or container
			END AS OU
		FROM	Organization AS o,
			Domain AS d
		WHERE	o.DomainID = d.OrganizationID) as ou1,
		(SELECT	o.OrganizationID as OUID,
			CASE
			    WHEN RDN IS NULL THEN	-- Unknown OU in this domain
				'<NULL>,'+d.DN		-- or the universal domain
			    WHEN RDN = '' THEN
			    	d.DN			-- DomainDN for the domain
			    ELSE
			    	o.RDN+','+d.DN		-- Ordinary OU or container
			END AS OU
		FROM	Organization AS o,
			Domain AS d
		WHERE	o.DomainID = d.OrganizationID
		) as ou2
	WHERE	o.OrganizationID <> @ParentId
	  AND	o.OrganizationID = ou1.OUID
	  AND	RIGHT(ou1.OU, LEN(ou2.OU)) = ou2.OU
	  AND	ou2.OUID = @ParentId
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'UserGetBySAMAccountNameDomainFlatName')
	DROP PROCEDURE UserGetBySAMAccountNameDomainFlatName
GO
CREATE PROCEDURE UserGetBySAMAccountNameDomainFlatName
	@SAMAccountName		nvarchar(20),
	@FlatName		nvarchar(32)
AS
	SELECT	u.UserID,
		u.UserOUID,
		u.UserCN,
		u.GUID,
		u.SAMAccountName
	FROM	[User] u, Organization o, Domain d 
	WHERE SAMAccountName = @SAMAccountName 
		AND u.UserOUID = o.OrganizationID
		AND o.DomainID = d.OrganizationID
		AND d.FlatName = @FlatName
GO


IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'GroupGetAllGroupsWithMemberUserByUserID')
	DROP PROCEDURE GroupGetAllGroupsWithMemberUserByUserID
GO
CREATE PROCEDURE GroupGetAllGroupsWithMemberUserByUserID
	@UserID		int
AS
	SELECT	g.GroupID,
		GUID,
		GroupCN,
		GroupOUID
	FROM	[Group] g, Member m
	WHERE	g.GroupID = m.GroupID
		AND m.TargetID = @UserID
		AND m.TargetTypeID = 2
		AND m.MemberMode <> 0
	RETURN @@ROWCOUNT
GO

IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'MemberGetAllGroupsWithMemberGroupByGroupID')
	DROP PROCEDURE MemberGetAllGroupsWithMemberGroupByGroupID
GO
CREATE PROCEDURE MemberGetAllGroupsWithMemberGroupByGroupID
	@GroupID		int
AS
	SELECT	GroupID,
		TargetTypeID,
		TargetID,
		MemberMode
	FROM	Member
	WHERE	TargetID = @GroupID
		AND TargetTypeID = 3
		AND MemberMode <> 0
	RETURN @@ROWCOUNT
GO

/*

CFS Problem: 52843

This procedure takes a member TargetID and TargetTypeID.

It will return all groups that inherit the member.

For example, if a member is in Group 4 below, this procedure will return
Group 1, Group 3, Group 4.

Group 1 -+- Group 2
         |
         +- Group 3 -+
                     |
                     +- Group 4
*/
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'P'
		AND name = 'GroupGetAllInheritedGroupsWithMemberByTargetIDTargetTypeID')
	DROP PROCEDURE GroupGetAllInheritedGroupsWithMemberByTargetIDTargetTypeID
GO
CREATE PROCEDURE GroupGetAllInheritedGroupsWithMemberByTargetIDTargetTypeID
	@TargetID	INTEGER,
	@TargetTypeID	INTEGER
AS
	DECLARE @GroupsWithUser TABLE
	(
		[TreeDepth]	INTEGER,
		[GroupID] 	INTEGER,
		[GUID] 		BINARY (16),
		[GroupCN] 	NVARCHAR (64),
		[GroupOUID]	INTEGER,
		[TargetID]	INTEGER,
		[TargetType]	INTEGER
	)
	DECLARE @TreeDepth INTEGER
	SET @TreeDepth = 0

	-- Populate table variable with groups that the user is directly a member of.
	INSERT INTO @GroupsWithUser ([TreeDepth], [GroupID], [GUID], [GroupCN], [GroupOUID], [TargetID], [TargetType])
		SELECT	@TreeDepth,
			g.GroupID,
			g.GUID,
			g.GroupCN,
			g.GroupOUID,
			m.TargetID,
			m.TargetTypeID
		FROM	[Group] g INNER JOIN Member m ON g.GroupID = m.GroupID
		WHERE 	m.TargetID = @TargetID
			AND m.TargetTypeID = @TargetTypeID
			AND m.MemberMode <> 0

	-- Find all the groups that the groups are a member of, 
	-- recursing up through the tree structure to the root.
	-- Limit the maximum tree depth that can be visited to 1000.
	WHILE @TreeDepth < 1000
	BEGIN
		SET @TreeDepth = @TreeDepth + 1

		-- Populate the table variable with groups that the groups are a member of
		INSERT INTO @GroupsWithUser 
			([TreeDepth], [GroupID], [GUID], [GroupCN], [GroupOUID], [TargetID], [TargetType])
		SELECT	
			@TreeDepth, m.GroupID, g.GUID, g.GroupCN, g.GroupOUID, m.TargetID, m.TargetTypeID
		FROM	@GroupsWithUser gwu
			INNER JOIN Member m ON m.TargetID = gwu.GroupID AND m.MemberMode <> 0 AND m.TargetTypeID = 3 -- 3 == Group
			INNER JOIN [Group] g ON g.GroupID = m.GroupID
		WHERE	gwu.TreeDepth = @TreeDepth - 1
			AND NOT EXISTS
			(
				SELECT * FROM @GroupsWithUser gwu2 WHERE gwu2.GroupID = m.GroupID
			)

		-- If no rows were added, there are no more parent groups left
		IF @@ROWCOUNT = 0
			BREAK
	END

	SELECT GroupID, GUID, GroupCN, GroupOUID FROM @GroupsWithUser

GO
/* 
 * $Id: AgentStatus.sql 86553 2008-02-21 07:23:54Z tfergus $
 * $Locker$
 *
 * Stored procedures for reports of AMT information
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'AgentStatusSummaryList' AND xtype = 'P'
)
        DROP PROCEDURE AgentStatusSummaryList
GO

CREATE PROCEDURE AgentStatusSummaryList
	@oudn Varchar(800)='%', 
	@ouMatch Bit=1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@fromDate AS DATETIME=NULL,
	@tillDate AS DATETIME=NULL

AS

BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0
END

SELECT
	SUM(CASE WHEN t.SumResultCode <> 0 THEN 1 ELSE 0 END) AS FailureCount,
	SUM(CASE WHEN t.SumResultCode = 0 THEN 1 ELSE 0 END) AS SuccessCount
FROM (
	SELECT DISTINCT
		nd.DeviceID,
		SUM(ags.ResultCode) AS SumResultCode
	FROM NetworkDevice AS nd
		INNER JOIN Computer AS c ON nd.ComputerID = c.ComputerID
		INNER JOIN #Organization AS s ON c.ComputerOUID = s.OUID
		INNER JOIN AgentStatus AS ags
			ON ags.DeviceID = nd.DeviceID
			AND (@fromDate IS NULL OR @fromDate < ags.Reported)
			AND (@tillDate IS NULL OR DATEADD(millisecond, -1, DATEADD(day, 1, @tillDate)) > ags.Reported)
	GROUP BY nd.DeviceID
) AS t

GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'AgentStatusFailedList' AND xtype = 'P'
)
        DROP PROCEDURE AgentStatusFailedList
GO

CREATE PROCEDURE AgentStatusFailedList
	@oudn Varchar(800)='%', 
	@ouMatch Bit=1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@compCN Varchar(128)='%', --computer name (size=64*2 --to take into acct encoded chars)
	@fromDate AS DATETIME=NULL,
	@tillDate AS DATETIME=NULL

AS

BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0
END

SELECT DISTINCT
	nd.DeviceID,
	c.ComputerID,
	c.ComputerCN,
	dbo.OUName(s.OUID) AS [OUDN],
	MAX(ags.Reported) AS Reported
FROM	NetworkDevice AS nd
	INNER JOIN Computer AS c
		ON nd.ComputerID = c.ComputerID
		AND c.ComputerCN LIKE @compCN -- match on ComputerCN (contains % - sql wildcard)
	INNER JOIN #Organization AS s
		ON c.ComputerOUID = s.OUID
	INNER JOIN AgentStatus AS ags
		ON ags.DeviceID = nd.DeviceID
		AND (@fromDate IS NULL OR @fromDate < ags.Reported)
		AND (@tillDate IS NULL OR DATEADD(millisecond, -1, DATEADD(day, 1, @tillDate)) > ags.Reported)
		AND ags.ResultCode <> 0
GROUP BY nd.DeviceID, c.ComputerID, c.ComputerCN, dbo.OUName(s.OUID)
ORDER BY dbo.OUName(s.OUID), c.ComputerCN

GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'AgentStatusSuccessList' AND xtype = 'P'
)
        DROP PROCEDURE AgentStatusSuccessList
GO

CREATE PROCEDURE AgentStatusSuccessList
	@oudn Varchar(800)='%', 
	@ouMatch Bit=1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@compCN Varchar(128)='%', --computer name (size=64*2 --to take into acct encoded chars)
	@fromDate AS DATETIME=NULL,
	@tillDate AS DATETIME=NULL

AS

BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0
END

SELECT DISTINCT
	nd.DeviceID,
	c.ComputerID,
	c.ComputerCN,
	dbo.OUName(s.OUID) AS [OUDN],
	MAX(ags.Reported) AS Reported
FROM	NetworkDevice AS nd
	INNER JOIN Computer AS c
		ON nd.ComputerID = c.ComputerID
		AND c.ComputerCN LIKE @compCN -- match on ComputerCN (contains % - sql wildcard)
	INNER JOIN #Organization AS s
		ON c.ComputerOUID = s.OUID
	INNER JOIN AgentStatus AS ags
		ON ags.DeviceID = nd.DeviceID
		AND (@fromDate IS NULL OR @fromDate < ags.Reported)
		AND (@tillDate IS NULL OR DATEADD(millisecond, -1, DATEADD(day, 1, @tillDate)) > ags.Reported)
		AND NOT EXISTS (
			SELECT	*
			FROM	AgentStatus AS ags2
			WHERE	ags2.DeviceID = ags.DeviceID
			  AND	ags2.ResultCode <> 0
		)
GROUP BY nd.DeviceID, c.ComputerID, c.ComputerCN, dbo.OUName(s.OUID)
ORDER BY dbo.OUName(s.OUID), c.ComputerCN

GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'AgentStatusDetails' AND xtype = 'P'
)
        DROP PROCEDURE AgentStatusDetails
GO

CREATE PROCEDURE AgentStatusDetails
	@deviceID int, --Device ID
	@fromDate AS DATETIME=NULL,
	@tillDate AS DATETIME=NULL
AS
SELECT
	ags.*
FROM NetworkDevice AS nd
	INNER JOIN AgentStatus AS ags
		ON ags.DeviceID = nd.DeviceID
		AND (@fromDate IS NULL OR @fromDate < ags.Reported)
		AND (@tillDate IS NULL OR DATEADD(millisecond, -1, DATEADD(day, 1, @tillDate)) > ags.Reported)
WHERE	nd.DeviceID = @deviceID

GO
/* 
 * $Id: AMTEventLog.sql 86553 2008-02-21 07:23:54Z tfergus $
 * $Locker$
 *
 * Stored procedures for reports of AMT event logs
 *
 * Protected by US patent 6,006,034; patents pending.
 * Copyright 1990-2002 ManageSoft Corporation. All rights reserved.
 * Reproduction, adaptation, or translation without prior permission
 * is prohibited.
 *
 */

-- USE MANAGESOFT
GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'AMTInformationMDSummaryList' AND xtype = 'P'
)
        DROP PROCEDURE AMTInformationMDSummaryList
GO

CREATE PROCEDURE AMTInformationMDSummaryList
	@oudn Varchar(800)='%', 
	@ouMatch Bit=1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@compCN Varchar(128)='%' --computer name (size=64*2 --to take into acct encoded chars)

AS

BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0
END

SELECT DISTINCT
	nd.DeviceID,
	c.ComputerID,
	c.ComputerCN,
	dbo.OUName(s.OUID) AS [OUDN],
	MAX(ags.Reported) AS [AgentStatusReportDate],	
	MAX(ael.Reported) AS [AMTEventLogReportDate]

FROM	NetworkDevice AS nd
	INNER JOIN Computer AS c
		ON nd.ComputerID = c.ComputerID
		AND c.ComputerCN LIKE @compCN
	INNER JOIN #Organization AS s
		ON c.ComputerOUID = s.OUID
	LEFT OUTER JOIN AgentStatus AS ags
		ON ags.DeviceID = nd.DeviceID
	LEFT OUTER JOIN AMTEventLog AS ael
		ON ael.DeviceID = nd.DeviceID
WHERE
	(	ags.Reported IS NOT NULL
		OR ael.Reported IS NOT NULL
	)
	AND (
		c.ComputerID IS NOT NULL
		OR nd.DeviceName LIKE @compCN
	)
GROUP BY nd.DeviceID, c.ComputerID, c.ComputerCN, dbo.OUName(s.OUID)
ORDER BY dbo.OUName(s.OUID), c.ComputerCN

GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'AMTEventLogSummaryList' AND xtype = 'P'
)
        DROP PROCEDURE AMTEventLogSummaryList
GO

CREATE PROCEDURE AMTEventLogSummaryList
	@oudn Varchar(800)='%', 
	@ouMatch Bit=1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@fromDate AS DATETIME=NULL,
	@tillDate AS DATETIME=NULL

AS

BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0
END

SELECT
	SUM(CASE WHEN t.MaxSeverity > 4 THEN 1 ELSE 0 END) AS FailureCount,
	SUM(CASE WHEN t.MaxSeverity <= 4 THEN 1 ELSE 0 END) AS SuccessCount
FROM (
	SELECT DISTINCT
		nd.DeviceID,
		MAX(ael.PETEventSeverity) AS MaxSeverity
	FROM NetworkDevice AS nd
		INNER JOIN Computer AS c ON nd.ComputerID = c.ComputerID
		INNER JOIN #Organization AS s ON c.ComputerOUID = s.OUID
		INNER JOIN AMTEventLog AS ael
			ON ael.DeviceID = nd.DeviceID
			AND (@fromDate IS NULL OR @fromDate < ael.Reported)
			AND (@tillDate IS NULL OR DATEADD(millisecond, -1, DATEADD(day, 1, @tillDate)) > ael.Reported)
	GROUP BY nd.DeviceID
) AS t

GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'AMTEventLogFailedList' AND xtype = 'P'
)
        DROP PROCEDURE AMTEventLogFailedList
GO

CREATE PROCEDURE AMTEventLogFailedList
	@oudn Varchar(800)='%', 
	@ouMatch Bit=1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@compCN Varchar(128)='%', --computer name (size=64*2 --to take into acct encoded chars)
	@fromDate AS DATETIME=NULL,
	@tillDate AS DATETIME=NULL

AS

BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0
END

SELECT DISTINCT
	nd.DeviceID,
	c.ComputerID,
	c.ComputerCN,
	dbo.OUName(s.OUID) AS [OUDN],
	MAX(ael.Reported) AS Reported
FROM NetworkDevice AS nd
	INNER JOIN Computer AS c
		ON nd.ComputerID = c.ComputerID
		AND c.ComputerCN LIKE @compCN -- match on ComputerCN (contains % - sql wildcard)
	INNER JOIN #Organization AS s
		ON c.ComputerOUID = s.OUID
	INNER JOIN AMTEventLog AS ael
		ON ael.DeviceID = nd.DeviceID
		AND (@fromDate IS NULL OR @fromDate < ael.Reported)
		AND (@tillDate IS NULL OR DATEADD(millisecond, -1, DATEADD(day, 1, @tillDate)) > ael.Reported)
		AND ael.PETEventSeverity > 4
GROUP BY nd.DeviceID, c.ComputerID, c.ComputerCN, dbo.OUName(s.OUID)
ORDER BY dbo.OUName(s.OUID), c.ComputerCN

GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'AMTEventLogSuccessList' AND xtype = 'P'
)
        DROP PROCEDURE AMTEventLogSuccessList
GO

CREATE PROCEDURE AMTEventLogSuccessList
	@oudn Varchar(800)='%', 
	@ouMatch Bit=1, --Values:[0=do exact OU Match | 1=include child-OUs in match]
	@compCN Varchar(128)='%', --computer name (size=64*2 --to take into acct encoded chars)
	@fromDate AS DATETIME=NULL,
	@tillDate AS DATETIME=NULL

AS

BEGIN
	CREATE TABLE #Organization(OUID int PRIMARY KEY)
	EXEC OrganizationIdentifyDescendentsByOUDN @oudn, @ouMatch, 0
END

SELECT DISTINCT
	nd.DeviceID,
	c.ComputerID,
	c.ComputerCN,
	dbo.OUName(s.OUID) AS [OUDN],
	MAX(ael.Reported) AS Reported
FROM NetworkDevice AS nd
	INNER JOIN Computer AS c
		ON nd.ComputerID = c.ComputerID
		AND c.ComputerCN LIKE @compCN -- match on ComputerCN (contains % - sql wildcard)
	INNER JOIN #Organization AS s
		ON c.ComputerOUID = s.OUID
	INNER JOIN AMTEventLog AS ael
		ON ael.DeviceID = nd.DeviceID
		AND (@fromDate IS NULL OR @fromDate < ael.Reported)
		AND (@tillDate IS NULL OR DATEADD(millisecond, -1, DATEADD(day, 1, @tillDate)) > ael.Reported)
		AND NOT EXISTS (
			SELECT	*
			FROM	AMTEventLog AS ael2
			WHERE	ael2.DeviceID = ael.DeviceID
			  AND	ael2.PETEventSeverity > 4
		)
GROUP BY nd.DeviceID, c.ComputerID, c.ComputerCN, dbo.OUName(s.OUID)
ORDER BY dbo.OUName(s.OUID), c.ComputerCN

GO

IF EXISTS (
        SELECT * FROM dbo.sysobjects
        WHERE [name] = 'AMTEventLogDetails' AND xtype = 'P'
)
        DROP PROCEDURE AMTEventLogDetails
GO

CREATE PROCEDURE AMTEventLogDetails
	@deviceID int, --Device ID
	@fromDate AS DATETIME=NULL,
	@tillDate AS DATETIME=NULL
AS
SELECT
	ael.*
FROM NetworkDevice AS nd
	INNER JOIN AMTEventLog AS ael
		ON ael.DeviceID = nd.DeviceID
		AND (@fromDate IS NULL OR @fromDate < ael.Reported)
		AND (@tillDate IS NULL OR DATEADD(millisecond, -1, DATEADD(day, 1, @tillDate)) > ael.Reported)
WHERE	nd.DeviceID = @deviceID

GO
