How can I get SQL result into a STRING variable?

how to store query result in variable in c#
c# execute sql query and get result
read one row from database c#
c# sql query results to list
c# sql query results to array
how to retrieve value from database in c#
sql single result
c# get value from sql table

I'm trying to get the SQL result in a C# string variable or string array. Is it possible? Do I need to use SqlDataReader in some way? I'm very new to C# functions and all, used to work in PHP, so please give a working example if you can (If relevant I can already connect and access the database, insert and select.. I just don't know how to store the result in a string variable).

This isn't the single greatest example in history, as if you don't return any rows from the database you'll end up with an exception, but if you want to use a stored procedure from the database, rather than running a SELECT statement straight from your code, then this will allow you to return a string:

public string StringFromDatabase()
    {
        SqlConnection connection = null;

        try
        {
            var dataSet = new DataSet();

            connection = new SqlConnection("Your Connection String Goes Here");
            connection.Open();

            var command = new SqlCommand("Your Stored Procedure Name Goes Here", connection)
            {
                CommandType = CommandType.StoredProcedure
            };

            var dataAdapter = new SqlDataAdapter { SelectCommand = command };

            dataAdapter.Fill(dataSet);

            return dataSet.Tables[0].Rows[0]["Item"].ToString();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
        finally
        {
            if (connection != null)
            {
                connection.Close();
            }
        }
    }

It can definitely be improved, but it would give you a starting point to work from if you want to go down a stored procedure route.

Obtaining a Single Value from a Database, For example, you may want to return the result of an aggregate function string connString) { Int32 newProdID = 0; string sql = "INSERT INTO  I'm trying to get the SQL result in a C# string variable or string array. Is it possible? Do I need to use SqlDataReader in some way? I'm very new to C# functions and all, used to work in PHP, so please give a working example if you can (If relevant I can already connect and access the database, insert and select.. I just don't know how to store the result in a string variable).

Try This:

SqlConnection con=new SqlConnection("/*connection string*/");               
SqlCommand SelectCommand = new SqlCommand("SELECT email FROM table1", con);
SqlDataReader myreader;
con.Open();

myreader = SelectCommand.ExecuteReader();

List<String> lstEmails=new List<String>();
while (myreader.Read())
 {
    lstEmails.Add(myreader[0].ToString());
    //strValue=myreader["email"].ToString();
    //strValue=myreader.GetString(0);
 }
con.Close();

accessing the Emails from list lstEmails[0]->first email lstEmails[1]->second email

...etc.,

[Solved] sql result saved into c# variable, Try: Hide Copy Code. public void autono() { int count; SqlDataReader reader = null; string connectionString = ConfigurationManager. Concatenates two strings and sets the string to the result of the operation. For example, if a variable @x equals 'Adventure', then @x += 'Works' takes the original value of @x, adds 'Works' to the string, and sets @x to that new value 'AdventureWorks'.

You could use an SQL Data Reader:

string sql = "SELECT email FROM Table WHERE Field = @Parameter";
string variable;
using (var connection = new SqlConnection("Your Connection String"))
using (var command = new SqlCommand(sql, connection))
{
    command.Parameters.AddWithValue("@Parameter", someValue);
    connection.Open();
    using (var reader = command.ExecuteReader())
    {
        //Check the reader has data:
        if (reader.Read())
        {
            variable = reader.GetString(reader.GetOrdinal("Column"));
        }
        // If you need to use all rows returned use a loop:
        while (reader.Read())
        {
            // Do something
        }
    }
}

Or you could use SqlCommand.ExecuteScalar()

string sql = "SELECT email FROM Table WHERE Field = @Parameter";
string variable;
using (var connection = new SqlConnection("Your Connection String"))
using (var command = new SqlCommand(sql, connection))
{
    command.Parameters.AddWithValue("@Parameter", someValue);
    connection.Open();
    variable = (string)command.ExecuteScalar();
}

Receiving an SQL query result in a variable, End SQL ALERT("The Video Library contains "+String($AllMovies)+" movies"). As you can see, you can receive the result of the query in a variable (in our case  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.

This May help you For MySQL

MySqlDataReader reader = mycommand.ExecuteReader();
while (reader.Read())
{
  TextBox2.Text = reader.ToString();
}

For SQL

using (SqlCommand command = new SqlCommand("*SELECT QUERY HERE*", connection))
{
//
// Invoke ExecuteReader method.
//
SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        TextBox2.Text = reader.GetString(0);
    }
}

Get Sql Query Results Into A String Variable, Hi Guys, I'm trying to get the results of an sql query into a variable, I can connect to the db and run the query, i can sucessfully print the results to  I want to execute a select statement and put the result of it (which is only 1 record with 1 value) in a variable. Why can't you just store the value of the record with myVar = rst!nameOfValueField ? – Roland Jun 2 '14 at 10:32. Simply have your Function return the value from the Recordset: what does the ! in rst!rubrieknaam do?

Try this:

public string SaveStringSQL(string pQuery, string ConnectionString)
{
    var connection = new Conexao(ConnectionString);
    connection.Open();

    SqlCommand command = new SqlCommand(pQuery, connection.Connection);
    var SavedString = (string)command.ExecuteScalar();

    connection.Close();

    return SavedString;
}

The ExecuteScalar function saves whatever type of data there is on your database - you just have to specify it.

Keep in mind that it can only save one line at a time.

An Introduction to SQL Server Table Variables By Examples, This tutorial shows you how to use the SQL Server table variables which offer some Using table variables in a stored procedure results in fewer recompilations than CREATE OR ALTER FUNCTION udfSplit( @string VARCHAR(MAX),  DECLARE @tab AS TABLE (col VARCHAR(10), colu2 varchar(10)) INSERT into @tab EXECUTE sp_executesql N'SELECT 1 as col1, 2 as col2 union all SELECT 1 as col1, 2 as col2 union all SELECT 1 as col1, 2 as col2' SELECT * FROM @tab. improve this answer. edited Oct 12 '11 at 13:34. 135 silver badges. 235 bronze badges. answered Apr 7 '11 at 8:23.

SQL Server Concat with +, The + operator allows you to add two or more strings together. Note: See also the CONCAT() and CONCAT_WS() functions. Syntax. string1 + string2 + string_n  The number of rows here is incosequential, it doesn't matter if there are 3 rows or 300, this will create a single comma separates string for all of the rows and return that string out. However, this will leave a trailing comma in the string with no value behind it. So the below section trims the last character off of the string so that it can be returned without an extra comma.

SQL Server CONCAT() Function, The CONCAT() function adds two or more strings together. Works in: SQL Server (starting with 2012), Azure SQL Database, Azure SQL Data Warehouse,  You are working as C# developer, You are writing C# Program in which you need to execute SQL Query that returns you single value, you need to execute query and save the result into variable. In below script we will run two queries and save results into integer type and string type variables.

C# To Hold SQL Results, How via C# can I query a SQL table for carName and store all results in a C# string Array variable? So something like: (I know this isn't actual 

Comments
  • Is it a SELECT statement for example? please give a working example is not a good way to ask by the way. Please read FAQ and How to Ask
  • Yes. It's "SELECT email FROM table1"
  • Seems to work ok, but the results are concatenated. (strValue[0] returns first letter not first value) Guess I need a separator or something?
  • @Vantalk: see my edited answer with list lstEmails for adding all Emails
  • I tried the edited version and printing with Console.Write(lstEmails) but it wont return any values and just repeats: System.Collections.Generic.List`1[System.String]