Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get SQL result saved into a C# variable?

Tags:

c#

sql

I have troubles finding out how to save an SQL result into a String or whatever type the result returns.

My SQL query is:

SELECT SUM(Length) FROM tbl_test WHERE TITLE LIKE 't%'

Here I need a function that sums up the length of all data-rows where title begins with the letter "T", when executing the query in MS-SQL it returns "188.99" (the SQL type is decimal)

My question is, how do I get to save that value into a C# variable? The query always returns ONE row with the particular value, which I want to save into a variable. I have a C# function to execute the query, I just need the value from that row, 188.99, to be saved into a variable. Any suggestions are cool, no matter if I the result is saved into a decimal variable or string.

like image 971
beginner2k10 Avatar asked Feb 18 '11 18:02

beginner2k10


People also ask

How do I save a SQL query result to a file?

On the Query menu, point to Results to, and then click Results to File. Enter and then execute the SQL statement. In the Save Results dialog box, specify the following settings: Save In: Select a directory in which to save the file.

How do I display SQL results?

You have the option of displaying your query results on the Run SQL window, as opposed to Data Display windows. To do this, go to View > Data Grid (Ctrl+G). Once you have selected this option, a panel will appear at the bottom of the window - your query results will be displayed there.


1 Answers

Try calling .ExecuteScalar() on the SqlCommand that you prepare for it. EG:

SqlConnection connection = new SqlConnection(myConnectionString);
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT SUM(Length) FROM tbl_test WHERE TITLE LIKE 't%'";

int result = ((int)cmd.ExecuteScalar());
connection.Close();

You can open and close SqlConnections as much as you like (it's SoP to open and close each time you do an operation, or series of ops in the same method) because .Net will not really close the connection for real, it'll "soft close" it and plop the live connection back into a Connection Pool for recycling later.

like image 145
Chris Wenham Avatar answered Sep 22 '22 06:09

Chris Wenham