我在这里发现了许多关于如何执行此操作的其他帖子,但不确定如何编写初始select语句,该语句检查系统名称和更新语句,因为涉及临时表。我很擅长使用存储过程,更不用说临时表了,所以我很茫然。我所理解的是,数据通过XML提要传送到SP(此步骤未显示在此处)。然后将来自xml提要的数据存储在临时表中。由于SP现在正在写入,SP会将临时表中的数据插入到真实表中。我需要添加一个步骤来检查系统名称是否存在,如果存在,更新它,如果不存在,则插入它。我需要有关IF EXISTS select语句和更新查询的帮助。
这是原始陈述,仅包含插入内容。
原始陈述
insert into si_systemdetail(projectname, systemname, contactsbcuid, sdverifier, systemtype, location, proposedlivedate, status, bkpsa, pripsa,platform)
select
@project, systemname, contactsbcuid, sdverifier,systemtype, location,
proposedlivedate, 'Initial', bkpsa, pripsa, @platform
from @systemInfo
where status in ('Production','Production w/o Appl')
and systemname not in (select systemname from si_systemdetail)
and @project is not null`
更新声明
IF EXISTS (select systemname from si_systemdetail WHERE systemname = (select systemname from @systemInfo where systemname in (select systemname from si_systemdetail) and @project is not null))
BEGIN
-- update query
UPDATE si_systemdetail
SET **I DO NOT KNOW HOW TO WRITE THIS SECTION**
WHERE
systemname IN (select systemname from si_systemdetail)
AND @project is not null
END
ELSE
BEGIN
-- Write your insert query
insert into si_systemdetail(projectname, systemname, contactsbcuid, sdverifier,
systemtype, location, proposedlivedate, status, bkpsa, pripsa, platform)
select
@project, systemname, contactsbcuid, sdverifier,systemtype, location,
proposedlivedate, 'Initial', bkpsa, pripsa, @platform
from @systemInfo
where status in ('Production','Production w/o Appl')
and systemname not in (select systemname from si_systemdetail)
and @project is not null
END
答案 0 :(得分:1)
您只需尝试运行UPDATE
然后检查@@ROWCOUNT
即可保存一个查询。如果为0,则可以尝试INSERT
。在SQL Server 2008中,您可以使用MERGE
替换这个混乱的逻辑。
UPDATE d
SET d.projectname = i.projectname,
d.contactsbcuid = i.contactsbcuid,
-- other columns here
d.[platform] = @platform
FROM
dbo.si_systemdetail AS d
INNER JOIN @systemInfo AS i
ON i.systemname = d.systemname
WHERE
i.[status] IN ('Production', 'Production w/o Appl')
AND @project IS NOT NULL;
IF @@ROWCOUNT = 0
BEGIN
insert into ...
END
当系统名称匹配但@project为NULL或[status]不在这两个值中时,不清楚您要执行的操作。