2

可以请一些帮助如何动态生成命令对象。见下文 - 我需要将数据库名称和表名传递给应该返回该表中的行数的函数。我正在努力编写此查询。查看我正在尝试的代码

        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

问候

4

1 回答 1

1

为此,您不需要命令参数。只需使用数据库和表名动态组合您的查询:

    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
于 2013-01-17T16:40:31.153 回答