我怎样才能将这个 UPDATE 查询放入这个现有的 SELECT 语句中?

How can I fit this UPDATE query into this existing SELECT statement?

我有一个现有的存储过程。我被要求尝试找到一种方法来将一组特定的逻辑放入过程中,以避免必须创建一个新的逻辑。然而,我并不是最擅长SQL,但我仍然愿意尽我所能完成我的任务。

我当前的目标:使用从 select 前 400 条语句生成的现有 table 并以某种方式适合我编写的更新(第二段代码)来处理它。

我现有的程序:

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
)

我在查询中添加了 Chart_id,因为您需要它来更新它。这将创建一个可用于更新记录的通用 table 表达式。

;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) + '+'