SQL查询在c#中不起作用

时间:2015-11-25 18:21:40

标签: c# sql sql-server-2008

当我在SQL Management Studio中运行下面的查询时,它的工作非常出色。

当我在c#中运行时,结果没有行(只有标题) - 为什么? 我单步执行代码。仅返回标头。没有记录。 注意:Query2被定义为SQL查询。

SQL Management Studio查询 - 工作

SELECT 
    * 
FROM 
    [TraceData].[dbo].[MachineLog2] 
WHERE 
    [MachineFailReason] not like 'Passed' 
    AND Timestamp  >= CAST(GETDATE()-1 AS DATETIME) + CAST('04:00:00' AS DATETIME)  
ORDER BY Timestamp DESC

C#代码 - 不起作用

SqlConnection conn2 = new SqlConnection(connectionString);  
string Query2 = @ConfigurationManager.AppSettings["Query2"];  
conn2.Open();

SqlCommand cmd2 = new SqlCommand(Query, conn2); 
SqlDataReader dr2 = cmd2.ExecuteReader();

2 个答案:

答案 0 :(得分:2)

可能是拼写错误,但您声明If strQty1 <> "" then If strQty1 > 0 then strXML = strXML & " <ItemOut quantity=" & chr(34) & strQty1 & chr(34) & " lineNumber=" & chr(34) & i & chr(34) & ">" & strCR strXML = strXML & " <ItemID>" & strCR strXML = strXML & " <SupplierPartID>S1K0R205B</SupplierPartID>" & strCR strXML = strXML & " </ItemID>" & strCR strXML = strXML & " <ItemDetail>" & strCR strXML = strXML & " <UnitPrice>" & strCR strXML = strXML & " <Money currency=" & chr(34) & "USD" & chr(34) & ">9.78</Money>" & strCR strXML = strXML & " </UnitPrice>" & strCR strXML = strXML & " <Description/>" & strCR strXML = strXML & " <UnitOfMeasure>EA</UnitOfMeasure>" & strCR strXML = strXML & " </ItemDetail>" & strCR strXML = strXML & " </ItemOut>" & strCR End If End If If strQty2 <> "" then If strQty2 > 0 then strXML = strXML & " <ItemOut quantity=" & chr(34) & strQty2 & chr(34) & " lineNumber=" & chr(34) & i & chr(34) & ">" & strCR strXML = strXML & " <ItemID>" & strCR strXML = strXML & " <SupplierPartID>A4216070B16</SupplierPartID>" & strCR strXML = strXML & " </ItemID>" & strCR strXML = strXML & " <ItemDetail>" & strCR strXML = strXML & " <UnitPrice>" & strCR strXML = strXML & " <Money currency=" & chr(34) & "USD" & chr(34) & ">3.96</Money>" & strCR strXML = strXML & " </UnitPrice>" & strCR strXML = strXML & " <Description/>" & strCR strXML = strXML & " <UnitOfMeasure>BX</UnitOfMeasure>" & strCR strXML = strXML & " </ItemDetail>" & strCR strXML = strXML & " </ItemOut>" & strCR End If End If 并使用Query2

Query

答案 1 :(得分:1)

通过将Query放在存储过程中并使用C#运行存储过程,可以更好地调试或完全解决这样的问题。

因此,创建查询的存储过程看起来像这样

USE TraceData;
GO
CREATE PROCEDURE MyWrappedQuery

AS 
BEGIN

SELECT 
    * 
FROM 
    [TraceData].[dbo].[MachineLog2] 
WHERE 
    [MachineFailReason] not like 'Passed' 
    AND Timestamp  >= CAST(GETDATE()-1 AS DATETIME) + CAST('04:00:00' AS DATETIME)  
ORDER BY Timestamp DESC

END

在C#中你可以运行查询'exec MyWrappedQuery'或通过ado.net运行SP

尝试并回复此问题,如果查询在SQL Server中有效但不通过C#,则应该有效。