T-SQL 查询未填充数据表

发布于 2025-01-08 13:18:35 字数 3150 浏览 0 评论 0原文

我有一个必须根据操作员输入执行的 SQL 查询。

我正在构建一个表单,其中有一个下拉框,其中填充了表列和一个文本框,供它们提供数据。

SQL 语句是使用 SQL Management Studio 2008 构建的。我已经对其进行了测试(其中 columnFilter="WorkOrder='100883'"),它返回 18 行数据。

当我将相同的数据传递给下面编写的方法时,没有错误,SQL 与我在 Management Studio 中输入的完全相同,但 DataTable 从来没有里面有任何数据。

该代码可能需要进行一些清理,因为我一直在尝试一些不同的事情,但它在逻辑上仍然有效......只是目前不是最合乎逻辑的。

拜托!有人可以告诉我我做错了什么吗?

我通常不使用 AddWithValue 参数选项(因为我认为它很草率并且意味着人们不知道数据类型) ,但在这种情况下我不知道数据类型(?)。我怀疑这个方法可能与我的问题有关,但我不知道如何检查它。

首先,我将向您展示代码:

public DataTable GetSheetMetalRequest(string columnFilter) {
  DataTable table = new DataTable();
  string sqlText = null;
  string[] split = !String.IsNullOrEmpty(columnFilter) ? columnFilter.Split('=') : new string[] { String.Empty };
  if (split.Length == 2) {
    StringBuilder sb = new StringBuilder("SELECT ");
    sb.Append("V.DateStamp, WorkOrder, PartNumber, Qty, EmployeeID, ");
    sb.Append("CAST(P.ProductionLineID AS VARCHAR(10))+': '+ProductionLine AS 'AcpLine', ");
    sb.Append("MTF, CAST(V.EventStatusID AS VARCHAR(10))+': '+[Status] AS 'AcpStatus', ");
    sb.Append("V.RequestID, ReasonID, E.DateStamp AS 'StartDate' ");
    sb.Append("FROM vwSheetMetalRequestByEvent V ");
    sb.Append("INNER JOIN ProductionLines P ON (V.ProductionLineID=P.ProductionLineID) ");
    sb.Append("INNER JOIN [Event] E ON (V.RequestID=E.RequestID) ");
    sb.Append("WHERE V.RequestID IS NOT NULL AND E.EventStatusID=1"); // EventStatusID=SheetMetalRequest
    sb.Append(string.Format(" AND [{0}]=@{0}", split[0]));
    sb.Append(" ORDER BY E.DateStamp, WorkOrder, PartNumber ");
    sqlText = sb.ToString();
  }
  if (!String.IsNullOrEmpty(sqlText)) {
    using (SqlCommand cmd = new SqlCommand(sqlText, Conn_Tracker)) {
      cmd.CommandType = CommandType.Text;
      cmd.Parameters.AddWithValue(string.Format("@{0}", split[0]), split[1]);
      string test = string.Format("{0}={1}", cmd.Parameters[0].ParameterName, cmd.Parameters[0].Value);
      Console.WriteLine(test); // ""
      try {
        cmd.Connection.Open();
        table.Load(cmd.ExecuteReader());
        if (table.Rows.Count < 1) {
          Console.WriteLine("no data");
        }
      } catch (Exception err) {
        LogError("GetSheetMetalRequest", err);
      } finally {
        cmd.Connection.Close();
      }
    }
  }
  return table;
}

现在,我将向您展示 SQL 语句的样子像(格式漂亮且可读):

declare @WorkOrder nvarchar(50)
set @WorkOrder='100883'

SELECT
  V.DateStamp, WorkOrder, PartNumber, Qty, EmployeeID, 
  CAST(P.ProductionLineID AS VARCHAR(10))+': '+ProductionLine AS 'AcpLine', 
  MTF, CAST(V.EventStatusID AS VARCHAR(10))+': '+[Status] AS 'AcpStatus', 
  V.RequestID, ReasonID, E.DateStamp AS 'StartDate' 
FROM vwSheetMetalRequestByEvent V 
  INNER JOIN ProductionLines P ON (V.ProductionLineID=P.ProductionLineID) 
  INNER JOIN [Event] E ON (V.RequestID=E.RequestID) 
WHERE
  V.RequestID IS NOT NULL AND 
  E.EventStatusID=1 AND 
  [WorkOrder]=@WorkOrder 
ORDER BY E.DateStamp, WorkOrder, PartNumber 

I have a SQL query I have to perform based on Operator Input.

I am building a form that has a Drop Down box that is populated with the table columns and a text box for them to provide the data.

