我有一张表FlowTrack
:
CREATE TABLE [dbo].[FlowTrack]
(
[RowID] [tinyint] IDENTITY(1,1) NOT NULL,
[ApplicationNo] [varchar](50) NOT NULL,
[StatusID] [tinyint] NOT NULL,
[UpdateType] [varchar](100) NULL,
[CreatedDate] [datetime] NULL,
[CreatedBy] [varchar](50) NULL
) ON [PRIMARY]
示例数据:
RowID ApplicationNo StatusID UpdateType CreatedDate CreatedBy
1 BPS/ANA/MO/7/0146215 1 3 2015-06-17 12:59:56.387 Tests
2 BPS/BHI/20/0164615 1 3 2015-06-17 12:57:57.727 Tester
3 BPS/BHI/6/0204815 1 3 2015-06-17 12:57:57.727 Tester
我的程序:
ALTER procedure Flowtrack
(@APPNO varchar(50),
@vc_status CHAR(1),
@CreatedBy varchar(50) )
AS
BEGIN
MERGE INTO [dbo].Flowtrack AS target
USING (SELECT ApplicationNo, StatusID
FROM Flowtrack
WHERE ApplicationNo = @APPNO AND [StatusID] = @vc_status) AS source
ON target.ApplicationNo = Source.ApplicationNo
WHEN MATCHED THEN
UPDATE
SET
target.ApplicationNo = source.ApplicationNo,
target.StatusID = source.StatusID,
target.UpdateType = 3,
target.CreatedDate = getdate(),
target.CreatedBy = @CreatedBy
WHEN NOT MATCHED BY TARGET THEN
INSERT
([ApplicationNo], [StatusID], [UpdateType],
[CreatedDate], [CreatedBy])
VALUES (source.ApplicationNo, source.StatusID, 3,
getdate(), @CreatedBy);
end
当我进行更新时,它正在更新
EXEC Flowtrack 'BPS/ANA/MO/7/0146215',3,'Tests'
但是在尝试插入时,它没有插入新记录
我无法找出未插入的原因
插入新申请号
EXEC Flowtrack 'BPS/ANA/MO/7',3,'Test'
答案 0 :(得分:2)
问题在于:
MERGE INTO [dbo].Flowtrack AS target
USING (SELECT ApplicationNo, StatusID
FROM Flowtrack
WHERE ApplicationNo = @APPNO AND [StatusID] = @vc_status) AS source
ON target.ApplicationNo = Source.ApplicationNo
AND target.StatusID = Source.StatusID
问题是当您传递新的AppNo
时,source
为空且没有任何内容可以插入。
更改为:
MERGE INTO [dbo].Flowtrack AS target
USING (SELECT ApplicationNo, StatusID
FROM (VALUES(@APPNO, @vc_status, @CreatedBy)) t(ApplicationNo, StatusID , CreatedBy)
) AS source
ON target.ApplicationNo = Source.ApplicationNo
AND target.StatusID = Source.StatusID