In my stored procedure where I am generating report in the table Age
, user can define date range for which date range data needs to be come. Table Age
has AgeDesc
, StartDay
and EndDay
. Please check the example shown here:
Table Age
AgeDesc StartDay EndDay
-----------------------------------
< 30 0 30
>30 < 60 30 60
>60 < 90 60 90
>90 < 120 90 120
In my stored procedure i have created a temp table as below and i have added the rest of the column from Age table to temp table as
CREATE TABLE #Bills
(
LedgerId INT,
LedgerName varchar(300),
InvoiceNumber Varchar(50),
InvoiceDate DATETIME,
)
DECLARE @dynamicColumn nvarchar(max)
SELECT @dynamicColumn = STRING_AGG(QUOTENAME(AgeDesc),',')
FROM tblAge
-- SELECT @dynamicColumn
DECLARE @addColumn nvarchar(max);
SELECT @addColumn = STRING_AGG(' ALTER TABLE #Bills ADD ' + QUOTENAME(AgeDESC) + ' VARCHAR(100) NULL; ',' ')
FROM tblAge
EXEC sp_executesql @addColumn
SELECT * FROM #Bills
After select from #Bills
, I am getting column name as that is perfect
LedgerId | LedgerName | InvoiceNumber | InvoiceDate | < 30 | >30 < 60 | >60 < 90 | >90 < 120
Now i want to insert data in #bill from my select statement as per days define in tblAge for each columns like
<30 days InvoiceDate <= GETDATE() AND InvoiceDate >= GETDATE()-30
for >30 <60 InvoiceDate < GETDATE()-30 AND InvoiceDate >= GETDATE()-60
For >60 < 90 InovoiceDate < GETDATE()-60 AND InvoiceDAte >= GETDATE()-90
for >90 < 120 InovoiceDate < GETDATE()-90 AND InoviceDate >= GETDATE()-120
INSERT INTO @Bills
SELECT * FROM
L.LedgerId
,L.LedgerName
,B.InvoiceNumber,
B.InvoiceDate
rest for newly added column value as per provided details
How can I do this? User can insert multiple row for different date range that will be added automatically in the #Bills table so i am using this.
Please provide me your suggestions or example. I will really be thankful for that.