我试图从一个表中选择一些字段并将它们从存储过程插入到现有表中。这是我正在尝试的:
SELECT col1, col2
INTO dbo.TableTwo
FROM dbo.TableOne
WHERE col3 LIKE @search_key
我认为SELECT ... INTO ...
适用于临时表,这就是我收到dbo.TableTwo
已存在的错误的原因。
如何将dbo.TableOne
中的多行插入dbo.TableTwo
?
答案 0 :(得分:592)
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
答案 1 :(得分:11)
有两种不同的方法可以实现从一个表到另一个表插入数据。
当先前已在数据库中创建表并且要将数据从另一个表插入此表时,将使用此方法。如果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
当先前未创建表时,需要使用此方法,并且需要在将来自一个表的数据从另一个表插入到新创建的表中时创建该方法。使用与所选列相同的数据类型创建新表。
----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
答案 2 :(得分:4)
它将如下所示:
insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration
from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""
答案 3 :(得分:2)
select *
into existing table database..existingtable
from database..othertables....
如果您已使用select * into tablename from other tablenames
,下次要追加,请说select * into existing table tablename from other tablenames
答案 4 :(得分:0)
如果目标表存在,但您不想指定列名:
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
答案 5 :(得分:0)
如果您想在新表中使用 select into 创建一个标识列,则可以按如下方式完成。
SELECT
ID = IDENTITY(INT, 1, 1),
name
INTO table2
FROM table1