Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. SQL query in c#

SQL query in c#

Scheduled Pinned Locked Moved C#
databasequestioncsharpsql-serversysadmin
11 Posts 4 Posters 12 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Y Yevgeny Efter

    Hello! I am writing an application that works with a SQL Server DB, and what I need is to send some info to the DB, and get a true / false answer from the DB. I was working always with SQLDataAdapter, but I don't need a SELECT query, but actually an answer (like return in c#). How can I do it in C#, and what kind of query should it be? Thanks in advance!

    G Offline
    G Offline
    Giorgi Dalakishvili
    wrote on last edited by
    #2

    You can use SqlCommand object to execute any sql command you wish.

    Giorgi Dalakishvili #region signature my articles #endregion

    Y 1 Reply Last reply
    0
    • G Giorgi Dalakishvili

      You can use SqlCommand object to execute any sql command you wish.

      Giorgi Dalakishvili #region signature my articles #endregion

      Y Offline
      Y Offline
      Yevgeny Efter
      wrote on last edited by
      #3

      But, can I get a return value from the DB using SqlCommand?

      G 1 Reply Last reply
      0
      • Y Yevgeny Efter

        But, can I get a return value from the DB using SqlCommand?

        G Offline
        G Offline
        Giorgi Dalakishvili
        wrote on last edited by
        #4

        Yes, you can. You can use ExecuteScalar method or by using output parameters. What command are you trying to run?

        Giorgi Dalakishvili #region signature my articles #endregion

        Y 1 Reply Last reply
        0
        • G Giorgi Dalakishvili

          Yes, you can. You can use ExecuteScalar method or by using output parameters. What command are you trying to run?

          Giorgi Dalakishvili #region signature my articles #endregion

          Y Offline
          Y Offline
          Yevgeny Efter
          wrote on last edited by
          #5

          I don't know yet, but I know that depending on some data in the db, it should return true or false.

          L 1 Reply Last reply
          0
          • Y Yevgeny Efter

            I don't know yet, but I know that depending on some data in the db, it should return true or false.

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #6

            Then just use ExecuteScalar

            Y 1 Reply Last reply
            0
            • L Lost User

              Then just use ExecuteScalar

              Y Offline
              Y Offline
              Yevgeny Efter
              wrote on last edited by
              #7

              Thanks! I hope I will manage with returning the value in SQL. Thanks again!

              L 1 Reply Last reply
              0
              • Y Yevgeny Efter

                Thanks! I hope I will manage with returning the value in SQL. Thanks again!

                L Offline
                L Offline
                Luis Alonso Ramos
                wrote on last edited by
                #8

                It's not so hard, but it depends on your query. Is it a regular query or a stored procedure? if it is a sotred procedure, do you use output parameters or a regular return value. Here is some sample code:

                using(SqlConnection conn = new SqlConnection(connString))
                {
                    conn.Open();
                 
                    //
                    // Regular query - returns a bit value from a table
                    //
                 
                    string sql = "SELECT BitColumn FROM Table WHERE Name = 'Luis'";
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    bool result = Convert.ToBoolean(cmd.ExecuteScalar());
                 
                    //
                    // Stored procedure - returns bit value in output parameter and in return value
                    //
                 
                    cmd = new SqlCommand("sp_Test", conn);
                    cmd.Parameters.Add("@BoolVal", SqlDbType.Boolean).Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("RetVal", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    cmd.ExecuteNonQuery();
                
                    int result1 = Convert.ToInt32(cmd.Parameters["RetVal"].Value);
                    bool result2 = Convert.ToBoolean(cmd.Parameters["@BoolVal"].Value);
                }
                

                For the second example, you will need a stored procedure like this:

                CREATE PROCEDURE sp_Test (@BoolVal bit OUT) AS
                BEGIN
                    -- Return in output parameter
                    SELECT @BoolVal = BitColumn FROM Table WHERE NAME = 'Luis';
                 
                    -- Return value of the stored procedure
                    IF @BoolVal IS NULL
                        RETURN 0
                    ELSE
                        RETURN 1
                END
                

                When you execute a query, it returns a resultset (a table with data). A stored procedure that SELECTs something and doesn't get it into a variable is returning a resultset. ExecuteReader and data adapters get the whole resultset, but ExecuteScalar gets the data in the first column of the first row of the first table (useful for returning one value). The stored procedure example calls ExecuteNonQuery because no resultset is returned. Output values are either an output parameter or the return value. You access both through the Commands collection of the SqlCommand object. I hope this helps!

                Luis Alonso Ramos Intelectix Chihuahua, Mexico

                My Blog!

                Y 1 Reply Last reply
                0
                • L Luis Alonso Ramos

                  It's not so hard, but it depends on your query. Is it a regular query or a stored procedure? if it is a sotred procedure, do you use output parameters or a regular return value. Here is some sample code:

                  using(SqlConnection conn = new SqlConnection(connString))
                  {
                      conn.Open();
                   
                      //
                      // Regular query - returns a bit value from a table
                      //
                   
                      string sql = "SELECT BitColumn FROM Table WHERE Name = 'Luis'";
                      SqlCommand cmd = new SqlCommand(sql, conn);
                      bool result = Convert.ToBoolean(cmd.ExecuteScalar());
                   
                      //
                      // Stored procedure - returns bit value in output parameter and in return value
                      //
                   
                      cmd = new SqlCommand("sp_Test", conn);
                      cmd.Parameters.Add("@BoolVal", SqlDbType.Boolean).Direction = ParameterDirection.Output;
                      cmd.Parameters.Add("RetVal", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                      cmd.ExecuteNonQuery();
                  
                      int result1 = Convert.ToInt32(cmd.Parameters["RetVal"].Value);
                      bool result2 = Convert.ToBoolean(cmd.Parameters["@BoolVal"].Value);
                  }
                  

                  For the second example, you will need a stored procedure like this:

                  CREATE PROCEDURE sp_Test (@BoolVal bit OUT) AS
                  BEGIN
                      -- Return in output parameter
                      SELECT @BoolVal = BitColumn FROM Table WHERE NAME = 'Luis';
                   
                      -- Return value of the stored procedure
                      IF @BoolVal IS NULL
                          RETURN 0
                      ELSE
                          RETURN 1
                  END
                  

                  When you execute a query, it returns a resultset (a table with data). A stored procedure that SELECTs something and doesn't get it into a variable is returning a resultset. ExecuteReader and data adapters get the whole resultset, but ExecuteScalar gets the data in the first column of the first row of the first table (useful for returning one value). The stored procedure example calls ExecuteNonQuery because no resultset is returned. Output values are either an output parameter or the return value. You access both through the Commands collection of the SqlCommand object. I hope this helps!

                  Luis Alonso Ramos Intelectix Chihuahua, Mexico

                  My Blog!

                  Y Offline
                  Y Offline
                  Yevgeny Efter
                  wrote on last edited by
                  #9

                  Thank you very much! Just one more question: If I decide to write a stored procedure, where do I store it? When you write "cmd = new SqlCommand("sp_Test", conn);", how will SQL Server know what "sp_Test" is?

                  Have a nice day!

                  L 1 Reply Last reply
                  0
                  • Y Yevgeny Efter

                    Thank you very much! Just one more question: If I decide to write a stored procedure, where do I store it? When you write "cmd = new SqlCommand("sp_Test", conn);", how will SQL Server know what "sp_Test" is?

                    Have a nice day!

                    L Offline
                    L Offline
                    Luis Alonso Ramos
                    wrote on last edited by
                    #10

                    Yevgeny Efter wrote:

                    If I decide to write a stored procedure, where do I store it?

                    It goes in your SQL Server database. You need to run the SQL query so the SP is created (the CREATE PROCEDURE thing). Search Google for "SQL server stored procedures"[^] and you will get a lot of info.

                    Yevgeny Efter wrote:

                    When you write "cmd = new SqlCommand("sp_Test", conn);", how will SQL Server know what "sp_Test" is?

                    Sorry, I missed that part (I didn't compile and run the code). By default it is a regular query (CommandType.CommandText). For a SP, you must specify it:

                    cmd.CommandTpe = CommandType.StoredProcedure;
                    

                    I hope this helps!

                    Luis Alonso Ramos Intelectix Chihuahua, Mexico My Blog!

                    Y 1 Reply Last reply
                    0
                    • L Luis Alonso Ramos

                      Yevgeny Efter wrote:

                      If I decide to write a stored procedure, where do I store it?

                      It goes in your SQL Server database. You need to run the SQL query so the SP is created (the CREATE PROCEDURE thing). Search Google for "SQL server stored procedures"[^] and you will get a lot of info.

                      Yevgeny Efter wrote:

                      When you write "cmd = new SqlCommand("sp_Test", conn);", how will SQL Server know what "sp_Test" is?

                      Sorry, I missed that part (I didn't compile and run the code). By default it is a regular query (CommandType.CommandText). For a SP, you must specify it:

                      cmd.CommandTpe = CommandType.StoredProcedure;
                      

                      I hope this helps!

                      Luis Alonso Ramos Intelectix Chihuahua, Mexico My Blog!

                      Y Offline
                      Y Offline
                      Yevgeny Efter
                      wrote on last edited by
                      #11

                      Thank you very much!

                      Have a nice day!

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups