Inserting data into a temporary table

后端 未结 14 1378
情书的邮戳
情书的邮戳 2020-12-22 22:28

After having created a temporary table and declaring the data types like so;

CREATE TABLE #TempTable(
ID int,
Date datetime,
Name char(20))

H

相关标签:
14条回答
  • 2020-12-22 22:46
    insert into #temptable (col1, col2, col3)
    select col1, col2, col3 from othertable
    

    Note that this is considered poor practice:

    insert into #temptable 
    select col1, col2, col3 from othertable
    

    If the definition of the temp table were to change, the code could fail at runtime.

    0 讨论(0)
  • 2020-12-22 22:47

    My way of Insert in SQL Server. Also I usually check if a temporary table exists.

    IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP Table #MyTable
    
    SELECT b.Val as 'bVals'
      INTO #MyTable
    FROM OtherTable as b
    
    0 讨论(0)
  • 2020-12-22 22:48
    INSERT INTO #TempTable(ID, Date, Name)
    SELECT OtherID, OtherDate, OtherName FROM PhysicalTable
    
    0 讨论(0)
  • 2020-12-22 22:55

    Basic operation of Temporary table is given below, modify and use as per your requirements,

    -- CREATE A TEMP TABLE

    CREATE TABLE #MyTempEmployeeTable(tempUserID  varchar(MAX), tempUserName  varchar(MAX) )
    

    -- INSERT VALUE INTO A TEMP TABLE

    INSERT INTO #MyTempEmployeeTable(tempUserID,tempUserName) SELECT userid,username FROM users where userid =21
    

    -- QUERY A TEMP TABLE [This will work only in same session/Instance, not in other user session instance]

    SELECT * FROM #MyTempEmployeeTable
    

    -- DELETE VALUE IN TEMP TABLE

    DELETE FROM #MyTempEmployeeTable
    

    -- DROP A TEMP TABLE

    DROP TABLE #MyTempEmployeeTable
    
    0 讨论(0)
  • 2020-12-22 22:58

    I have provided two approaches to solve the same issue,

    Solution 1: This approach includes 2 steps, first create a temporary table with specified data type, next insert the value from the existing data table.

    CREATE TABLE #TempStudent(tempID  int, tempName  varchar(MAX) )
    INSERT INTO #TempStudent(tempID, tempName) SELECT id, studName FROM students where id =1
    
    SELECT * FROM #TempStudent
    

    Solution 2: This approach is simple, where you can directly insert the values to temporary table, where automatically the system take care of creating the temp table with the same data type of original table.

    SELECT id, studName  INTO #TempStudent FROM students where id =1
    
    SELECT * FROM #TempStudent
    
    0 讨论(0)
  • 2020-12-22 22:59
    SELECT  ID , Date , Name into #temp from [TableName]
    
    0 讨论(0)
提交回复
热议问题