我有一个带有重复列的JSON数据,我需要一次插入到SQL Server.Here CommonCategoryRowId,并且CommonCategoryAttributeName将更改
以下是JSON数据的示例
"[{\"CommonCategoryAttributeName\":\"Gopal\",\"CommonCategoryRowId\":1},{\"CommonCategoryAttributeName\":\"Reddy\",\"CommonCategoryRowId\":1},{\"CommonCategoryAttributeName\":\"vinnamala\",\"CommonCategoryRowId\":1}]"
答案 0 :(得分:0)
这里有一个解决类似问题的答案Parse JSON in TSQL 如果在此处引用文章Consuming JSON Strings in SQL Server
使用上面的函数,您可以将JSON解析为表格,然后从那里选择进行插入
SELECT *
INTO #Tmp
FROM dbo.parseJSON(
'[
{"CommonCategoryAttributeName":"Gopal","CommonCategoryRowId":1},
{"CommonCategoryAttributeName":"Reddy","CommonCategoryRowId":1},
{"CommonCategoryAttributeName":"vinnamala","CommonCategoryRowId":1}]"') data
WHERE Object_id is NULL
SELECT a.StringValue, b.StringValue
FROM #Tmp a
LEFT JOIN #Tmp b ON b.Name = 'CommonCategoryAttributeName' AND a.Parent_id = b.parent_id
WHERE a.Name = 'CommonCategoryRowId'
这是结果
希望有所帮助
1 Gopal
1 Reddy
1 vinnamala
答案 1 :(得分:0)
public string PartyID(Stream ABC)//json that i posted
{
DataTable dt = new DataTable();
string response = string.Empty;
try
{
string Json = string.Empty;
StreamReader sr = new StreamReader(ABC);
dynamic param = JsonConvert.DeserializeObject<dynamic>(sr.ReadToEnd());
string CommonCategoryAttributeName= param.CommonCategoryAttributeName;
string CommonCategoryRowId= param.CommonCategoryRowId;
string[] commonCategoryAttributeName= CommonCategoryAttributeName.Split(new char[] { ',' });
DataTable tbl = new DataTable();
tbl.Columns.Add("CommonCategoryAttributeName", typeof(string));
tbl.Columns.Add("CommonCategoryRowId", typeof(long));
for (int i = 0; i < CommonCategoryAttributesRowId.Length; i++)
{
tbl.Rows.Add(CommonCategoryAttributeName[i], commonCategoryRowId);
}
string json = JsonConvert.SerializeObject(tbl, Formatting.None);
json = Regex.Unescape(json);
dt = (DataTable)JsonConvert.DeserializeObject(json.Trim(new Char[] { ' ', '"', '.' }), typeof(DataTable));
SqlParameter[] parameters = { new SqlParameter("@commonAttributes", dt) };
int result = yourclass.ExecuteNonQuery(null, CommandType.StoredProcedure, "commonID", parameters);
}
catch (Exception Ex)
{
}
return response;
}