我在sql server 2005中有两个表。在一个表table1中有一列其数据类型为xml,我们以xml格式保存数据。现在我有另一个表table2,我们存储几个文件名。所以现在我想在这样的xml数据上写查询,这将返回table2中定义的那些字段值。如何使用简单的sql语句而不是存储过程来实现它。
<Record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DELETED>
<JID>41185</JID>
<WID>0</WID>
<AccountReference>LH169</AccountReference>
<OEReference>Ari002</OEReference>
<InvoiceNumber>0</InvoiceNumber>
<OrderPlacedBy>Mark Catterall</OrderPlacedBy>
<Specialist>0FFICINA MOTTAUTO</Specialist>
<Priority>2</Priority>
<JobType>OUR</JobType>
<JobState>NOTSTARTED</JobState>
<JobAddedDate>2011-05-31T16:17:00</JobAddedDate>
<JobStartedDate>2011-05-31T16:18:00</JobStartedDate>
<JobFinishedDate>1777-01-01T00:00:01</JobFinishedDate>
<JobShippedDate>1777-01-01T00:00:01</JobShippedDate>
<RecievedDate>1777-01-01T00:00:01</RecievedDate>
<UPSShippingNumber />
<CustomerName>02 IRELAND</CustomerName>
<ContactName>ALAN CONLAN</ContactName>
<Telephone>00353868377926</Telephone>
<StandardHours>3.00</StandardHours>
<JobDescription>test for search 2</JobDescription>
<UserName xsi:nil="true" />
<AwaitingCustomer>0</AwaitingCustomer>
<ReturnToCore>0</ReturnToCore>
<AwaitingFromSalvage>0</AwaitingFromSalvage>
<PartDescription>test for search 2</PartDescription>
<PostalCode>IRELAND</PostalCode>
<OURPrice xsi:nil="true" />
<ExchangePrice xsi:nil="true" />
<NewPrice xsi:nil="true" />
<eBayPrice xsi:nil="true" />
<Status>UPDATED</Status>
</DELETED>
</Record>
假设在我的table2中存储的字段很少 JID,WID,AccountReference,OEReference,InvoiceNumber。
所以请指导我如何在xml数据上编写sql,它只返回xml数据中的JID,WID,AccountReference,OEReference,InvoiceNumber,但是文件名不会被硬编码,而是从另一个表table2中获取。
请指导我。
答案 0 :(得分:1)
要从xml读取数据,您可以像这样使用:
Select
MyXmlColumn.value('(Record/DELETED/JID)[1]', 'int' ) as JID,
MyXmlColumn.value('(Record/DELETED/WID)[1]', 'int' ) as WID,
MyXmlColumn.value('(Record/DELETED/AccountReference)[1]', 'nvarchar(255)' ) as AccountReference from table2
使用您的参数创建存储过程:
create procedure getmyxmldata
(
@param1 varchar(50),
@param2 varchar(50)
)
as
begin
declare @myQuery varchar(1000);
set @myQuery = 'Select
MyXmlColumn.value(''(Record/DELETED/' + @param1 + ')[1]'', ''nvarchar(255)'' ) as ' + @param1 + ',
MyXmlColumn.value(''(Record/DELETED/' + @param1 + ')[1]'', ''nvarchar(255)'' ) as ' + @param1 + ' from table2';
EXEC sp_executesql @myQuery
end
也可以从此存储过程中的另一个表中读取指定的字段,并在不传递参数的情况下动态创建select语句。
[更新2]
您可以针对多个已删除的代码尝试此操作:
Select
Row.value('(./JID)[1]', 'int' ) as JID,
Row.value('(./WID)[1]', 'int' ) as WID,
Row.value('(./AccountReference)[1]', 'nvarchar(255)' ) as AccountReference
from table2
CROSS APPLY MyXmlColumn.nodes('/Record/DELETED') as Record(Row)