Home » .Net Framework

Selecting a single value from a returned row

I hope this is the appropriate forum, but I have been struggling with this for the past few days. How do you query a single value in a one row result from an Entity query? 

What I have is about 24 columns that are in the table, I run a query, it always returns only one row, but I have to dynamically choose which column is selected as the result in that row. How can I accomplish this?


3 Answers Found


Answer 1

I have this in my code:


Dim customQuery As ObjectQuery(Of tblSubtestNorm) = From a In db.tblSubtestNorms Where a.ST = tempvalue2 _
                  And a.RS = tempvalue Select a


The above code always returns  a single  row of data. The question is, how do I then dynamically  state that I want to return the value in "X" column? The column  I am returning is always going to be different based on property settings elsewhere.



Answer 2

Hi MarkSA,

If you want to select particular columns, you can use projections in your query and shape your results by picking particular properties rather than entities. If the column  you are returning is always different and you want to choose  the column dynamically, you can use projecting with query  builder methods, something like :

Dim context AsNew NorthwindEntities
Dim colSel AsString = "CompanyName"'Column name you want to select. You can change the name to othersDim customQuery = context.Customers.Where("it.CustomerID = 'VINET'").Select("it." & colSel)

ForEach mm In customQuery

And I think you can also achieve what you want using Dynamic LINQ.

By the way, I am moving this thread to "ADO.NET Entity Framework and LINQ to Entities" forum  for better response.

Best regards,

Alex Liang

MSDN Subscriber Support in Forum

If you have any feedback on our support, please contact msdnmg@microsoft.com


Answer 3

That worked beautifully. Thank you so much for your help on this Alex.

This is what I have

Insertinto ReportDetail( Partcipantid, Reportid) 

selectdistinct ParticipantID , 9 from OpenCredit

      except select ParticipantID, 9 from StoreCredit where Closed = 0

 Issue is that when above select statement returns no row, it seems like no record is entered.

So I want to check record count of select statement and if 0, insert specific row.

This is pseudo code (but it best explains what I am trying to accomplish)

-- insert records in detail table and get teh record count

Insertinto ReportDetail( Partcipantid, Reportid) 

selectdistinct ParticipantID , 9 from OpenCredit

      except select ParticipantID, 9 from StoreCredit where Closed = 0

if @rec_count = 0 -- if there are no records, enter this specific entry

      insertinto ReportDetail( reportid, PartcipantId, createdon)values ( 9,- 1,(getdate() - 1))

Is it even possible?

Another less elegant option is to run the same query twice, once to check record count and if it is +ve then run again the same query for insert.

Please advice. I tried posting before http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/31d5ff0f-45fb-45a9-a385-bd1942763fca but no solution


I have execute sql task and i pass in 2 parameters to the sql statement inside execute sql task. Sometimes the sql statement returns rows and sometimes it doesn't.
when the sql statement returns rows, the rest of the package runs fine. If the sql statement does not return rows, the package fails and the error message is

[Execute SQL Task] Error: An error occurred while assigning a value to variable "varPeriod": "Single Row result set is specified, but no rows were returned.".

what should i do to make sure that even if the sql statement returns nothing, it has to go on?

The execute sql task that i am talking about is inside foreach loop?



New to asp.net and struggling with a problem.

I have two gridviews on same page - If a record is selected in Gridview1, I need to unselect a record (if one is selected) in Gridview2 - and vice-versa.

Can this be done?



I Using this code for delete a row from Grid.

<telerik:GridViewColumn Header="Delete">
							<Button Command="{Binding DeleteCommand, Source={StaticResource vmCriterion}}" CommandParameter="{Binding SelectedRow, Source={StaticResource vmCriterion}}">Delete</Button>                         

But, Imustchoose a Row, Before removing.
Iwantby clickingoneachrowis removed!

please help me.


every row of sql is broken into 14 separate rows in the txt file

so, if sql table has 5 rows, then the txt file should have 5 * 14 + 1

the 1 extra row is at the beginning of the flat file which specifies how many separate groups of 14 rows are present (in this case, 5)

how do i achieve this?



I need to return result of the second select statement if the first select statement returns nothing:

-- First statementSELECT Salesmen.SalesmanID, Salesmen.FullName, 
  Salesmen.AssignedAppointments, Salesmen.Picture, 
  Salesmen ON 
  Appointments.SalesmanID = Salesmen.SalesmanID
WHERE (Appointments.Closed = 1)
ORDERBY Salesmen.AssignedAppointments
-- Second statementSELECT *
FROM Salesmen
ORDERBY AssignedAppointments


I have three tables: Design, Box, Wall.

Design has a column DesignId that is a GUID. It does not allow nulls, is unique, and is the primary key. The identity is set to false for compatibility with Entity Framework v4.

