变量字段,需要用EXECUTE来执行。
BEGIN
IF OBJECT_ID ( ' dbo.#TempTable ' ) IS NOT NULL
DROP TABLE dbo.#TempTable
CREATE TABLE #TempTable
(
Id INT ,
Item NVARCHAR ( 100 )
)
END
IF OBJECT_ID ( ' dbo.#TempTable ' ) IS NOT NULL
DROP TABLE dbo.#TempTable
CREATE TABLE #TempTable
(
Id INT ,
Item NVARCHAR ( 100 )
)
END
动态添加一个以当前日期作为字段:
BEGIN
DECLARE @ColumnName NVARCHAR ( 100 )
SET @ColumnName = ' [ ' + CONVERT ( NVARCHAR ( 100 ), GETDATE (), 112 ) + ' ] ' -- 20090629
EXECUTE ( ' ALTER TABLE #TempTable ADD ' + @ColumnName + ' NVARCHAR(100) ' )
END
DECLARE @ColumnName NVARCHAR ( 100 )
SET @ColumnName = ' [ ' + CONVERT ( NVARCHAR ( 100 ), GETDATE (), 112 ) + ' ] ' -- 20090629
EXECUTE ( ' ALTER TABLE #TempTable ADD ' + @ColumnName + ' NVARCHAR(100) ' )
END
执行SELECT * FROM #TempTable之后,结果: