2

Can some please help how to dynamically generate command object. See below - I need to pass database name and table name to the function which should return number of rows in that table. I'm struggling to write this query. See code which i'm try

        Using _Conn As New SqlConnection(_ConnString)
            _SQLCommand = New SqlCommand()
            _SQLCommand.CommandText = "Select count(*) from " & _
            "lvar_Database " + ".dbo." + lvar_Table
            _SQLCommand.Parameters.Add(New SqlParameter("@Database_Name", SqlDbType.NVarChar))
            _SQLCommand.Parameters.Add(New SqlParameter("@Table_Name", SqlDbType.NVarChar))
            _SQLCommand.Parameters("@Database_Name").Value = lvar_Database
            _SQLCommand.Parameters("@Table_Name").Value = lvar_Table
            Try
                _Conn.Open()
                GetNumberofRows = Convert.ToInt32(_SQLCommand.ExecuteScalar())
            Catch ex As Exception
            End Try
        End Using

Regards

1 Answer 1

1

You do not need command parameters for this. Just assemble your query dynamically with the db and table name:

    Using _Conn As New SqlConnection(_ConnString)
        _SQLCommand = New SqlCommand()
        _SQLCommand.CommandText = _
            "Select count(*) from " + _
            lvar_database + _
            ".dbo." + _
            lvar_Table

        Try
            _Conn.Open()
            GetNumberofRows = Convert.ToInt32(_SQLCommand.ExecuteScalar())
        Catch ex As Exception
        End Try
    End Using
Sign up to request clarification or add additional context in comments.

Comments

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.