Box has  a column BoxId that is a GUID. It does not allow nulls, is unique, and is the primary key. The identity is set to false as well.

Box also has a column DesignId that is a GUID. It does not allow nulls, is not unique and is not the primary key.

Wall has  a column WallId that is a GUID. It does not allow nulls, is unique, and is the primary key. The identity is set to false as well.

Wall also has a column DesignId that is a GUID. It does not allow nulls, is not unique and is not the primary key.

Wall also has a column BoxId that is a GUID. It does not allow nulls, is not unique and is not the primary key.

Box.DesignId has been set as a ForeignKey relating to Design.DesignId.

Wall.DesignId has been set as a ForeignKey relating to Design.DesignId

Wall.BoxId has been set as a ForeignKey relating to Box.BoxId.


If I execute      SELECT DesignId FROM Design     I see the correct number of rows.

If I execute     SELECT BoxId From Box        I see zero rows.

If I execute     SELECT * FROM Box       I see the correct number of rows and every row has a unique GUID in the BoxId column.



What the cob is going on??? Please help!






I have a query that *needs* to return values to my web page. In most cases it will, but some times there are no rows returned. In that case I would like to return a row of dummy values. Is this possible?

Say I have something like this:

select something, somethingElse from db where somevalue = parameter


If this doesn't return anything, I would like to return something like

select null as something, null as somethingElse

The thing is that it needs to be the same table, so that the web page doesn't detect it.



I want to get only the first result set only if it returns rows.  like, call select statement B only if A returns no rows.  Right now I'm using a union to get everything.


select col1,col2 from tableA where col3=10 and col4=20




select col1,col2 from tableA where col3=10 and col4=0


But if the first select returns rows, I don't need the results of the 2nd.  I tried a case statement or isnull, but that doesn't work with multiple rows. If:

1 1 10 20

1 2 10 20

1 3 10 0

1 4 10 0

I'd want just the first 2 rows if I was looking for 20, but I didn't find the 20, I'd want to look for 0. 



Hi all,

My scenario is this: the application that tracks orders has room for five Order Detail lines per order. The Orders table in the db has OrderID (PK), OrderLine1, UnitPrice1, OrderLine2, UnitPrice2, ..... OrderLine5, UnitPrice 5 etc - all as separate columns, but each order is all on the same row in the table and is identified by OrderID. Each order may have anywhere between 1 and 5 Order Detail lines - i.e there won't alway be five - meaning that often many of the OrderLine & Unit Price columns will be empty.

What I need to do is write a query that returns all OrderIDs and associated Order Details in the table, but with one row per Order Detail (not OrderID), and I only want to return an Order Detail if it exists. I don't want to return a row for OrderDetail2,3,4 & 5 if only OrderDetail1 is completed for that particular OrderID.

So, my attempt so far is:

SET @OrderLine2 = (SELECT O.OrderLine2 FROM Orders as o where o.OrderID = 123456)

IFISNULL(@OrderLine2,'') = ''BEGINSELECT O.OrderID, O.OrderLine1
	FROM Orders AS o
	where o.OrderID = 123456
	FROM Orders AS o
	where o.OrderID = 123456

	FROM Orders AS o
	where o.OrderID = 123456

But this doesn't feel a very elegant way of doing it. Also, this only works for two OrderDetail rows - I've got to get it working for five which I think is going to make it a very long and complicated query!

Does anyone know of a better way to achieve this?

Thanks, Matt


I have 1 detail row 3 different groups in my Report like Group1, Group2 & Group3. If I preview the report the group details are displayed in 3 different lines one by one as follows




But I would like all 4 sections be displayed in a single line like

Details Group1_Name    Group2_Name     Group3_Name

How to do I achieve this SSRS 2008?


this.UIMap.LoginParams.UIUserNameEditText = testContextInstance.DataRow["UserName"].ToString();
this.UIMap.LoginParams.UIPasswordEditPassword = testContextInstance.DataRow["Password"].ToString();

where login method contains action for inserting data into username editbox, password and clicking on the LOGIN button

1. using the above code i m facing one problem - only username is inserted in the editbox (all the iteration for the number of rows present in csv file), but not the password resulting failure of testcase.

2. i want to execute the code for only one data row, whereas file contains 3 data rows.


I have a table that has several columns of comments. Several people enter a row with comments. For each comment column i am tryng to concatenate each columns comments and add it to a second table with the same column headers. SQL Server 2008. Please help.Thanks for your time. I appreciate it.

Table 1










Comment 2

Comment 3

User 2




Comment 2

Comment 3


Table 2









User 1 Comment1, User 2 Comment 1

User 1 Comment2, User 2 Comment 2

User 1 Comment3, User 2 Comment 3


Hi guys,

