I am trying to insert multiple rows of JSON output into SQL using C#.
This is C# code that I have:
string connString = @"MultipleActiveResultSets=true;Data Source=db;USER id=yy;Password=xxx;Initial Catalog=dim";
string sprocname = "InsertPerfCounterData2";
string paramName = "@json";
string paramValue = SayHello(logger);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sprocname, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(paramName, paramValue));
cmd.ExecuteReader();
}
}
I am getting an Exception Unhandled error at cmd.ExecuteReader();
System.Data.SqlClient.SqlException: 'JSON text is not properly formatted. Unexpected character ']' is found at position 501.'
How do I modify C# code to make it work?
This is the stored procedure code:
CREATE PROCEDURE [dbo].[InsertPerfCounterData2]
@json NVARCHAR(max)
AS
BEGIN
INSERT INTO dbo.PerfCounter3 ([RECORDNO], [BATCH_DATE])
SELECT
GLD.RECORDNO, GLD.BATCH_DATE
FROM
OPENJSON(CONCAT('[',@JSON,']')) OJ
CROSS APPLY
OPENJSON(OJ.[value],'$.GLDETAIL')
WITH (RECORDNO varchar(30),
BATCH_DATE date) GLD;
END
This is example of JSON input:
{
"GLDETAIL": {
"RECORDNO": "264378-1756289-919567--accrual",
"BATCH_DATE": "02/01/2022"
}
},
{
"GLDETAIL": {
"RECORDNO": "264378-1756290-919568--accrual",
"BATCH_DATE": "02/01/2022"
}
},
Update (5/5/2022):
I am trying to declare "result.Data" (based on @Charlieface's answer on the bottom).
If the result of resultJson is like this, and data type is String:
resultJson =
"[{\"GLDETAIL\":{\"RECORDNO\":\"264378-1756289-919567--
accrual\",\"BATCH_DATE\":\"02/01/2022\"}},{\"GLDETAIL\":
{\"RECORDNO\":\"264378-1756290-919568--
accrual\",\"BATCH_DATE\":\"02/01/2022\"}}]"
How do I apply into "result.Data" properly?
foreach (var r in result.Data)
table.Rows.Add(r.RECORDNO, r.BATCH_DATE);

SqlBulkCopy. Alsocmd.ExecuteReader();is wrong here as there is no output, you should usecmd.ExecuteNonQuery();