2011-02-14 238 views
0

我想動態更改基於查詢字符串的SQLDataAdapter中的查詢。我嘗試將它作爲參數傳遞,但這不起作用。還有其他建議嗎?使用SQLDataAdapter查詢動態列名稱

現在我有:

Dim conn As Data.SqlClient.SqlConnection = New Data.SqlClient.SqlConnection(WebConfigurationManager.ConnectionStrings("MyConnection").ToString()) 

    Dim ad As New SqlDataAdapter 
    Dim selectSQL As String = "SELECT BookTitle, Publisher, Location, CallNumber, [Extra_Description] AS Description, [ISBN] FROM [New_Book_Table] WHERE [Export_to_list]='True' AND [@Category]='True'" 
    Dim selectCMD As SqlCommand = New SqlCommand(selectSQL, conn) 
    ad.SelectCommand = selectCMD 
    selectCMD.Parameters.Add("@Category", SqlDbType.NVarChar, 30).Value = getCategoryString() 
    Dim ds As New DataSet 

    ad.Fill(ds) 
    ListView1.DataSource = ds 
    ListView1.DataBind() 

但得到的錯誤:System.Data.SqlClient.SqlException: Invalid column name '@Category'.

我猜是因爲這是不是這樣做的正確方法。我怎樣才能做到這一點?我可以通過查詢字符串獲得列名。我想將該列名稱傳入查詢並將其識別爲列。

回答

0

好吧,我想通了這一點,這是一個比試圖動態添加參數,由於初始SelectSQL只是一個字符串更容易的方法,我動態構造該字符串機智以下功能:

Protected Function getSQLQuery() As String 
    Dim baseQuery As String = "SELECT BookTitle, Publisher, Location, CallNumber, [Extra_Description] AS Description, [ISBN] FROM [New_Book_Table] WHERE [Export_to_list]='True'" 
    Dim category As String = getCategoryString() 
    Return baseQuery & "AND [" & category & "]='True'" 
End Function