I'm new to SSIS and trying to design a package that will take a multi-row notes table and concatenate it into a single-row notes table. For example, the source fields may include Customer#, Note#, NoteText, Sequence#. In the current format, a long note may be stored in 2, 3, 4 rows. My SSIS package somehow needs to loop through each row, ordered by Sequence#, and concatenate the NoteText field into a single output field. For example:


Customer# Note# NoteText      Sequence#
--------- ----- --------      ---------
1234   1   Example of a multi 1
1234   1   line note.     2
5555   2   Single line note.  3
6666   3   Example of a multi 4
6666   3   line note that spans5
6666   3   three rows.     6


Needs to output the following:


Customer# Note# NoteText 
--------- ----- --------   
1234   1   Example of a multi line note.
5555   2   Single line note.
6666   3   Example of a multi line note that spans three rows. 


Does anyone know what the best method is to accomplish this? I tried using a Script Task and writing it in VB.NET but I wasn't able to figure out how to access multiple rows of data at once. I don't have much experience writing T-SQL Stored Procedures, but I could learn quickly if this is the best method.

Any suggestions?


Hi All,


I am new to BizTalk development and need some help regarding the BizTalk mappings. I need a way to map multiple rows with same ID to a single output record. ID is just a field in the source message and my source message is a flat file with tab delimated. For example if we have following input message,


ID         PN           Status

DM01      01            Accepted

DM01      02            Accepted

DM02      01            Accepted


   It should map to something like















Note that items with same ID are combined in a parent/child  hierarchy .


I will be very thankful if anyone can help me with this and give some hints. Fyi, I am using BizTalk 2002 and trying to do this with Map Editor.




I am using a queryable set of data from four tables: 

 public IQueryable<Customer> GetCustomer(int id)
        return from c in entities.Customers
               join ca in entities.Customer_Address on c.CustomerID equals ca.CustomerID
               join ce in entities.Customer_Email on c.CustomerID equals ce.CustomerID
               join cp in entities.Customer_Phone on c.CustomerID equals cp.CustomerID
               where c.CustomerID == id
               select c;

The Customers entity can only have one row per customerID but the other tables can have multiple rows.  I know that I can display all of the data rows by using a 'foreach' loop but I only want to display the Customers data one time.  I cannot call this data outside of the 'foreach' loop because the page has to inherit IEnumerable for the multiple rows.  Is there a way to do this along my path or do I need to switch gears?



I have following tables with the sample data.

MatFieldTicket (IPID, EntryID)      TransientKYCMat(EntryID, FieldName,OldValue,NewValue)
IPID      EntryID                          EntryID        FieldName           Oldvalue            Newvalue
111       501                                501              FirstName            ABC                  AAA
111       502                                501              LastName            DEF                   BBB
111       503                                502              LastName            Sanjay               YYY
111       504                                503              FirstName            Ash                    
                                                  504             TrustLine                                      DDD          

I need to select list all records with the following result
EntryId,OldName1,OldName2,NewName1,NewName2 where OldName1 is FirstName,OldName2 is LastName, NewName1 is the new value for FirstName,NewName2 is the new value for LastName and also if the Newvalue of FisrtName field is Empty or NULL then display TrustLine NewValue. So my result would be as follows:

IPID         EntryID       OldName1        OldName2       Newvalue1         NewValue2
111          501             ABC                 DEF                AAA                  BBB
111          502                                    Sanjay                                    YYY
111          503             Ash                                        DDD                

Please help me out in writing a select statement. If required any other information let me know.




I have a table that contains a package name, a datetype column and a date column.

I need a query that will return a table that contains two particular date types in the same row e.g.

PackageName, Date1, Date 2

I tried a UNION query but it gave me separate rows for the two date types. I need them in one row as I have to feed them into another query that will compare these two dates and take some other actions.



Hi all,

Why in the code below I am able to list all rows and display the field 'stepID' but I am not able to concatenate them all in the variable @stepIds?

declare @date asdatetimeset @date = '2010-09-20 23:01:20:000'declare @instance asuniqueidentifierset @instance = '04658F34-CBF1-4CCD-A683-F23BDB669D35'Declare @CrLf char(2)
  Set @CrLf = Char(13) + Char(10)
	Declare @stepIds varchar(8000)
	Set @stepIds = ''Select--@stepIds = @stepIds + ' - Step: ' + CONVERT(varchar(4), stepID)
		(instanceID = @instance) and ([timeStamp] > @date)
Thank you!

Hello All,

I have been having a problem accessing all of the rows in a C1FlexGrid. For example I have a grid which has three rows, and when I use

UITestControlCollection tableRows = tableToSearch.Rows;

tableRows will only contain two rows, Row 2 and Row 3, but not the first row. Has anyone else had this kind of issue? I can access Row 1 via other methods, as found in


but I am concerned that I will need to be able to access the top row using the .Rows collection.


Best regards,

Elliot Meisinger


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure