I'm trying to consume a rest/json get api via CLR stored procedure. My problem is that i'm getting only one(last) record.
Here is my code:
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void FrtApiJsonGet ()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("some site");
var byteArray = Encoding.ASCII.GetBytes("login:password");
request.Method = "GET";
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " +
Convert.ToBase64String(byteArray));
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream receiveStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(receiveStream,
Encoding.UTF8))
{
string strContent = readStream.ReadToEnd();
string value1 = string.Empty;
string value2 = string.Empty;
string value3 = string.Empty;
string value4 = string.Empty;
SqlPipe pipe = SqlContext.Pipe;
SqlMetaData[] cols = new SqlMetaData[4];
cols[0] = new SqlMetaData("value1", SqlDbType.NVarChar, 50);
cols[1] = new SqlMetaData("value2", SqlDbType.NVarChar, 50);
cols[2] = new SqlMetaData("value3", SqlDbType.NVarChar, 50);
cols[3] = new SqlMetaData("value4", SqlDbType.NVarChar, 50);
SqlDataRecord record = new SqlDataRecord(cols);
pipe.SendResultsStart(record);
var strArray = strContent.Split(new string[] { "{,}" },
StringSplitOptions.None);
foreach(var str in strArray)
{
var subArray = str.Split(',');
foreach (var substr in subArray)
{
if (substr.Contains("\"value1\""))
value1 = substr.Split('\"')[3];
if (substr.Contains("\"value2\""))
callKey = substr.Split('\"')[3];
if (substr.Contains("\"value3\""))
callPhase = substr.Split('\"')[3];
if (substr.Contains("\"value4\""))
callresult = substr.Split('\"')[3];
}
record.SetSqlString(0, new SqlString(value1));
record.SetSqlString(1, new SqlString(value2));
record.SetSqlString(2, new SqlString(value3));
record.SetSqlString(3, new SqlString(value4));
pipe.SendResultsRow(record);
value1 = string.Empty;
value2 = string.Empty;
value3 = string.Empty;
value4 = string.Empty;
}
pipe.SendResultsEnd();
}
}
}
}
}
I know that the api works and if i try the same code without the sqlpipe in console app it returns a list of values...Yet when used as clr stored procedure i get only one(last) record.
pipe.Send(str);just before thevar subArray = str.Split(',');so you can see what should be each row.{,}? perhaps there is an encoding issue (doubtful, but have to ask). Perhaps there is a "hidden" character in the incoming data that makes it not match exactly to{,}? I will post an answer since the overall issue has been identified.FrtApiJsonGetbut without theSqlPipe,SqlContextand all that stuff. You just loopstrArrayand see what you get.