Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show value printed by sql query in message box

I want to print a value that is returned by SQL Server.

If NOT Exists(SELECT * FROM ItemList WHERE ItemName='txtItemNama') 
   BEGIN   
    INSERT INTO ItemList (ItemName) VALUES('txtItemNamea')  
   END 
ELSE  
   BEGIN 
    Print 'Duplicate' 
   END

This query will either return me either number of rows affected or Duplicate

I want to use this Duplicate in C# in MessageBox.Show()

string query1 = "If NOT Exists(SELECT * FROM ItemList WHERE ItemName='txtItemName') BEGIN  INSERT INTO ItemList (ItemName) VALUES('txtItemName')  END ELSE  BEGIN Print 'Duplicate' END";
            SqlCommand cmd = new SqlCommand(query1, conn);
            SqlDataReader dr;
            conn.Open();
            dr=cmd.ExecuteReader();
            conn.Close();
MessageBox.Show(dr);

I don't know how to use dr to do this. Please help me out to print Duplicate here

MessageBox.Show(dr);

What do I need to do here?

like image 780
Shantanu Gupta Avatar asked Jan 08 '10 12:01

Shantanu Gupta


People also ask

How do I get SQL query output in a text file?

However, if you prefer to export SQL query results to a text file via a Wizard, we have your back. To begin with, right-click the database in SQL Server Management Studio or SSMS. Then, select the Import or Export data option and head to Export Data under Tasks. Next, open the SQL Server Import and Export wizard.

How do you display text in SQL?

Note: You can use literal string (enclosed in single or double quotation mark) just like we use a column name in the SELECT statement. If you use the literal string with a column then it will be displayed in every row of the query results.


1 Answers

a few years late but you should be able to retrieve print/info text (like originally asked) by attaching an eventhandler to the InfoMessage event on the SqlConnection object -

But only do this if you can't (for some reason) use the alternatives mentioned in this thread.

static void Main(string[] args)
{
    using (SqlConnection connection = new SqlConnection(@"someconnectionstring"))
    {
        connection.Open();
        using(SqlCommand command = new SqlCommand("test", connection))
        {
            connection.InfoMessage += new SqlInfoMessageEventHandler(connection_InfoMessage);
            using (SqlDataAdapter adapter = new SqlDataAdapter(command))
            {
                DataTable dt = new DataTable();
                adapter.Fill(dt); // Do something with DataTable
            }
        }
    }
}

static void connection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
    // e contains info message etc
}
like image 92
cstruter Avatar answered Nov 15 '22 18:11

cstruter