我在查詢獲取某些資訊時遇到了一些問題
select id_column, d_description
from table1
where (select substring(cast(g_xml_comprobante as nvarchar(max)), charindex('contrato=', cast(g_xml_comprobante as nvarchar(max))) 10, 15) as 'contract'
from table1 a, table 3 b
where convert(varchar(6), b.d_date, 112) > '202108'
and b.id_column = a.id_column) = '2019896177'
我收到此錯誤:
訊息 512,級別 16,狀態 1,第 1 行
子查詢回傳了 1 個以上的值。當子查詢跟隨 =、!=、<、<=、>、>= 或當子查詢用作運算式時,這是不允許的。
情況是這樣的,我們在table1的一列中有XML資訊,在XML中有一個合同號。所以我想要的是從某些合同中獲取所有 ID,我有合同值,這就是為什么我需要它在那里。
有可能實作嗎?
如果我不清楚,請告訴我,以便我澄清。
謝謝您的幫助!
uj5u.com熱心網友回復:
Serge 寫的也是對的。但是,如果您只是檢查子查詢中是否存在特定的合同 ID,并且由于某種原因多行具有相同的合同,那么您可以做的是。您可以使用 In 子句如下
select id_column, d_description
from table1
where '2019896177' in (select substring(CAST(g_xml_comprobante as nvarchar(max)),CHARINDEX('contrato=',CAST(g_xml_comprobante as nvarchar(max))) 10,15) as 'contract' from table1 a,table3 b
where convert(varchar(6),b.d_date,112) > '202108' and b.id_column=a.id_column
)
然而,第二種方法在處理此類錯誤時很常見,但這主要取決于您的資料,回傳的是什么資料。如果您的子查詢為所有行回傳相同的值,那么最好的方法是Top 1在您的子查詢中使用。
select id_column, d_description
from table1
where (select Top 1 substring(CAST(g_xml_comprobante as nvarchar(max)),CHARINDEX('contrato=',CAST(g_xml_comprobante as nvarchar(max))) 10,15) as 'contract' from table1 a,table3 b
where convert(varchar(6),b.d_date,112) > '202108' and b.id_column=a.id_column
)='2019896177'
uj5u.com熱心網友回復:
您的查詢有很多問題:
- 您的主要問題:您要
table1第二次查詢,然后再次交叉連接整個表。 - 因此,
table3也可能有多種結果。所以你實際上需要一個EXISTShere. - 此外,您可以使用 XQuery 來決議 XML,而不是可怕的字串操作
- 應使用日期范圍查詢日期,如果您確實需要截斷時間組件,則可以使用
cast( ... as date) - 始終使用正確的連接語法,而不是不推薦使用的舊式逗號連接
- 使您的查詢可讀:使用空格,它是免費的
- 使用合理的表別名,而不是毫無意義
abc
select
t1.id_column,
t1.d_description
from table1 t1
where exist (select 1
from [table 3] t3
where t3.d_date > '202108'
and t3.id_column = t1.id_column
-- not sure exactly what XQuery you are looking for
and t3.g_xml_comprobante.exist('//@contrato[. = "2019896177"]') = 1
);
uj5u.com熱心網友回復:
您正在嘗試將子查詢結果與常量進行比較。但是您的子查詢回傳多個值。在這種情況下,您可以在子查詢之前使用 ANY 或 ALL。ANY 表示如果任何回傳值符合條件,則結果為真。ALL 表示如果所有回傳值都符合條件,則結果為真。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/366940.html
標籤:sql sql-server xml 子查询
上一篇:T-SQL,如何決議這個XML?
