【问题标题】:How to return JSON object by executing SQL Server stored procedure如何通过执行 SQL Server 存储过程返回 JSON 对象
【发布时间】:2015-10-23 05:43:47
【问题描述】:

我正在使用此方法返回 XML 作为结果。执行存储过程后,我需要返回一个 json 对象。我应该在哪里编辑以下代码以返回 JSON 对象?

public XmlElement GetGraphData(int eventTypeID, int patientID)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
    con.Open();

    SqlCommand cmd = new SqlCommand("sp_GetGraphData", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@EventID", eventTypeID);
    cmd.Parameters.AddWithValue("@PatientID", patientID);

    cmd.ExecuteNonQuery();

    SqlDataAdapter da = new SqlDataAdapter(cmd);

    DataSet ds = new DataSet();
    da.Fill(ds);

    con.Close();

    XmlDataDocument xmldata = new XmlDataDocument(ds);
    XmlElement xmlElement = xmldata.DocumentElement;
}

【问题讨论】:

  • 您想将数据集转换为 json 对象。对吗?
  • 旁注:您应该为您的存储过程使用sp_ 前缀。微软有reserved that prefix for its own use (see Naming Stored Procedures),你确实会在未来某个时候冒着名称冲突的风险。 It's also bad for your stored procedure performance。最好只是简单地避免 sp_ 并使用其他东西作为前缀 - 或者根本不使用前缀!
  • 另外 - 你正在执行查询两次 - 一次在ExecuteNonQuery,第二次在da.Fill(ds) - 不要那样做!你想做什么?从数据库加载数据?不要为此使用ExecuteNonQuery!此调用仅适用于不返回任何数据的 SQL 语句! (如INSERTDELETE
  • 是的,Amey Deshpande .. 你是对的
  • 你可以使用Newtonsofts Json.Net

标签: c# sql-server json xml stored-procedures


【解决方案1】:

SQL Server 2016 具有 FOR JSON 子句,可直接在查询/存储过程中格式化查询结果 - 请参阅 https://msdn.microsoft.com/en-us/library/dn957476.aspx

【讨论】:

    【解决方案2】:

    对于以 JSON 格式返回创建 SP 类似

    CREATE PROCEDURE spGetAlluser 
    
    AS
    BEGIN
        Select * from AspNetUsers FOR JSON AUTO
    END
    GO
    

    在类 obj 中获取用户详细信息

    var UserDetails=JsonConvert.DeserializeObject<string>(result)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 2015-11-02
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      相关资源
      最近更新 更多