Is there any way I can add a column to a table but I want the heading to be a date, and every new column added will have a column heading for the next day hence the
SET @date1 = @date1 + 1
What I want the table to look like is, where the date on top is a new column for each day the script loops:
StoreID StoreName 02/01/12 03/01/12 04/01/12
1234 Coles1 7512 8574
1235 Coles2 7210 8441
1236 Coles3 4845 5448
When I run the script I get the following error messages:
Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near '@Column'.
Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near '@Column'.
Here is my script:
DECLARE @date datetime
DECLARE @date1 datetime
DECLARE @date2 datetime
DECLARE @Column varchar(8)
SET @date = '02 Jan 2012'
SET @date1 = '02 Jan 2012'
SET @date2 = '08 Jan 2012'
SET @Column = CONVERT(VARCHAR(8), @date1, 3)
IF NOT EXISTS (SELECT * FROM sysobjects WHERE xtype = 'U' AND name = '#vl_temp_trans')
BEGIN
CREATE TABLE #vl_temp_trans
(StoreID INT,
StoreName VARCHAR(100),
@Column MONEY) ----> column name to be date "@Column)
END
WHILE (@date1 <= @date2)
BEGIN
SET @Column = CONVERT(VARCHAR(8), @date1, 3)
ALTER table #vl_temp_trans
ADD @Column MONEY ----> column name to be date "@Column"
Insert into #vl_temp_trans (storeID, storeName, @Column)
select storeId, storeName, TotalDailyTransactions
from daily_trans t1 (nolock)
full outer join outlets t2 (nolock) on t1.StoreID = t2.StoreID
where DailyEnd = @date1 + 1
SET @date1 = @date1 + 1
END
TotalDailyTransactionsandDailyEnd? One, both? Why aren't any of your columns prefixed with their table alias to avoid ambiguous column name errors (and questions from us)?{}button to make them look like your code sample.