
PRINT 'EXECUTE 021'

-- create table 
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[mclBook_RefUsage]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[mclBook_RefUsage]
GO

CREATE TABLE [dbo].[mclBook_RefUsage] (
	[RefUsageId] [int] IDENTITY (1, 1) NOT NULL ,
	[RefId] [int] NOT NULL ,
	[IdInSource] [char] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
	[UsageCount] [int] NULL 
) ON [PRIMARY]
GO


-- create entries in RefUsage
DECLARE RefUsageCursor SCROLL CURSOR FOR
	SELECT RefId, IdInSource
	FROM Reference
	WHERE IsMCLFlora = 1

DECLARE @referenceId int,
	@sourceId varchar(100)

OPEN refUsageCursor

FETCH FIRST FROM RefUsageCursor
	INTO 	@referenceId,
		@sourceId

WHILE @@FETCH_STATUS = 0 
BEGIN
	INSERT INTO mclBook_RefUsage (RefId, IdInSource) VALUES (@referenceId, @sourceId)

	FETCH NEXT FROM RefUsageCursor
		INTO 	@referenceId,
			@sourceId
END

CLOSE RefUsageCursor
DEALLOCATE RefUsageCursor
GO

-- count usage of references
UPDATE mclBook_RefUsage SET UsageCount = dbo.f_mclBook_countReferenceUsage(dbo.mclBook_RefUsage.IdInSource)
GO

