Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Column to Temp Table - 'Invalid column name DECIMAL'

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?

like image 991
ExceptionLimeCat Avatar asked Jun 18 '13 14:06

ExceptionLimeCat


People also ask

What is ## temp table?

"##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.

Can we alter temp table?

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.


1 Answers

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
like image 183
Martin Smith Avatar answered Oct 29 '22 07:10

Martin Smith