我正在尝试进行UPDATE或INSERT,但我不确定如果不使用循环这是否可行。这是一个例子:
说我在下面的SQL中加入了两个表:tblCompany和tblOrders。
SELECT CompanyID, CompanyName, c.LastSaleDate, o.SalesOrderID, o.SalesPrice
, DATEADD(m, -6, GETDATE()) AS DateLast6MonthFromToday
FROM dbo.tblCompany c
CROSS APPLY (
SELECT TOP 1 SalesOrderID, SalesPrice
FROM dbo.tblOrders o
WHERE c.CompanyID = o.CompanyID
ORDER BY SalesOrderID DESC
) AS a
WHERE Type = 'End-User'
示例结果:
CompanyID, SalesOrderID, SalesPrice, LastSalesDate, DateLast6MonthFromToday
101 10001 50 2/01/2016 10/20/2016
102 10002 80 12/01/2016 10/20/2016
103 10003 80 5/01/2016 10/20/2016
我要做的是比较LastSalesDate和DateLast6MonthFromToday。条件如下:
如上面的示例结果,查询将仅更新SalesOrderID 10001和10003.而对于公司102,自LastSaleDate更大以来没有插入,那么只需对SalesOrderID执行UPDATE。
我知道如果我创建一个Cursor来循环遍历每个记录并进行比较然后更新或插入,我可能会这样做,但我想知道是否有另一种方法在没有循环的情况下执行此操作,因为我有大约20K记录。
很抱歉这个混乱,
答案 0 :(得分:1)
我不知道您的表格结构和数据类型。我一无所知 关于这2个表之间的重复和连接关系。 但我只希望在下一个例子中展示它是如何工作的:
use [your test db];
go
create table dbo.tblCompany
(
companyid int,
companyname varchar(max),
lastsaledate datetime,
[type] varchar(max)
);
create table dbo.tblOrders
(
CompanyID int,
SalesOrderID int,
SalesPrice float
);
insert into dbo.tblCompany
values
(1, 'Avito', '2016-01-01', 'End-User'),
(2, 'BMW', '2016-05-01', 'End-User'),
(3, 'PornHub', '2017-01-01', 'End-User')
insert into dbo.tblOrders
values
(1, 1, 500),
(1, 2, 700),
(1, 3, 900),
(2, 1, 500),
(2, 2, 700),
(2, 3, 900),
(3, 1, 500),
(3, 2, 700),
(3, 3, 900)
declare @column_1_value int = 5;
declare @column_2_value int = 777;
with cte as (
select
CompanyID,
SalesOrderID,
SalesPrice
from (
select
CompanyID,
SalesOrderID,
SalesPrice,
row_number() over(partition by CompanyID order by SalesOrderId desc) as rn
from
dbo.tblOrders
) t
where rn = 1
)
merge cte as target
using (select * from dbo.tblCompany where [type] = 'End-User') as source
on target.companyid = source.companyid
and source.lastsaledate >= dateadd(month, -6, getdate())
when matched
then update set target.salesprice = 1111
when not matched
then insert (
CompanyID,
SalesOrderID,
SalesPrice
)
values (
source.CompanyId,
@column_1_value,
@column_2_value
);
select * from dbo.tblOrders
如果您要向我提供信息,那么我可以正确准备目标和源表。