簡體   English   中英

如何將 XML 從 C# 傳遞到 SQL Server 2008 中的存儲過程?

[英]How to pass XML from C# to a stored procedure in SQL Server 2008?

我想將 xml 文檔傳遞給 sql server 存儲過程,例如:

CREATE PROCEDURE BookDetails_Insert (@xml xml)

我想將一些字段數據與其他表數據進行比較,如果匹配,則必須將記錄插入到表中。

要求:

  1. 如何將 XML 傳遞給存儲過程? 我試過這個,但它不起作用: [工作]

     command.Parameters.Add( new SqlParameter("@xml", SqlDbType.Xml) { Value = new SqlXml(new XmlTextReader(xmlToSave.InnerXml, XmlNodeType.Document, null)) });
  2. 如何訪問存儲過程中的 XML 數據?

編輯: [工作]

 String sql = "BookDetails_Insert";
        XmlDocument xmlToSave = new XmlDocument();
        xmlToSave.Load("C:\\Documents and Settings\\Desktop\\XML_Report\\Books_1.xml");

        SqlConnection sqlCon = new SqlConnection("...");
        using (DbCommand command = sqlCon.CreateCommand())
        {
            **command.CommandType = CommandType.StoredProcedure;**
            command.CommandText = sql;
            command.Parameters.Add(
              new SqlParameter("@xml", SqlDbType.Xml)
              {
                  Value = new SqlXml(new XmlTextReader(xmlToSave.InnerXml
                             , XmlNodeType.Document, null))
              });

            sqlCon.Open();
            DbTransaction trans = sqlCon.BeginTransaction();
            command.Transaction = trans;

            try
            {
                command.ExecuteNonQuery();
                trans.Commit();
                sqlCon.Close();
            }
            catch (Exception)
            {
                trans.Rollback();
                sqlCon.Close();
                throw;
            }

編輯2 :如何創建一個選擇查詢來選擇頁面,基於一些條件的描述。

  <booksdetail> <isn_13>700001048</isbn_13> <isn_10>01048B</isbn_10>       
    <Image_URL>http://www.landt.com/Books/large/00/7010000048.jpg</Image_URL>   
    <title>QUICK AND FLUPKE</title> <Description> PRANKS AND JOKES QUICK AND FLUPKE </Description> </booksdetail> 

對於您問題的第 2 部分,請參閱我對存儲過程的回答:將 XML 作為參數傳遞和插入(鍵/值對)以獲取有關如何在存儲過程中使用 XML 的示例。

編輯:下面的示例代碼基於評論中給出的具體示例。

declare @MyXML xml

set @MyXML = '<booksdetail> 
                  <isbn_13>700001048</isbn_13> 
                  <isbn_10>01048B</isbn_10> 
                  <Image_URL>http://www.landt.com/Books/large/00/70100048.jpg</Image_URL> 
                  <title>QUICK AND FLUPKE</title> 
                  <Description> PRANKS AND JOKES QUICK AND FLUPKE - CATASTROPHE QUICK AND FLUPKE </Description> 
              </booksdetail>'

select Book.detail.value('(isbn_13/text())[1]','varchar(100)') as isbn_13, 
       Book.detail.value('(isbn_10/text())[1]','varchar(100)') as isbn_10, 
       Book.detail.value('(Image_URL/text())[1]','varchar(100)') as Image_URL, 
       Book.detail.value('(title/text())[1]','varchar(100)') as title, 
       Book.detail.value('(Description/text())[1]','varchar(100)') as Description
    from @MyXML.nodes('/booksdetail') as Book(detail)     

http://support.microsoft.com/kb/555266中所述,您需要將 xml 數據作為 NText 傳遞。

您可以按如下方式查詢 XML 變量:

DECLARE @PeopleXml XML
    SET @PeopleXml = '<People>
    <Person>
    <Name>James</Name>
    <Age>28</Age>
    </Person>
    <Person>
    <Name>Jane</Name>
    <Age>24</Age>
    </Person>
    </People>'
--  put [1] at the end to ensure the path expression returns a singleton.
SELECT p.c.value('Person[1]/Name[1]', 'varchar(50)')
FROM @PeopleXml.nodes('People') p(c) -- table and column aliases
public static string UpdateStaticCertificateFormateNo1Data(StaticCertificateFormatNo1LogicLayer StaticFormat1Detail)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
    con.Open();
    string strXMLRegistrationDetails, strXMLQutPut = "<root></root>";
    System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(StaticFormat1Detail.GetType());
    System.IO.MemoryStream stream = new System.IO.MemoryStream();
    x.Serialize(stream, StaticFormat1Detail);
    stream.Position = 0;
    XmlDocument xd = new XmlDocument();
    xd.Load(stream);
    strXMLRegistrationDetails = xd.InnerXml;
    SqlTransaction trn = con.BeginTransaction();
    try
    {
        SqlParameter[] paramsToStore = new SqlParameter[2];
        paramsToStore[0] = ControllersHelper.GetSqlParameter("@StaticFormat1Detail", strXMLRegistrationDetails, SqlDbType.VarChar);
        paramsToStore[1] = ControllersHelper.GetSqlParameter("@OutPut", strXMLQutPut, SqlDbType.VarChar);
        SqlHelper.ExecuteNonQuery(trn, CommandType.StoredProcedure, "UPS_UpdateStaticCertificateFormateNo1Detail", paramsToStore);
        trn.Commit();
    }
    catch (Exception ex)
    {
        trn.Rollback();
        con.Close();
        if (ex.Message.Contains("UNIQUE KEY constrastring"))
        { return "Details already in  List"; }
        else { return ex.Message; }
    }
    con.Close();
    return "Details successfully Added...";
}

您將主要使用 xPath 和 XQuery 來查詢和修改 XML 數據。

這是一個很好的起點http://msdn.microsoft.com/en-us/library/ms190798.aspx

我真的無法更具體,因為你的問題非常模糊。 如果您需要有關如何使用 XPath 和 XQuery 的幫助,請詢問有關如何做某事的具體問題。

var MainXML = new XElement("DocumentElement");
            foreach (GridViewRow gvr in gvStudent.Rows)
            {
                DropDownList ddl = (DropDownList)gvr.FindControl("ddlStudent");
                if (ddl.SelectedValue != "Select")
                {
                    string StuId = ((HiddenField)gvr.FindControl("hfStudentId")).Value;
                    var datacontent =
                                    new XElement("StudentStatus",
                                    new XElement("Status", ddl.SelectedValue),
                                    new XElement("StudentId", StuId)
                                    );
                    MainXML.Add(datacontent);
                }
            }
            if (MainXML.ToString() == "<DocumentElement />")
            {
                return;
            }
            string msg = obj.UpdateStudentProjectStatus(MainXML.ToString());
            
            
            --------------------------Sql--------------------------
            DECLARE
            @XMLData XML
                IF OBJECT_ID('tempdb..#tmpSelectionParameters') IS NOT NULL     --Remove dbo here 
                         DROP TABLE #tmpSelectionParameters   -- Remove "tempdb.dbo"

                SELECT   
                CAST(colx.query('data(Status)') AS varchar(500)) AS Status,
                CAST(colx.query('data(StudentId)') AS varchar(500)) AS StudentId 
                INTO    #tmpSelectionParameters
                FROM    @XMLData.nodes('DocumentElement/StudentStatus') AS Tabx ( Colx )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM