SQL Server SELECT into existing table
我试图从一个表中选择一些字段并将它们从存储过程插入到现有表中。 这是我正在尝试的:
1 2 3 4 | SELECT col1, col2 INTO dbo.TableTwo FROM dbo.TableOne WHERE col3 LIKE @search_key |
我认为
如何从
1 2 3 4 | INSERT INTO dbo.TABLETWO SELECT col1, col2 FROM dbo.TABLEONE WHERE col3 LIKE @search_key |
假设dbo.TABLETWO中只有两列 - 否则需要指定列:
1 2 3 4 5 | INSERT INTO dbo.TABLETWO (col1, col2) SELECT col1, col2 FROM dbo.TABLEONE WHERE col3 LIKE @search_key |
有两种不同的方法可以实现从一个表到另一个表插入数据。
对于现有表 - INSERT INTO SELECT
当先前已在数据库中创建表并将数据从另一个表插入此表时,将使用此方法。如果insert子句和select子句中列出的列相同,则不需要列出它们。为了可读性和可伸缩性的目的,始终列出它们是一种好习惯。
1 2 3 4 5 6 7 8 9 10 11 12 | ----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
当先前未创建表时,需要使用此方法,并且需要在将来自一个表的数据从另一个表插入到新创建的表中时创建该方法。使用与所选列相同的数据类型创建新表。
1 2 3 4 5 6 7 8 9 10 | ----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
它的工作原理如下:
1 2 | INSERT INTO Gengl_Del SELECT Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration FROM Gengl WHERE BOOK='" & lblBook.Caption &"' AND DocNO=" & txtVno.Text &"" |
1 2 3 | SELECT * INTO existing TABLE DATABASE..existingtable FROM DATABASE..othertables.... |
如果您已经使用
如果目标表确实存在但您不想指定列名称:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 |