0

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

我当前的目标:使用从 select top 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
)
4

1 回答 1

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) + '+'
于 2015-06-04T22:06:50.627 回答