I have a temporary table that hold all items available
#TableA
ItemId ItemName ItemVer
1 Name1 2
2 Name2 9
3 Name3 5
.
.
.
500 Name500 3
I then have another that holds all the dates a Snapshot was taken along with the SnapshotId
CREATE TABLE #tmpSnapshot_Dates(
[SnapshotId] [uniqueidentifier] NOT NULL,
[DateTaken] datetime NOT NULL)
INSERT INTO #tmpSnapshot_Dates SELECT SnapshotId, DateTaken From Snapshot_Info Where DateTaken <= @EndDate
Now for each date in the #tmpSnapshot_Dates table I want to get a count that relates it each Item
SELECT ItemId, Count(*) From Items Where SnapshotId = @SnapshotId
And then update #TableA by adding a column
DECLARE @ColName VARCHAR(100)
SET @ColName = 'Installed ' + CONVERT(Varchar, @DateA, 6)
exec('ALTER TABLE #TableA ADD ['+@ColName+'] int NOT NULL CONSTRAINT [DF_#TableA_Installed on] DEFAULT 0')
And then insert the data into the new column. I then need to repeat this for each date in #tmpSnapshot_Dates
giving a resulting #TableA that looks something like
#TableA
ItemId ItemName ItemVer Installed 01 Jan 12 Installed 07 Feb 12
1 Name1 2 34 33
2 Name2 9 56 59
3 Name3 5 12 26
.
.
.
500 Name500 3 98 106
My questions are
- Am I creating a nightmare here by approaching it the wrong way?
- How am I best to loop through
#tmpSnapshot_Datesand then get the data to create the next column? I always try to avoid cursors but is this one of those situation I need to use one?
There could be 12 columns to add and not every item will be returned for each date.
Definitely it won’t be nice, but yes, you need to use cursors and iterate over the
#tmpSnapshot_Dates, but if you have the option i suggest you to use a reporting software with the capability to create pivot grids.