我收到此错误消息,并且不知道如何调试它。
这是我的代码:
DECLARE @CurMonth int
DECLARE @CurYear int
DECLARE @Date datetime
SET @Date = DATEADD(m, -1, CAST(CAST(GETDATE() AS date) AS datetime))
SET @CurMonth = MONTH(@Date)
SET @CurYear = YEAR(@Date)
EXEC Tablename.dbo.ps_ProcedureTable1 @CurMonth, @CurYear
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[ps_ProcedureTable1]
(
@CurMonth int,
@CurYear int
)
AS
MERGE
Tablename.dbo.table1 AS target
USING
(SELECT
a.Ti, a.G, a.A, a.R, a.D, a.U,
a.FullName, a.W,
a.SDay, a.EDay, a.HDay,
a.C, a.QC, a.FC, a.CH, a.TH, a.FH,
a.LH, a.TtH, a.WKH, a.Va, a.Tr,
a.OT, a.Other, a.M, a.P, a.Ve,
a.SCa, a.HWK, a.AHr, a.SPF, a.AfTl,
a.TtHC, a.WKHRs, a.Days, a.ISWD,
a.HInD, a.OT, a.RT, a.HrSt, a.Sk
FROM Tablename.dbo.vw_Table1 a WITH (NOLOCK)
WHERE MONTH(a.W) = @CurMonth AND YEAR(a.W) = @CurYear) AS Source
ON Source.U = Target.U AND Source.W = Target.W
WHEN MATCHED THEN
UPDATE SET
SDay = Source.SDay,
EDay = Source.EDay,
HDay = Source.HDay,
C = Source.C,
QC = Source.QC,
FC = Source.FC,
CH = Source.CH,
TH = Source.TH,
FH = Source.FH,
LH = Source.LH,
TtH = Source.TtH,
WKH = Source.WKH,
Va = Source.Va,
Tr = Source.Tr,
OT = Source.OT,
Other = Source.Other,
M = Source.M,
P = Source.P,
Ve = Source.Ve,
SCa = Source.SCa,
HWK = Source.HWK,
AHr = Source.AHr,
SPF = Source.SPF,
AfTl = Source.AfTl,
TtHC = Source.TtHC,
WKHRs = Source.WKHRs,
Days = Source.Days,
ISWD = Source.ISWD,
HInD = Source.HInD,
OT = Source.OT,
RT = Source.RT,
HrSt = Source.HrSt,
Sk = Source.Sk
WHEN NOT MATCHED THEN
INSERT (Ti, G, A, R, D, U,
FullName, W, SDay, EDay, HDay,
C, QC, FC, CH, TH, FH, LH,
TtH, WKH, Va, Tr, OT, Other,
M, P, Ve, SCa, HWK, AHr, SPF,
AfTl, TtHC, WKHRs, Days, ISWD, HInD,
OT, RT, HrSt, Sk)
VALUES (Source.Ti, Source.G, Source.A, Source.R, Source.D, Source.U,
Source.FullName, Source.W, Source.SDay, Source.EDay, Source.HDay,
Source.C, Source.QC, Source.FC, Source.CH, Source.TH, Source.FH, Source.LH,
Source.TtH, Source.WKH, Source.Va, Source.Tr, Source.OT, Source.Other,
Source.M, Source.P, Source.Ve, Source.SCa, Source.HWK, Source.AHr, Source.SPF,
Source.AfTl, Source.TtHC, Source.WKHRs, Source.Days, Source.ISWD, Source.HInD,
Source.OT, Source.RT, Source.HrSt, Source.Sk);
GO
我收到此错误消息。
Msg 8672,Level 16,State 1,Procedure ps_EAGenerateWorkHours,Line 12
MERGE语句尝试多次更新或删除同一行。当目标行与多个源行匹配时会发生这种情况。 MERGE语句不能多次更新/删除目标表的同一行。优化ON子句以确保目标行最多匹配一个源行,或使用GROUP BY子句对源行进行分组。
警告:聚合或其他SET操作消除了空值。
我已在网上查看和研究,但我无法弄清楚我的代码有什么问题。
答案 0 :(得分:0)
合并查询执行将返回'重复的行'错误,如果
SELECT U, W, count(*)
FROM Tablename.dbo.vw_Table1 a WITH (NOLOCK)
WHERE MONTH(a.W) = @CurMonth AND YEAR(a.W) = @CurYear
group by U, W
having count(*)>1
或
SELECT U, W, count(*)
FROM Tablename.dbo.table1 a WITH (NOLOCK)
group by U, W
having count(*)>1
返回任何行
其中一个查询根据' on子句'返回重复的行。合并查询