Wondering how to build a logic for the below scenario (I am using SQL Server 2008 & above).
In TblMaster each record will have a Start value and an End value. Along with that a CharToAdd varchar column as well. If the range says 1 to 3 then in the TblDetails there should be an entry for 1,2,3. Not sure whether I am explaining it effectively so have provided a screenshot with sample input/output as well.
Ranges would be anywhere between 5000 to 100000 (max) so performance is a concern as well.
Table Schema:
CREATE TABLE [dbo].[VMaster](
[VID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[VName] [varchar](30) NOT NULL
)
GO
CREATE TABLE [dbo].[TblMaster](
[SID] [int] IDENTITY(1,1) NOT NULL Primary Key,
[VID] [int] NOT NULL,
[CreatedDate] [datetime] default (getdate()) NOT NULL,
[CharToAdd] [varchar](10) NOT NULL,
[Start] [int] NOT NULL,
[End] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TblDetails](
[DetailsID] [int] IDENTITY(1,1) NOT NULL Primary Key,
[SID] [int] NOT NULL,
[Sno] [int] NOT NULL,
[ConcatenatedText] [varchar](20) NOT NULL,
[isIssued] [bit] default (0) NOT NULL,
[isUsed] [bit] default (0) NOT NULL
)
GO
ALTER TABLE [dbo].[TblMaster] WITH CHECK ADD CONSTRAINT [fk_SI_id] FOREIGN KEY([VID])
REFERENCES [dbo].[VMaster] ([VID])
GO
ALTER TABLE [dbo].[TblMaster] CHECK CONSTRAINT [fk_SI_id]
GO
Sample data for the tables:
Insert into dbo.VMaster Values ('A1')
GO
Insert into dbo.TblMaster Values (1,default, 'ABC', 100, 105)
GO
Sample records inserted into the tables and the output expected in TblDetails:
EDIT: What if the record in TblMaster is getting updated later? If both the bit fields in TblDetails are 0 for all the corresponding auto-generated rows then should delete the old records and regenerate based on the "new range" updated.
--Modifying the original range. So the records 100, 104, 105 has to be removed
-- from tblDetails if its isIssued, isUsed are both 0.
-- If not will have to reject this update
Update dbo.TblMaster
Set Start = 101, [End] = 103
Where SID = 1
--Another scenario. We need to remove 100,101,102,103,104,105 from tblDetails if
-- its isIssued, isUsed are both 0. Then create entries from 1000 to 1500 in tblDetails.
-- If isIssued, isUsed are not 0 then will have to reject this update
Update dbo.TblMaster
Set Start = 1000, [End] = 1500
Where SID = 1
Go recursive :
OUPUT
I use a UDF to create Dynamic Ranges. A Numbers or Tally Table would do the same
Returns
The UDF if you care to use it (you may have to set maxrecursion to 0)
The following example illustrates how it is dynamic
Notice the UPDATE
Returns
You can certainly use one of many tricks for creating a list of numbers. What's probably easiest for you is to actually create one in the database. I'll leave that task up to you. So let's assume you have a
Numbers
table with values from 0 up to the maximum possible rows in a range.