You cannot do this. For this you need to use dynamic SQL, something like this:
DECLARE @NewTablecols AS NVARCHAR(MAX); DECLARE @query AS NVARCHAR(MAX); select @NewTablecols = STUFF((SELECT distinct ',' + QUOTENAME(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'new_table' FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') , 1, 1, ''); SET @query = 'INSERT INTO new_table ( '+ @NewTablecols + ' ) SELECT ' + @NewTablecols + ' FROM YourTableName'; execute(@query);
It is assumed that the entire list of columns found in new_table will be found in the second table YourTableName , otherwise you will receive an error message saying that the column name was not found.
Look here:
source share