4

I'm very new to C#. I'm trying to retrieve the number of columns using:

SELECT count(*) FROM sys.columns 

Could you please explain how to use the command and put it into a variable.

7 Answers 7

4

To connect to the database you can use the SqlConnection class and then to retrieve the Row Count you can use the Execute Scalar function. An example from MSDN:

cmd.CommandText = "SELECT count(*) FROM sys.columns;";
Int32 count = (Int32) cmd.ExecuteScalar();

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection

Sign up to request clarification or add additional context in comments.

1 Comment

he's asking for the column count, not the row count.
4

You will need to use ExecuteScalar as the others have said. Also, you will need to filter your SELECT on the object_id column to get the columns in a particular table.

SELECT count(*) FROM sys.columns WHERE object_id = OBJECT_ID(N'table_name')

Alternatively, you could do worse than familiarise yourself with the ANSI-standard INFORMATION_SCHEMA views to find the same information in a future-proof, cross-RDBMS way.

Comments

2

You have to use a command and retrieve back the scalar variable :

SqlCommand cmd = new SqlCommand(sql, conn);
Int32 count = (Int32)cmd.ExecuteScalar();

Comments

1
string connectionString =
            "Data Source=(local);Initial Catalog=Northwind;"
            + "Integrated Security=true";

        // Provide the query string with a parameter placeholder.
        string queryString =
            "SELECT Count(*) from sys.columns";

        // Specify the parameter value.
        int paramValue = 5;

        // Create and open the connection in a using block. This
        // ensures that all resources will be closed and disposed
        // when the code exits.
        using (SqlConnection connection =
            new SqlConnection(connectionString))
        {
            // Create the Command and Parameter objects.
            SqlCommand command = new SqlCommand(queryString, connection);

            // Open the connection in a try/catch block. 
            // Create and execute the DataReader, writing the result
            // set to the console window.
            try
            {
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("\t{0}",
                        reader[0]);
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

2 Comments

Thanks for your help. How do I convert the number of columns to an integer for use in a random command?
@liamp47, look at others(Darren Davies,aleroot,gout) answers all of them had converted.
1

use Executescalar() for getting a single element.

 using (SqlConnection con = new SqlConnection(ConnectionString)) //for connecting to database
            {
                con.Open();
                try
                {
                    using (SqlCommand getchild = new SqlCommand("select count(*) from table1 ", con)) //SQL queries
                    {
                        Int32 count = (Int32)getchild.ExecuteScalar();
                     }
                }
             }

Comments

0

Use ExecuteScalar

Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

Int32 colnumber = 0;
string sql = "SELECT count(*) FROM sys.columns";
using (SqlConnection conn = new SqlConnection(connString))
{
    SqlCommand cmd = new SqlCommand(sql, conn);
    try
    {
        conn.Open();
        colnumber = (Int32)cmd.ExecuteScalar();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Comments

0

You'll want to use the ADO .NET functions in the System.Data.SqlClient namespace. ExecuteScalar is an easy-to-use method when you only want to get a single result. For multiple results, you can use a SqlDataReader.

using System.Data.SqlClient;
string resultVar = String.Empty;
string ServerName="localhost";
string DatabaseName="foo";
        SqlConnection conn=new SqlConnection(String.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI",ServerName,DatabaseName));
        SqlCommand cmd=new SqlCommand(Query,conn);
        try
        {
            conn.Open();
        }
        catch (SqlException se)
        {
            throw new InvalidOperationException(String.Format(
                "Connection error: {0} Num:{1} State:{2}",
                se.Message,se.Number, se.State));
        }
        resultVar = (string)cmd.ExecuteScalar().ToString();
        conn.Close();

1 Comment

There is no need to cast as (string) after calling ToString().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.