C# - using TableAdapter to return a single value from stored procedure returns null

SEA picture SEA · Mar 23, 2011 · Viewed 7.6k times · Source

I do not understand but my stored procedure which I added to table adapter only returns null value. It is supposed to return a simple integer value. In the preview I had with data set desinger, I could clearly get the integer value that I wanted. But for some reason I cannot get the value from my codes.

I followed the instruction of MSDN library: http://msdn.microsoft.com/en-us/library/37hwc7kt(VS.80).aspx

My code for c# is:

humansDataSetTableAdapters.ProfilesTableAdapter tableAdapter 
= new humansDataSetTableAdapters.ProfilesTableAdapter(); 

int returnValue = (int)tableAdapter.getSample();

Console.Write(returnValue);

My code for stored procedure getSample is:

DECLARE @r int
SET @r = 7
RETURN @r

Can anybody let me know how I can solve this problem?? Any help will be appreciated!

Answer

Nikki9696 picture Nikki9696 · Mar 23, 2011

Scalar expects a result, not a return. Be definition, it looks for the first column, first row. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

Try

DECLARE @r int
SET @r = 7
SELECT @r