2

Lets assume i have these tables

FooTable                     BarTable
id    value                  id    value

BarTable is acting as a mirrored table for FooTable and shall at some points recieve copies of entire rows from FooTable

Now, as i've tried this:

Insert Into BarTable select * from FooTable where yadi yada

and it feels horrible to use the *.

Is there any other way i might approach this?

4

2 回答 2

3
Insert Into BarTable
(id, value)
select
id, values
from FooTable
where yadi yada
于 2013-08-16T13:19:01.430 回答
2

请看下面,我用数据创建了一个临时表,然后将所有数据插入到一个相同的表中,一个有一个标识列,一个没有。

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'
于 2013-08-16T13:35:31.413 回答