采取以下脚本:
EXEC sp_MSforeachtable @command1 = "DROP TABLE ?";
GO
CREATE TABLE _adminServices (
[ServiceID] INT CHECK ([ServiceID] > 0) NOT NULL IDENTITY,
[ServiceName] NVARCHAR(255) DEFAULT NULL,
[ManagerStaffID] INT CHECK ([ManagerStaffID] > 0) DEFAULT NULL,
[ODMStaffID] INT CHECK ([ODMStaffID] > 0) DEFAULT NULL,
[ReferralInactivityDays] INT DEFAULT NULL,
[TargetSupportHours] INT DEFAULT NULL,
[ShowInLists] SMALLINT NOT NULL DEFAULT '1',
[RecordEntryDate] DATETIME2(0) DEFAULT NULL,
[RecordModDate] DATETIME2(0) DEFAULT NULL,
PRIMARY KEY ([ServiceID])
) ;
CREATE INDEX [ManagerStaffID] ON _adminServices ([ManagerStaffID]);
CREATE INDEX [ODMStaffID] ON _adminServices ([ODMStaffID]);
CREATE INDEX [ShowInLists] ON _adminServices ([ShowInLists]);
GO
EXEC sp_MSforeachtable @command1 = 'IF (
select COUNT(TABLE_NAME)
from INFORMATION_SCHEMA.COLUMNS
where COLUMNPROPERTY(object_id(TABLE_SCHEMA+''.''+TABLE_NAME), COLUMN_NAME, ''IsIdentity'') = 1
AND TABLE_SCHEMA+''.''+TABLE_NAME = ''?''
) = 1
BEGIN
SET IDENTITY_INSERT ? ON;
END;';
GO
INSERT INTO _adminServices (ServiceID, ServiceName, ManagerStaffID, ODMStaffID, ReferralInactivityDays, TargetSupportHours, ShowInLists, RecordEntryDate, RecordModDate) VALUES
(1, 'Service 1', 16, 18, 0, NULL, 1, '2017-07-21 11:59:56', '2017-10-25 09:38:02');
GO
当我在SSMS中执行上述脚本时,出现以下错误:
Msg 544,Level 16,State 1,Line 36 当IDENTITY_INSERT设置为OFF时,无法在表'_adminServices'中为identity列插入显式值。
谁能告诉我为什么?
编辑:我的目标如下:我有多个表和多个插入。 对于插入,我有脚本。因为我不想为每个表写入SET IDENTITY_INSERT ON和OFF,因为我只对文件进行INSERT INTO查询,所以我想要一种方法来执行以下操作:
删除数据库中的所有表
创建所有表(我有这个SQL)
将所有必需的身份设置为ON
运行插入(我有SQL)
将所有必需的身份设置为关闭
答案 0 :(得分:0)
插入原始值的一般方案:
创建表
SET IDENTITY INSERT ON
INSERT VALUES
SET IDENTITY INSERT OFF
如果您的表没有单一结构sp_MSforeachtable,那么您将不适合