MSSQL尝试在MySQL中捕获和设置标识插入?

时间:2010-06-28 13:59:15

标签: mysql tsql

你知道如何在MySQL中重写这些查询吗? 我找不到身份插入,我找不到任何尝试catch, 我不明白。

CREATE TRIGGER T1 ON DB1.dbo.A
AFTER INSERT AS

 BEGIN TRY

  SET IDENTITY_INSERT DB2.dbo.B ON
   INSERT INTO dbo.B(id, text) SELECT A.id,A.text FROM dbo.A INNER JOIN inserted I ON I.id = A.id
  SET IDENTITY_INSERT DB2.dbo.B OFF

  SET IDENTITY_INSERT DB2.dbo.D ON      
   INSERT INTO dbo.D(id, text) SELECT A.id,A.text FROM dbo.A INNER JOIN inserted I ON I.id = A.id     
  SET IDENTITY_INSERT DB2.dbo.D OFF

 END TRY
 BEGIN CATCH

  ROLLBACK TRANSACTION

  SET IDENTITY_INSERT DB2.dbo.B OFF
  SET IDENTITY_INSERT DB2.dbo.D OFF
 END CATCH

GO

2 个答案:

答案 0 :(得分:0)

只需将id列设置为AUTO_INCREMENT即可。您无需打开和关闭某些内容。

documentation

中了解详情

答案 1 :(得分:0)

MySQL触发器具有隐式事务支持,因此触发器不能使用显式或隐式开始或结束事务的语句,例如START TRANSACTIONCOMMITROLLBACK

在MySQL中没有必要启用将值插入主键列 - 这已经被允许了。但是,您可以切换外键约束检查和唯一索引检查:

http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_unique_checks

执行此操作的常用方法是将现有值存储在用户变量中,更改设置,然后在脚本完成后恢复设置:

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;

-- Your SQL statements here.

SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

我不确定为什么你需要在你的触发器中这样做,所以你的MySQL触发器看起来像这样:

DELIMITER |
CREATE TRIGGER T1 AFTER INSERT ON A FOR EACH ROW
BEGIN

    INSERT INTO B (id, text) VALUES (NEW.id, NEW.text);

    INSERT INTO C (id, text) VALUES (NEW.id, NEW.text);

END;|
DELIMITER ;

以下是快速测试的结果:

CREATE TABLE `A` (
  `id` int(11) NOT NULL auto_increment,
  `text` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
);

CREATE TABLE `B` (
  `id` int(11) NOT NULL auto_increment,
  `text` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
);

CREATE TABLE `C` (
  `id` int(11) NOT NULL auto_increment,
  `text` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
);

DELIMITER |
CREATE TRIGGER T1 AFTER INSERT ON A FOR EACH ROW
BEGIN

    INSERT INTO B (id, text) VALUES (NEW.id, NEW.text);

    INSERT INTO C (id, text) VALUES (NEW.id, NEW.text);

END;|
DELIMITER ;

INSERT INTO `A` (id, text) VALUES (1, 'Line 1');
INSERT INTO `A` (id, text) VALUES (2, 'Line 3');
INSERT INTO `A` (id, text) VALUES (3, 'Line 3');

SELECT * FROM `A`;
+----+--------+
| id | text   |
+----+--------+
|  1 | Line 1 |
|  2 | Line 3 |
|  3 | Line 3 |
+----+--------+

SELECT * FROM `B`;
+----+--------+
| id | text   |
+----+--------+
|  1 | Line 1 |
|  2 | Line 3 |
|  3 | Line 3 |
+----+--------+

SELECT * FROM `C`;
+----+--------+
| id | text   |
+----+--------+
|  1 | Line 1 |
|  2 | Line 3 |
|  3 | Line 3 |
+----+--------+

如果您想要与TRY ... CATCH类似的内容,则需要使用处理程序:
http://dev.mysql.com/doc/refman/5.1/en/declare-handler.html

这是关于MySQL触发器的文档:
http://dev.mysql.com/doc/refman/5.1/en/commit.html