请看下面,我用数据创建了一个临时表,然后将所有数据插入到一个相同的表中,一个有一个标识列,一个没有。
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'