如何将表中的所有列值插入到第二个相同的表中?

时间:2013-08-16 13:16:18

标签: sql-server tsql

让我们假设我有这些表

FooTable                     BarTable
id    value                  id    value

BarTable充当FooTable的镜像表,并且在某些时候应从FooTable

收到整行的副本

现在,正如我已经尝试过的那样:

Insert Into BarTable select * from FooTable where yadi yada

使用*感觉很糟糕。

我还有其他办法吗?

2 个答案:

答案 0 :(得分:3)

Insert Into BarTable
(id, value)
select
id, values
from FooTable
where yadi yada

答案 1 :(得分:1)

请参阅下文,我创建一个包含数据的临时表,然后将所有数据插入到相同的表中,其中一个表没有标识列。

CREATE TABLE #TableOne ( field1 int, field2 int )
CREATE TABLE #TableTwo ( field1 int, field2 int )

INSERT INTO #TableOne ( Field1, Field2 ) VALUES ( 100, 200 )
INSERT INTO #TableOne ( Field1, Field2 ) VALUES ( 101, 201 )
INSERT INTO #TableOne ( Field1, Field2 ) VALUES ( 102, 201 )

INSERT INTO #TableTwo
SELECT * FROM #TableOne

-- If table that your loading data into has an Identity column you need to turn it off and you need 
-- to specificy each column
CREATE TABLE #TableThree ( field1 int IDENTITY(1,1), field2 int )
SET IDENTITY_INSERT #TableThree ON 

INSERT INTO #TableThree ( Field1, Field2 )
SELECT * FROM #TableOne

SET IDENTITY_INSERT #TableThree OFF

如果表格中有大量字段,并且不想手动编写每个字段,则可以使用此代码。

DECLARE @TableColumns AS VARCHAR(MAX)

SELECT @TableColumns = ISNULL(@TableColumns,'') + CASE WHEN @TableColumns IS NULL THEN '' ELSE ', ' END + '[' + C.Name + ']'
FROM SYS.Columns C
WHERE OBJECT_ID = OBJECT_ID('dbo.MyTable')

PRINT 'INSERT INTO NewTable ( ' + @TableColumns + ')'
PRINT 'SELECT ' + @TableColumns + ' FROM MyTable'