0

我正在尝试编写一个查询来检查仪表是否存在然后进行更新,它不会插入月度数据表!问题是我对语法感到困惑,我不知道该怎么做!

这就是数据库设计。假设我有仪表编号 2012345 我该怎么做?谢谢在此处输入图像描述

4

2 回答 2

1

在 SQL Server 中(仅用name作演示,您当然需要更多字段)

MERGE meters AS target
USING (SELECT '2012345') AS source (meternumber)
ON (target.meternumber = source.meternumber)
WHEN MATCHED THEN 
  UPDATE SET name='MeterUpdate#1', meternumber=source.meternumber
WHEN NOT MATCHED THEN 
  INSERT (name, meternumber) VALUES ('MeterInsert#1', source.meternumber);

一个用于测试的 SQLfiddle

在 MySQL 中,在meters(meternumber) 上创建一个唯一索引;

CREATE UNIQUE INDEX bop ON meters(meternumber);

然后使用插入/更新;

INSERT INTO meters (name, meternumber) VALUES ('MeterInsert#1', '2012345')
    ON DUPLICATE KEY UPDATE name='MeterUpdate#1', meternumber='2012345';

另一个 SQLfiddle

于 2013-07-01T20:31:21.613 回答
0

SQL Server 具有 MERGE http://msdn.microsoft.com/en-us/library/bb522522(v=sql.105).aspx,您可以将其用作 UPSERT。这是从文档中复制的示例(示例 A):

MERGE dbo.FactBuyingHabits AS Target
USING (SELECT CustomerID, ProductID, PurchaseDate FROM dbo.Purchases) AS Source
ON (Target.ProductID = Source.ProductID AND Target.CustomerID = Source.CustomerID)
WHEN MATCHED THEN
    UPDATE SET Target.LastPurchaseDate = Source.PurchaseDate
WHEN NOT MATCHED BY TARGET THEN
    INSERT (CustomerID, ProductID, LastPurchaseDate)
    VALUES (Source.CustomerID, Source.ProductID, Source.PurchaseDate)
OUTPUT $action, Inserted.*, Deleted.*; 
于 2013-07-01T18:43:27.827 回答