C# 将包含重复列的json数据插入sql server
我有一个JSON数据,其中包含重复的列,其中包含需要一次插入到sql Server中的不同数据。此处CommonCategoryRowId相同,CommonCategoryAttributeName将更改 下面是JSON数据的示例C# 将包含重复列的json数据插入sql server,c#,sql-server,json,C#,Sql Server,Json,我有一个JSON数据,其中包含重复的列,其中包含需要一次插入到sql Server中的不同数据。此处CommonCategoryRowId相同,CommonCategoryAttributeName将更改 下面是JSON数据的示例 "[{\"CommonCategoryAttributeName\":\"Gopal\",\"CommonCategoryRowId\":1},{\"CommonCategoryAttributeName\":\"Reddy\",\"CommonCategoryRow
"[{\"CommonCategoryAttributeName\":\"Gopal\",\"CommonCategoryRowId\":1},{\"CommonCategoryAttributeName\":\"Reddy\",\"CommonCategoryRowId\":1},{\"CommonCategoryAttributeName\":\"vinnamala\",\"CommonCategoryRowId\":1}]"
这里有一个类似的答案 如果这里指的是一篇文章 使用上面的函数,您可以将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
publicstringpartyid(streamabc)//我发布的json
{
DataTable dt=新的DataTable();
字符串响应=string.Empty;
尝试
{
string Json=string.Empty;
StreamReader sr=新StreamReader(ABC);
dynamic param=JsonConvert.DeserializeObject(sr.ReadToEnd());
字符串CommonCategoryAttributeName=param.CommonCategoryAttributeName;
字符串CommonCategoryRowId=param.CommonCategoryRowId;
字符串[]commonCategoryAttributeName=commonCategoryAttributeName.Split(新字符[]{',});
DataTable tbl=新的DataTable();
tbl.Columns.Add(“CommonCategoryAttributeName”,typeof(string));
添加(“CommonCategoryRowId”,typeof(long));
for(int i=0;i
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;
}