一次插入多个表以及其他记录

时间:2017-02-01 10:04:21

标签: sql sql-server

我有2张桌子

CREATE TABLE [dbo].[extendable1](
[serialnumber] [int] IDENTITY(1,1) NOT NULL,
[createdby] [nvarchar](36) NOT NULL,
[createddate] [datetime] NOT NULL)

CREATE TABLE [dbo].[extendable1_custom](
[serialnumber] [int] NOT NULL,
[createdby] [nvarchar](36) NOT NULL,
[createddate] [datetime] NOT NULL,
[currencyid] [nvarchar](3) NULL,
[partid] [nvarchar](30) NULL,
[price] [float] NULL)

对于具有相同属性的列以及自定义表中的其他数据,我需要同时在两个表中插入相同的值,但是我无法在线查找任何示例以向我展示完成之后,我看到了使用输出子句的例子,并试图从这条线走下去没有成功。

只是要指出我的目标是提取在extendable1中创建的indentity ID并将此值输入extendable1_custom

修改
我想插入的值的一个例子:

  

插入extendable1(createdby,createddate)选择' SO',getDate()

将serialnumber排除为IDENTITY字段,无论输入多少记录,这些值在可扩展1中都是相同的

  

从#temp <插入extendable1_custom(createdby,createddate,currencyid,partid,price)select(extendedable1.serialnumber,extendable1.createdby,extendable1.createddate,#temp.currencyid,#temp.partid,#temp.price) / p>

我应该走另一条路吗?或者这可能吗?

由于

3 个答案:

答案 0 :(得分:1)

您可以使用以下查询同时插入两个表格

START TRANSACTION;
 INSERT INTO extendable1 VALUES (column1, column2, ..);
 INSERT INTO extendable1_custom VALUES(column1, column2, columnx ..);
COMMIT;

答案 1 :(得分:0)

您不能在一个语句中插入相同的记录,但您可以在一个事务中按如下方式插入:

BEGIN TRAN
INSERT INTO [dbo].[extendable1] VALUES(.....)
INSERT INTO [dbo].[extendable1_custom] (serialnumber,createdby,createddate) VALUES(...,...,...)
COMMIT 

这意味着这块代码将完整地执行(全部或全部) - 您可以阅读有关Atomicity的信息,这是交易的四个特征之一。

答案 2 :(得分:0)

是的,你可以简单地使用begin tran并使用both语句提交。 其次,您需要使用错误处理以及相同的错误处理。 如果tran计数大于0,则使用回滚在这种情况下回滚查询。

虽然Tran的工作方式相同,但是所有人都会得到提交或者没有。但有时我们会遇到插入问题,所以为了获得最佳结果,还要使用rollback。