簡體   English   中英

為什么變量在 select 查詢中不起作用?

[英]Why variable isn’t working in select query?

為什么當我使用絕對值時這有效但當我嘗試使用變量作為查詢參數時查詢不返回任何數據?

private void SetBomNumber()
{
   
    try
    {
        da2 = new SqlDataAdapter("SELECT Products.[ProductCode], Max(ISNULL([BomNumber], 0) + 1) AS NewBomSerial FROM Products LEFT JOIN Bom ON Products.ProductCode = Bom.ProductCode GROUP BY Products.[ProductCode] HAVING(((Products.[ProductCode]) = '210002')) ", Cn);
        da2.Fill(dt2);
        if (dt2.Rows.Count > 0)
        {
            int BomNumber= Convert.ToInt32(dt2.Rows[0]["NewBomSerial"].ToString());
            txtBomNum.Text = BomNumber.ToString();
            MessageBox.Show("The Next Serial Is :" + BomNumber);
        }
        else
        {
            MessageBox.Show("The Query Doesn’t Work");
        }
        
    }
    catch (Exception Err)
    {
        MessageBox.Show("This Error Occured :" + Err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);


    }

}

使用變量這會顯示錯誤消息“查詢不起作用”?

private void SetBomNumber()

{


try
{

    da2 = new SqlDataAdapter("SELECT Products.[ProductCode], Max(ISNULL([BomNumber], 0) + 1) AS NewBomSerial FROM Products LEFT JOIN Bom ON Products.ProductCode = Bom.ProductCode GROUP BY Products.[ProductCode] HAVING(((Products.[ProductCode]) = @prcode)) ", Cn);
    da2.SelectCommand.Parameters.AddWithValue("@prcode", "%" + txtprcode.Text + "%");
    da2.Fill(dt2);
    if (dt2.Rows.Count > 0)
    {
        int BomNumber= Convert.ToInt32(dt2.Rows[0]["NewBomSerial"].ToString());
        txtBomNum.Text = BomNumber.ToString();
        MessageBox.Show("The Next Serial Is :" + BomNumber);
    }
    else
    {
        MessageBox.Show("The Query Doesn’t Work");
    }
    
}
catch (Exception Err)
{
    MessageBox.Show("This Error Occured :" + Err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

此代碼以其他形式工作沒有問題,在此先感謝。

基於@DRapp 的評論,感謝他,這對我有用:如果您需要條件是變量的確切值,請使用:

da2 = new SqlDataAdapter("SELECT Products.[ProductCode], Max(ISNULL([BomNumber], 0) + 1) AS NewBomSerial FROM Products LEFT JOIN Bom ON Products.ProductCode = Bom.ProductCode GROUP BY Products.[ProductCode] HAVING(((Products.[ProductCode]) = @prcode)) ", Cn);
           
da2.SelectCommand.Parameters.AddWithValue("@prcode",  txtprcode.Text );

如果您需要條件與您可以使用的變量一樣:

   da2 = new SqlDataAdapter("SELECT Products.[ProductCode], Max(ISNULL([BomNumber], 0) + 1) AS NewBomSerial FROM Products LEFT JOIN Bom ON Products.ProductCode = Bom.ProductCode GROUP BY Products.[ProductCode] HAVING(((Products.[ProductCode]) LIKE @prcode)) ", Cn);
               
   da2.SelectCommand.Parameters.AddWithValue("@prcode", "%" +txtprcode.Text+ "%");

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM