开发者

Most efficient way to return AND USE a single row query from SQL Server?

开发者 https://www.devze.com 2023-01-27 13:44 出处:网络
I am using c# and SQL Server to get data from the d开发者_Go百科atabase and populate a few labels on a page on pageload. The information comes from a SQL view which returns a whole bunch of informatio

I am using c# and SQL Server to get data from the d开发者_Go百科atabase and populate a few labels on a page on pageload. The information comes from a SQL view which returns a whole bunch of information in a single row. eg:

SELECT 'car' AS product, 12 As daysUntilEOM, '2010-01-01' AS LastHoliday, 23.7 AS Length

There will always be only 1 row returned

The rest of my project is using LINQ and I originally started going down that path, but what is the point of creating an object that I'm only going to use once off for this, assigning all the values into the object as key-value pairs, and then reassigning them out to the label texts? Seems a lot of pointless coding.

Using a datareader also seems to have the same problem.

The simplest solution (ie least code) I can see is to use a dataAdapter to fill a dataset and pass the dataset back from the DAL to the page and then do the assigning straight to the labels. But for a single row of data this seems to be like using a truck to carry a single tomato.

Is there something like ExecuteScalar that returns a whole row instead of just the first column? Or should the ease of coding the DataAdapter just be enough and I should stop worrying about overhead?

Thanks!


You should call ExecuteReader and pass the CommandBehavior.SingleRow flag.

To avoid coupling, you can convert the DataReader into a dictionary, like this:

return Enumerable.Range(0, reader.FieldCount)
                 .ToDictionary(reader.GetName, reader.GetValue);


ExecuteScalar returns a scalar value, not the row. DataAdapter with a command object (possibly also feeding a parameter to a stored proc rather than executing the sql statement) will be fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消