RESOLVED..
This has been resolved as I was making a stupid mistake. I didn’t initialize the string builder
StringBuilder sb = new StringBuilder();
I am using the following CTE query in my website to fetch data using c#. But it is giving an error in the if Statement inside for loop
ERROR MESSAGE
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
String strSqlCTE;
strSqlCTE= " DECLARE @PageId int ";
strSqlCTE += " SET @PageId =" + pageid + "; ";
strSqlCTE += " WITH RecursiveTable (PageId, PageName, PageInternalLink, PageInternalLinkUrl, PageInheritance, Level) ";
strSqlCTE += " AS(SELECT tt.PageId, tt.PageName, tt.PageInternalLink, tt.PageInternalLinkUrl, tt.PageInheritance, 0 AS Level ";
strSqlCTE += " FROM pg_Pages AS tt WHERE PageId = @PageId ";
strSqlCTE += " UNION ALL ";
strSqlCTE += " SELECT tt.PageId, tt.PageName, tt.PageInternalLink, tt.PageInternalLinkUrl, tt.PageInheritance, Level + 1 ";
strSqlCTE += " FROM pg_Pages AS tt ";
strSqlCTE += " INNER JOIN RecursiveTable rt ON rt.PageInheritance = tt.PageId ) ";
strSqlCTE += " SELECT * FROM RecursiveTable ORDER BY Level DESC ";
DataSet dsBC = new DataSet();
dsBC = DataProvider.Connect_Select(strSqlCTE);
if (dsBC.Tables[0].Rows.Count > 0)
{
int RowCount = dsBC.Tables[0].Rows.Count;
StringBuilder sb = null;
for ( int i = 0; i <= RowCount; i++)
{
if (i == RowCount)
{
sb.Append("<a href='" + dsBC.Tables[0].Rows[0]["PageInternalLinkUrl"].ToString() + "'>" + dsBC.Tables[0].Rows[0]["PageName"].ToString().ToUpper() + "</a>");
}
else
{
sb.Append("<a href='" + dsBC.Tables[0].Rows[0]["PageInternalLinkUrl"].ToString() + "'></a> ● ");
}
}
ltrBreadCrumb.Text = sb.ToString();
}
My CTE query is is working and below is the actual query
DECLARE @PageId int
SET @PageId = 31;
WITH RecursiveTable (PageId, PageName, PageInternalLink, PageInternalLinkUrl, PageInheritance, Level)
AS(
--Anchor
SELECT tt.PageId, tt.PageName, tt.PageInternalLink, tt.PageInternalLinkUrl, tt.PageInheritance, 0 AS Level
FROM pg_Pages AS tt
WHERE PageId = @PageId
UNION ALL
--Recursion
SELECT tt.PageId, tt.PageName , tt.PageInternalLink, tt.PageInternalLinkUrl, tt.PageInheritance, Level + 1
FROM pg_Pages AS tt
INNER JOIN RecursiveTable rt ON rt.PageInheritance = tt.PageId
)
SELECT * FROM RecursiveTable ORDER BY Level DESC
This works good on when run in the Management studio but following statement generate error
sb.Append("<a href='" + dsBC.Tables[0].Rows[0]["PageInternalLinkUrl"].ToString() + "'></a> ● ");
dsBC.Tables[0].Rows.Count statement return correct row numbers based on the input. Problems seems to be in the as it cant recognize column name which is present in the CTE query.
Am I am doing something wrong please correct me about the problem.
This has been resolved as I was making a stupid mistake. I missed to initialize string builder