BEGIN TRY
SET IDENTITY_INSERT tablename ON
INSERT tablename (id,column) VALUES(1,N'value')
SET IDENTITY_INSERT tablename OFF
END TRY
BEGIN CATCH
RAISERROR ('Database already contains data. Skipping insertion.',16,1)
END CATCH
抛出错误Incorrect syntax near 'ON'.
没有TRY ... CATCH
块,它可以正常工作。
我正在做多个IDENTITY_INSERT ON或OFF,我想在单TRY ... CATCH
内做,我真的需要制作多个TRY ... CATCH
块吗?
答案 0 :(得分:2)
第一件事1,你不应该将值插入到标识列中,如果你确实需要你对从标识列生成的值的影响,请不要将它作为标识列。
无论如何,如果你确实需要做你在这里尝试做的事情,这里有一些代码安全地执行它并在你在Identity列中显式插入值后让你的表处于健康状态。
ALTER TABLE tablename
ADD CONSTRAINT uu_id UNIQUE (ID)
GO
DECLARE @id INT = 2;
DECLARE @value NVARCHAR(10) = N'Value';
BEGIN TRY
IF EXISTS (SELECT 1 FROM tablename WHERE ID = @id)
BEGIN
RAISERROR('Database already contains data. Skipping insertion.',16,1);
END
SET IDENTITY_INSERT tablename ON
BEGIN TRANSACTION;
INSERT tablename (id,ColumnName)
VALUES( @id , @value)
COMMIT TRANSACTION;
SET IDENTITY_INSERT tablename OFF;
DBCC CHECKIDENT('tablename', RESEED, 0);
DBCC CHECKIDENT('tablename', RESEED);
END TRY
BEGIN CATCH
IF (@@TRANCOUNT <> 0)
BEGIN
ROLLBACK TRANSACTION;
END
SELECT ERROR_MESSAGE() AS [ERROR_MESSAGE]
,ERROR_SEVERITY() AS [ERROR_SEVERITY]
,ERROR_STATE() AS [ERROR_STATE]
-- Do your other error logging here
END CATCH
答案 1 :(得分:-2)
我刚刚发现问题/解决方案。一切都在文档中,所以如果有人知道我可以在哪里学习RTFM课程,请给我发表评论。
可以在http://msdn.microsoft.com/de-de/library/ms175976(v=sql.100).aspx阅读,语法是
BEGIN TRY
{ sql_statement | statement_block }
END TRY
所以,如果你有多个sql语句,你会写一个块,这意味着
BEGIN TRY BEGIN
SET IDENTITY_INSERT tablename ON
INSERT tablename (id,column) VALUES(1,N'value')
SET IDENTITY_INSERT tablename OFF
END END TRY