2013-07-03 62 views
1

我將以下xml發送到要在where子句中使用的sql server存儲過程。int的通過列表作爲xml與where子句一起使用

<root> 
<id>1</id> 
<id>2</id> 
<id>3</id> 
</root 

我想制定一種方法來有一個選擇語句where where子句將檢查傳入的XML參數中的任何id值。

事情是這樣的:

@xml xml 
select * from table 
where (if exists (select id in @xml)) 

抱歉,我不是在SQL非常好。

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

+0

@Jamesla。 。 。是xml類型還是'nvarchar'類型的xml? –

+0

當前xml類型,但可以根據需要進行更改。 – Jamesla

回答

1
declare @xml xml; 
set @xml = CAST('<root><id>1</id><id>2</id><id>3</id></root>' AS XML) 

select id from mytable 
where exists(select 1 from @xml.nodes('/root/id')as result(node) 
      where node.value('(.)[1]', 'int') = id) 
+0

你是一個完美運作的傳奇人物。 – Jamesla

0

我總是參考Erland Sommarskog的this link來處理sql中的數組。它提供了一個很好的示例,並將其與其他將數組傳遞給存儲過程的機制進行了對比。

請注意,如果您使用的是SQL Server 2008,他具有another link詳細說明使用表值參數。對你的例子來說,這可能是矯枉過正的,但如果你渴望瞭解可供使用的東西,那麼它的全部值得一讀。