我有一个现有的存储过程。我被要求尝试找到一种方法,使一组特定的逻辑适合程序,以避免必须创建一个新的逻辑。但是,我不是最好的SQL,但我仍然希望尽我所能来完成我的任务。
我目前的目标:使用select select 400语句生成的现有表,并以某种方式符合我编写的更新(第二块代码)来处理它。
我现有的程序:
USE [cph]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[PatientSynch]
@EnvironmentKey varchar(1)
AS
BEGIN
DECLARE @patId VARCHAR(25)
select top 400
c.pat_id as cpPatId,
(LEFT(c.fname, 1)
+LEFT(c.lname, 1)
+ @EnvironmentKey
+ RIGHT('00000000'
+ convert(varchar,c.pat_id),8 )) AS PRN,
c.pref_meth_cont_cn as PreferredChannel
--,p.cppatid,p.prn
from
dbo.cppat c
left outer join dbo.patient p on c.pat_id=p.cppatid
where
p.cppatid is null or p.prn is null
order by
c.pat_id desc
END
我根据自己的需要创建的声明:
UPDATE dbo.cppat
SET chart_id = CONVERT(VARCHAR(10), pat_id) + '+'
WHERE pat_id IN
(
SELECT pat_id
FROM cppat
)
答案 0 :(得分:1)
我在查询中添加了Chart_id,因为您需要它来更新它。这将创建一个可用于更新记录的公用表表达式。
;WITH Update_Complex_Query AS
(
SELECT TOP 400
c.pat_id AS cpPatId
, (LEFT(c.fname, 1) + LEFT(c.lname, 1) + @EnvironmentKey + + RIGHT('00000000' + convert(VARCHAR, c.pat_id), 8)) AS PRN
, c.pref_meth_cont_cn AS PreferredChannel
--,p.cppatid,p.prn
, c.Chart_Id
FROM dbo.cppat c
LEFT JOIN dbo.patient p
ON c.pat_id = p.cppatid
WHERE p.cppatid IS NULL
OR p.prn IS NULL
ORDER BY c.pat_id DESC
)
UPDATE Update_Complex_Query
SET Chart_id = CONVERT(VARCHAR(10), cpPatId) + '+'