The SQL statement was built using SQL Management Studio 2008. I have tested it (where columnFilter="WorkOrder='100883'"), and it returns 18 rows of data.

When I pass the same data to the method I wrote below, there is no error, the SQL is exactly the same as that I punched into Management Studio, but the DataTable never has any data in it.

The code could use a little cleaning up because I've been trying a few different things, but it is still logically valid ...just not the most logical at the moment.

Please! Could someone tell me what I am doing wrong?

I do not generally use the AddWithValue Parameter option (because I think it is sloppy and implies one does not know the data type), but in this case I do not know the data type (?). I suspect this method may have something to do with my problem, but I don't know how to check it.

First, I'll show you the code:

public DataTable GetSheetMetalRequest(string columnFilter) {
  DataTable table = new DataTable();
  string sqlText = null;
  string[] split = !String.IsNullOrEmpty(columnFilter) ? columnFilter.Split('=') : new string[] { String.Empty };
  if (split.Length == 2) {
    StringBuilder sb = new StringBuilder("SELECT ");
    sb.Append("V.DateStamp, WorkOrder, PartNumber, Qty, EmployeeID, ");
    sb.Append("CAST(P.ProductionLineID AS VARCHAR(10))+': '+ProductionLine AS 'AcpLine', ");
    sb.Append("MTF, CAST(V.EventStatusID AS VARCHAR(10))+': '+[Status] AS 'AcpStatus', ");
    sb.Append("V.RequestID, ReasonID, E.DateStamp AS 'StartDate' ");
    sb.Append("FROM vwSheetMetalRequestByEvent V ");
    sb.Append("INNER JOIN ProductionLines P ON (V.ProductionLineID=P.ProductionLineID) ");
    sb.Append("INNER JOIN [Event] E ON (V.RequestID=E.RequestID) ");
    sb.Append("WHERE V.RequestID IS NOT NULL AND E.EventStatusID=1"); // EventStatusID=SheetMetalRequest
    sb.Append(string.Format(" AND [{0}]=@{0}", split[0]));
    sb.Append(" ORDER BY E.DateStamp, WorkOrder, PartNumber ");
    sqlText = sb.ToString();
  }
  if (!String.IsNullOrEmpty(sqlText)) {
    using (SqlCommand cmd = new SqlCommand(sqlText, Conn_Tracker)) {
      cmd.CommandType = CommandType.Text;
      cmd.Parameters.AddWithValue(string.Format("@{0}", split[0]), split[1]);
      string test = string.Format("{0}={1}", cmd.Parameters[0].ParameterName, cmd.Parameters[0].Value);
      Console.WriteLine(test); // ""
      try {
        cmd.Connection.Open();
        table.Load(cmd.ExecuteReader());
        if (table.Rows.Count < 1) {
          Console.WriteLine("no data");
        }
      } catch (Exception err) {
        LogError("GetSheetMetalRequest", err);
      } finally {
        cmd.Connection.Close();
      }
    }
  }
  return table;
}

Now, I'll show you what the SQL statement looks like (formatted to be pretty and readable):

declare @WorkOrder nvarchar(50)
set @WorkOrder='100883'

SELECT
  V.DateStamp, WorkOrder, PartNumber, Qty, EmployeeID, 
  CAST(P.ProductionLineID AS VARCHAR(10))+': '+ProductionLine AS 'AcpLine', 
  MTF, CAST(V.EventStatusID AS VARCHAR(10))+': '+[Status] AS 'AcpStatus', 
  V.RequestID, ReasonID, E.DateStamp AS 'StartDate' 
FROM vwSheetMetalRequestByEvent V 
  INNER JOIN ProductionLines P ON (V.ProductionLineID=P.ProductionLineID) 
  INNER JOIN [Event] E ON (V.RequestID=E.RequestID) 
WHERE
  V.RequestID IS NOT NULL AND 
  E.EventStatusID=1 AND 
  [WorkOrder]=@WorkOrder 
ORDER BY E.DateStamp, WorkOrder, PartNumber 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里人 2025-01-15 13:18:35

我想问题是 split[1] 中的撇号。数据库试图找到“'100883'”字符串而不是“100883”

请尝试这个小技巧:

cmd.Parameters.AddWithValue(string.Format("@{0}", split[0]), split[1].Replace("'",""));

I suppose the problem is apostrophe signs in split[1]. Database trying to find "'100883'" string instead "100883"

Please try this little hack:

cmd.Parameters.AddWithValue(string.Format("@{0}", split[0]), split[1].Replace("'",""));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文