我对DB(SQL Server)中的数据有疑问。我的数据库列同时包含关系数据和JSON类型数据。很少有json列被错误地填充。需要C#代码来解决此问题。
示例考虑我的表名是 dbo.Organization。
列是
orgReferenceNumber,organizationsAssociation。
organizationAssociation是一个JSON类型列。下面是正在填充的数据。
[{"associatedToId":null,"associationType":null,"isObsolete":null}
由于上述json中所有属性均为null,因此预期输出为[]
需要C#代码,该代码循环访问特定列的所有记录,并检查JSON的所有属性是否为空或NULL。如果为空/ NULL,则将其覆盖为[]。
更新:添加代码SSIS C#代码脚本组件。在我所面对的问题之下。 object val = objProp.GetValue(value, null);
System.Reflection.TargetParameterCountException HResult = 0x8002000E
Message =参数计数不匹配。
#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reflection;
using Newtonsoft.Json.Linq;
#endregion
namespace ST_cecd1942b9e44e899c1e9e560039f2c3
{
public static class ExtensionMethods
{
public static bool StringPropertiesEmpty(this object value)
{
foreach (PropertyInfo objProp in value.GetType().GetProperties())
{
if (objProp.CanRead)
{
object val = objProp.GetValue(value, null);
if (val.GetType() == typeof(string))
{
if (val == "" || val == null)
{
return true;
}
}
}
}
return false;
}
}
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
System.Data.SqlClient.SqlConnection connection;
ConnectionManager strcon = Dts.Connections["UCP_Q"];
connection = (System.Data.SqlClient.SqlConnection)strcon.AcquireConnection(null);
string sql = "select organisationReferenceNumber,organizationAssociation from dbo.organisation";
SqlCommand cmd = new SqlCommand(sql, connection);
SqlDataReader reader = cmd.ExecuteReader();
long CRN;
String Json;
if (reader.HasRows)
{
while (reader.Read())
{
CRN = Convert.ToInt64(reader.GetValue(0));
Json = Convert.ToString(reader.GetValue(1));
// JObject jObj = JObject.Parse(Json);
bool checkNull = ExtensionMethods.StringPropertiesEmpty(Json.Replace("\"", ""));
//if(checkNull=='true')
//{
//}
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}