试图将这些查询合并为一个,因为我想在不使用 temp table 的情况下编写查询。不断收到语法错误

Trying to combine this queries into one, because I want to write queries without using temp table. Keep getting syntax error

    SELECT
          CAST([patientDATA] AS XML).value('PatientcardCard[1]/Replacements[1]/patientId[1]', 'nvarchar(80)') [patientId]
        ,* into #tmp
        FROM hospital [c1] with(NOLOCK)
        where
        patientserial in (
        select ptserial From patients with(Nolock)
        where patientsid=6889
        and patientprogramid in (
        26917,
        21296,
        27025
        )
        )
    
    

    select patientId,patientbarcode,patientprogramID
    into #tmp1
    From #tmp
    join patients with(nolock) on patientserial=ptserial
    where patientid in
    ('0401478300007847',
    '0401478300008566',
    '0401478300008761',
    '0401478300008727',
    '0401478300007648',
    '0401478300008020'
)

所以第一个查询是使用强制转换从列内的标签获取值,标签是 patientID,并将数据存储到临时文件中 table。

第二个查询是从临时 table 中提取数据。我想在不使用 temp table 的情况下编写嵌套查询。但我保留了语法错误,这是我目前的查询:

select patientId,patientbarcode,patientprogramID
        
        From (
 SELECT
          CAST([patientDATA] AS XML).value('PatientcardCard[1]/Replacements[1]/patientId[1]', 'nvarchar(80)') [patientId]
        ,* into #tmp
        FROM hospital [c1] with(NOLOCK)
        where
        patientserial in (
        select ptserial From patients with(Nolock)
        where patientsid=6889
        and patientprogramid in (
        26917,
        21296,
        27025
        )
        )



)
        join patients with(nolock) on patientserial=ptserial
        where patientid in
        ('0401478300007847',
        '0401478300008566',
        '0401478300008761',
        '0401478300008727',
        '0401478300007648',
        '0401478300008020'
    )

我在 SQL 中的错误:

invalid column in first line, around patientId,patientbarcode


and in join part, invalid column as ptserial

是不是因为值被投了?

你的方法有些问题。

  1. SELECT * 不是一个好主意。也显得没有必要 为您的最终查询。
  2. 您应该参考每列的 table 来自.
  3. 你可能想多了。
SELECT CAST([patientDATA] AS XML).value('PatientcardCard[1]/Replacements[1]/patientId[1]', 'nvarchar(80)') [patientId]
, patientbarcode
, patiendprogramID

FROM hospital h
    INNER JOIN patients p ON p.ptserial = h.patientserial

WHERE patientsid = 6889
  AND patientprogramid IN (26917, 21296, 27025)
  AND patientid IN (
        '0401478300007847'
        ,'0401478300008566'
        ,'0401478300008761'
        ,'0401478300008727'
        ,'0401478300007648'
        ,'0401478300008020'
        )