SQL Server SELECT進入現有表

我試圖從一個表中選擇一些字段並將它們從存儲過程插入到現有表中。 這是我正在嘗試的: sql

SELECT col1, col2
INTO dbo.TableTwo 
FROM dbo.TableOne 
WHERE col3 LIKE @search_key

我認爲SELECT ... INTO ...是臨時表,這就是爲何我獲得dbo.TableTwo已經存在的錯誤。 數據庫

如何從dbo.TableOne dbo.TableTwo多行插入dbo.TableTwoide


#1樓

它的工做原理以下: spa

insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration 
from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""

#2樓

select *
into existing table database..existingtable
from database..othertables....

若是你已經使用了select * into tablename from other tablenames ,下次要追加,你能夠select * into existing table tablename from other tablenames code


#3樓

SELECT ... INTO ...僅在INTO子句中指定的表不存在時纔有效 - 不然,您必須使用: get

INSERT INTO dbo.TABLETWO
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

假設dbo.TABLETWO中只有兩列 - 不然須要指定列: it

INSERT INTO dbo.TABLETWO
  (col1, col2)
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

#4樓

有兩種不一樣的方法能夠實現從一個表到另外一個表插入數據。 io

對於現有表 - INSERT INTO SELECT

當先前已在數據庫中建立表並將數據從另外一個表插入此表時,將使用此方法。 若是insert子句和select子句中列出的列相同,則不須要列出它們。 爲了可讀性和可伸縮性的目的,始終列出它們是一種好習慣。 table

----Create testable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable

對於非現有表 - SELECT INTO

當先前未建立表時,須要使用此方法,而且須要在未來自一個表的數據從另外一個表插入到新建立的表中時建立該方法。 使用與所選列相同的數據類型建立新表。 ast

----Create a new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable

參考1 2


#5樓

若是目標表確實存在但您不想指定列名稱:

DECLARE @COLUMN_LIST NVARCHAR(MAX);
DECLARE @SQL_INSERT NVARCHAR(MAX);

SET @COLUMN_LIST = (SELECT DISTINCT
    SUBSTRING(
        (
            SELECT ', table1.' + SYSCOL1.name  AS [text()]
            FROM sys.columns SYSCOL1
            WHERE SYSCOL1.object_id = SYSCOL2.object_id and SYSCOL1.is_identity <> 1
            ORDER BY SYSCOL1.object_id
            FOR XML PATH ('')
        ), 2, 1000)
FROM
    sys.columns SYSCOL2
WHERE
    SYSCOL2.object_id = object_id('dbo.TableOne') )

SET @SQL_INSERT =  'INSERT INTO dbo.TableTwo SELECT ' + @COLUMN_LIST + ' FROM dbo.TableOne table1 WHERE col3 LIKE ' + @search_key
EXEC sp_executesql @SQL_INSERT
相關文章
相關標籤/搜索