[英]SQL Server 2008 ALTER TABLE add column with specific column
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
消息170,第15级,状态1,第1行
Line 1: Incorrect syntax near '@Column'.第1行:'@Column'附近的语法不正确。
Msg 170, Level 15, State 1, Line 1消息170,第15级,状态1,第1行
Line 1: Incorrect syntax near '@Column'.第1行:'@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
You can't do this without dynamic SQL. 没有动态SQL,您无法做到这一点。 Here is a query that will get you the result you want.
这是一个可以获得您想要的结果的查询。 You are more than welcome to uncomment the
--INTO #t
bit, however it is unclear what you want to do with the #temporary table beyond that (if you tell us the end result, instead of "I want to add a column name as @column, maybe we can help with that too). In order to continue referencing that #t table, you'll need to continue using code within the same scope - meaning more dynamic SQL that is executed within the same sp_executesql
call. 非常欢迎您取消注释
--INTO #t
位,但是不清楚除了那个之外你想用#temporary表做什么(如果你告诉我们最终结果,而不是“我想添加一个列名”作为@column,也许我们也可以帮助它。)为了继续引用#t表,你需要继续使用同一范围内的代码 - 这意味着在同一个sp_executesql
调用中执行的更多动态SQL。
DECLARE
@start DATE = '2012-01-02',
@end DATE = '2012-01-08';
DECLARE
@sql NVARCHAR(MAX) = N'',
@colMax NVARCHAR(MAX) = N'',
@colNames NVARCHAR(MAX) = N'';
;WITH x(rn) AS ( SELECT TOP (DATEDIFF(DAY, @start, @end) + 1) ROW_NUMBER()
OVER (ORDER BY [object_id]) - 1 FROM sys.all_columns ),
y(d) AS ( SELECT CONVERT(CHAR(10), DATEADD(DAY, rn, @start)) FROM x
)
SELECT @colMax += N',' + CHAR(13) + CHAR(10)
+ QUOTENAME(d) + ' = SUM(CASE WHEN DailyEnd = '''
+ d + ''' THEN TotalDailyTransactions ELSE 0 END)',
@colNames += N',' + QUOTENAME(d) FROM y;
SET @sql = 'SELECT StoreID, StoreName, ' + STUFF(@colNames, 1, 1, '')
+ ' --INTO #t
FROM ( SELECT StoreID, StoreName, ' + STUFF(@colMax, 1, 1, '')
+ ' FROM dbo.daily_trans
WHERE DailyEnd >= ''' + CONVERT(CHAR(10), @start) + ''''
+ ' AND DailyEnd < ''' + CONVERT(CHAR(10), DATEADD(DAY, 1, @end)) + '''
GROUP BY StoreID, StoreName
UNION ALL SELECT StoreID, StoreName, ' + STUFF(@colMax, 1, 1, '')
+ ' FROM dbo.outlets
WHERE DailyEnd >= ''' + CONVERT(CHAR(10), @start) + ''''
+ ' AND DailyEnd < ''' + CONVERT(CHAR(10), DATEADD(DAY, 1, @end)) + '''
GROUP BY StoreID, StoreName) AS x';
PRINT @sql;
-- EXEC sp_executesql @sql;
I think the problem is that you can't use a variable to define a column name. 我认为问题是你不能使用变量来定义列名。
I used some of your code to test with. 我用了一些代码来测试。 This first part executed fine.
第一部分执行得很好。
DECLARE @date1 datetime
DECLARE @Column varchar(8)
SET @date1 = '02 Jan 2012'
SET @Column = CONVERT(VARCHAR(8), @date1, 3)
select @Column
But when I added the CREATE TABLE statement and executed all of it at once, then I got the same error you did. 但是当我添加CREATE TABLE语句并立即执行所有操作时,我遇到了同样的错误。
CREATE TABLE #vl_temp_trans
(StoreID INT,
StoreName VARCHAR(100),
@Column MONEY) ----> column name to be date "@Column)
To do this you will need to build up the CREATE TABLE and ALTER TABLE statements as a string and then execute those using EXECUTE or sp_executesql . 为此,您需要将CREATE TABLE和ALTER TABLE语句构建为字符串,然后使用EXECUTE或sp_executesql执行这些语句。 A search for "dynamic sql" will also give you some article that describe this too.
搜索“动态sql”也会给你一些描述这个的文章。
There is two things you need to do to execute this code... 执行此代码需要做两件事......
SP_ExecuteSQl
SP_ExecuteSQl
have look to below code which is updated by me sure reslove your issue 看看下面的代码,由我更新肯定重新解决你的问题
DECLARE @date datetime
DECLARE @date1 datetime
DECLARE @date2 datetime
DECLARE @ColumnNAAME varchar(8)
Declare @Query NVARCHAR(1000)
DECLARE @ParmDefinition NVARCHAR(500);
SET @date = getdate()
SET @date1 = getdate()
SET @date2 = getdate()
SET @ColumnNAAME = CONVERT(VARCHAR(8), @date1, 3)
IF NOT EXISTS (SELECT * FROM sysobjects WHERE xtype = 'U' AND name = '#vl_temp_trans')
BEGIN
SET @ParmDefinition = N'@Column varchar(8)';
Set @Query = 'CREATE TABLE ##vl_temp_trans (StoreID INT, StoreName VARCHAR(100), ['+@ColumnNAAME+'] MONEY)'
EXECUTE sp_executesql @Query,@ParmDefinition,
@Column = @ColumnNAAME;
----> column name to be date "@Column)
SELECT * from ##vl_temp_trans
END
ELSE
BEGIN
SELECT * from ##vl_temp_trans
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.