Reputation: 177
I have an SQL Query which is returned to a datatable dtStories (c#).
with records as (select row_number() over (order by pages.createdate desc)as 'row',
field1, field2...etc. from records where row between 1 and 7
(There are other instances where i'll need "nth" row or between x & y rows, hence I'm not using a simple select top 7 query.)
I was trying to do slightly different things based on which row it was, so I was querying row[0] thinking this would have the row number in. But, checking the returns in my SQL Server, it actually only returns field 1, field 2... etc which is obviously why my
foreach (Datarow row in dtStories)
{
if (row[0].ToString() == "1")
{
...
}
}
doesn't work.
Is there a way to either make sure row is returned as part of the SQLQuery into the DataTable, or using c# just access row1, row2 etc. of the table?
Upvotes: 1
Views: 707
Reputation: 70513
you don't show the whole select statement so it is IMPOSSIBLE to know what you are actually doing. We can tell this because the (
and )
don't match.
I expect your code (indented to make clear) looks something like this:
with records as
(
select row_number() over (order by pages.createdate desc)as 'row',
field1, field2 -- ...
from original_table
)
select
field1, field2 -- ...
from records
where row between 1 and 7
now it should be clear... to include the row column you need it in the 2nd select list (outside the CTE)
with records as
(
select row_number() over (order by pages.createdate desc)as 'row',
field1, field2 -- ...
from original_table
)
select row, -- here!
field1, field2 -- ...
from records
where row between 1 and 7
Upvotes: 3
Reputation: 48177
dont understand if your with records ..
is sql server or c# code. Doesnt look sql because doesnt have closing parenthesis and doesnt have select.
WITH
is call CTE, and CTE are temporaly created in memory.
You want something like
with records as
(
select row_number() over ....
)
SELECT *
FROM records
Upvotes: 0