生成的bug数据脚本如何不在insert语句中设置IDENTITY?

use*_*898 3 sql-server ssms azure-sql-database

I'm using SQL Server Management Studio to generate sql script (big one) to update Azure DB. The problem is that the script is generated with IDENTITY on and the insert statements are exported with the ID column which as result gives me the errors :

Cannot insert explicit value for identity column in table 'Table_Name' when IDENTITY_INSERT is set to OFF.

My question is how to generate the script right that is will not use IDENTITY on and the insert.

wBo*_*Bob 6

bcp可能是实现这一目标的更好方法,并且可以很好地与 Azure SQL 数据库配合使用。它是一个命令行工具,可让您轻松提取和加载数据。例如:

bcp "dbo.yourTable" out c:\temp\temp.bcp -S "yourSourceServer" -d "yourSourceDatabase" -T -n

bcp "dbo.yourTable" in c:\temp\temp.bcp -S "yourTargeteServer" -d "yourTargetDatabase" -U someSQLLogin -P somePassword -E -n
Run Code Online (Sandbox Code Playgroud)

-Ebcp in语句中指定开关以保留您的IDENTITY值。替换上面我模板中的表、服务器和数据库名称,看看是否可以运行第一个语句。请注意,在第一个示例中,我使用的是 Windows 身份验证 ( -T),但在第二个示例中使用的是SQL 身份验证(-U用于用户和-P密码)。bcp 的 MSDN 主页提供了一些很好的例子:

https://msdn.microsoft.com/en-us/library/ms162802.aspx

如果您的表中已经有一些数据,请考虑先将数据插入临时表,然后插入INSERT主表,例如

SET IDENTITY_INSERT yourTargetTable ON
GO

INSERT INTO yourTargetTable ( columnList )
SELECT columnList
FROM yourStagingTable s
WHERE NOT EXISTS
    (
    SELECT *
    FROM yourTargetTable t
    WHERE s.yourPrimaryKey = t.yourPrimaryKey
    )
GO

SET IDENTITY_INSERT yourTargetTable OFF
GO
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以实现这一点。

  • 例如,您可以使用 SQL Server 集成服务 (SSIS) 完成同样的事情,但创建 SSIS 项目会产生一些开销。
  • 例如,如果您的表不太大,请在 tempdb 中使用类似SELECT [all columns except the identity column] INTO tempdb.dbo.scratchTable FROM yourMainTable. Generate Scripts针对此副本运行该选项,然后删除您的临时表。