2009-09-16 169 views
1

我遇到过一个场景,我想将大量数据传递给存储过程以生成一些动态SQL。SQL Server CLR存储过程JSON参数

我想传递的数据存储在我在ASP.NET MVC Web项目中使用的Json/C#类对象中。

[ 
{ 
    "code":"ABC123", 
    "Count": "12998", 
    "Params": 
    [ 
    {"name": "Recent", "value": "0-12m"}, 
    {"name": "Orders", "value": "1"} 
    ] 
}, 
{ 
    "code":"ABC124", 
    "Count": "13998", 
    "Params": 
    [ 
    {"name": "Recent", "value": "0-12m"}, 
    {"name": "Orders", "value": "2"} 
    ] 
}, 
{ 
    "code":"ABC125", 
    "Count": "7998", 
    "Params": 
    [ 
    {"name": "Recent", "value": "0-12m"}, 
    {"name": "Orders", "value": "3"} 
    ] 
} 
] 
..... 

然后使用该文本参数转换回JSON对象,我用这一个动作过滤器将其转换为一个对象。

public class ObjectFilter : ActionFilterAttribute 
{ 

    public string Param { get; set; } 

    public Type RootType { get; set; } 

    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 

     if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) 
     { 

      object o = 

      new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream); 
      filterContext.HttpContext.Request.InputStream.Seek(0, SeekOrigin.Begin); // Rewind InputStream for other filters 

      filterContext.ActionParameters[Param] = o; 

     } 

     else 
     { 

      var xmlRoot = XElement.Load(new StreamReader(filterContext.HttpContext.Request.InputStream, 

      filterContext.HttpContext.Request.ContentEncoding)); 

      object o = new XmlSerializer(RootType).Deserialize(xmlRoot.CreateReader()); 

      filterContext.ActionParameters[Param] = o; 

     } 

    } 

}

然后用C#等在我的CLR存储过程创建一个SQL语句,如:

UPDATE [Sample] 
SET [Field] = 
CASE 
WHEN [Recent] = "0-12m" AND [Orders] = "1" THEN "ABC123" 
WHEN [Recent] = "0-12m" AND [Orders] = "2" THEN "ABC124" 
WHEN [Recent] = "0-12m" AND [Orders] = "3" THEN "ABC125" 
... 

这是可能的,有没有人做过这样的事。我看过几篇关于使用XML参数的文章,但没有使用使用反序列化(?)json的varchar参数的文章。

+0

这可能有助于[在SQL Server中使用JSON字符串](http:// www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/?utm_source=simpletalk&utm_medium=email-main&utm_content=JSON-20101116&utm_campaign=SQL) – aaroned 2010-11-19 07:19:50

回答

1

我试图用我的代码来解析一个JSON字符串参数,但所需要的命名空间是不是在一个SQL CLR项目使用,因此我已经切换到文档XML参数。

1

如果您自己构建不安全的装配体,则只能使用不安全的装配体,如DataContractJsonSerializer。另一种选择是跳过对不安全程序集的引用和使用,并编写自己的JSON解析代码(或从别人那里复制它)。