SQL Server SELECT到现有表

我试图从一个表中选择一些字段,并将它们插入到存储过程中的一个现有表中。以下是我正在尝试的:

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

我认为SELECT ... INTO ...是临时表,这就是为什么我得到一个错误,dbo.TableTwo已经存在。

如何从dbo.TableOne插入多行到dbo.TableTwo?

579407 次浏览

SELECT ... INTO ...只在INTO子句中指定的表不存在时才有效-否则,你必须使用:

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

假设dbo中只有两列。TABLETWO -你需要指定列,否则:

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

它的工作原理如下:

insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration
from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""
select *
into existing table database..existingtable
from database..othertables....

如果你已经使用了select * into tablename from other tablenames,下一次,追加,你说select * into existing table tablename from other tablenames

有两种不同的方法实现将数据从一个表插入到另一个表。

对于现有表- INSERT INTO SELECT

当先前已经在数据库中创建了表,并且数据将从另一个表插入到这个表中时,使用此方法。如果insert子句和select子句中列出的列相同,则不需要列出它们。出于可读性和可伸缩性的目的,最好总是列出它们。

----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

如果之前没有创建表,并且需要将一个表中的数据插入到新创建的表中,则使用此方法。使用与所选列相同的数据类型创建新表。

----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

如果目标表确实存在,但你不想指定列名:

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

如果你想在新表中创建一个标识列,那么可以如下所示。

SELECT
ID = IDENTITY(INT, 1, 1),
name
INTO    table2
FROM table1

如果你想从Table_B插入到Table_A,只有当列不在Table_A时,然后使用以下方法:

BEGIN TRANSACTION


INSERT INTO dbo.Table_A (Column_1)
SELECT DISTINCT Some_Column AS Column_1
FROM dbo.Table_B
WHERE Some_Column
NOT IN (SELECT DISTINCT GroupId
FROM dbo.Table_A)


COMMIT