Create a temp table from another temp table and exclude some fields

Hursh 191 Reputation points
2022-07-19T22:12:03.287+00:00

;WITH cte AS
(
SELECT ID, CustNmbr, CustAddr, CustPhone, ProdNum, ProdDesc
FROM Customers
)
SELECT * INTO #TempCust FROM Results

Next, I want to SELECT * INTO #TempData but do not want to include the column "ID" and without explicitly naming each fields in it?

Developer technologies Transact-SQL
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2022-07-19T22:18:33.847+00:00

    Sorry, no feature to do this.

    Overall, I prefer explicit CREATE TABLE over SELECT INTO. And SELECT * is generally considered bad practice.


  2. Tom Phillips 17,771 Reputation points
    2022-07-20T01:37:34.013+00:00

    You can't.

    The syntax for columns list is either * for all columns, or you must list every column individually separated by commas.

    See:
    https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16

    0 comments No comments

  3. LiHong-MSFT 10,056 Reputation points
    2022-07-20T02:14:25.683+00:00

    Hi @Hursh
    For select list, you cannot use *(all columns) and also remove some columns at the same time.
    Considering that you have many columns in your table, you can execute the query below to get all the columns of the temp table, then copy the result of the query and manually delete the columns you don't need, which saves time of manual typing.

    DECLARE @Column_Names VARCHAR(MAX)  
      
    SELECT @Column_Names=ISNULL(@Column_Names + ',','')+QUOTENAME(name)  
    FROM   tempdb.sys.columns  
    WHERE  Object_id = Object_id('tempdb..#TempCust');   
      
    PRINT @Column_Names  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  4. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2022-07-20T08:03:04.637+00:00

    Slightly better than dabbling with dynamic SQL may be to get all columns into a temp table, and then

       ALTER TABLE #temp DROP COLUMN IDontWantThisOne  
    

    But, here too, the risk is that you outsmart yourself, if you don't know what you are doing.

    The best solution in most cases is to list all columns in CREATE TABLE, no matter how boring it may seem.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.