I'm creating a temporary table via a SELECT INTO
. I'd like to create the temp table then add a column to it like so:
SELECT id, name, val
INTO #TEMP_TBL
ALTER TABLE #TEMP_TBL ADD new_col AS DECIMAL
Error: Invalid column name 'DECIMAL'.
Where am I going wrong here?
"##tempTable" denotes Global Temporary Tables. It starts with the single hash value "##" as the prefix of the table name and its name is always unique. There is no random number appended to the name. Global Temporary Tables are visible to all connections of SQL Server.
You can ALTER the SQL Server temp tables after creating it, but table variables don't support any DDL statement like ALTER statement. SQL temp tables can't be used in User Defined Functions, but table variables can be.
Don't use the AS
. The correct syntax is
ALTER TABLE #TEMP_TBL ADD new_col DECIMAL(18,4) /*Or whatever precision/scale */
Or you could do this all in one go with
SELECT id,
name,
val,
CAST(NULL AS DECIMAL(18, 4)) AS new_col
INTO #TEMP_TBL
FROM ....
It thinks you are trying to add a computed column.
CREATE TABLE #TEMP_TBL(X INT)
/* Y is a computed column with same value as X*/
ALTER TABLE #TEMP_TBL ADD Y AS X
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With