在c#中执行SQL查询时出错,手动输入时出错

时间:2015-04-23 09:05:00

标签: c# sql sql-server

我在c#中执行qry,当我从程序中运行它时会返回此错误:

System.Data.dll中出现'System.Data.SqlClient.SqlException'类型的第一次机会异常

以及我捕获SqlException时的异常:

  

“。”附近的语法不正确。

然而,当我在SQL Server中运行它并手动交换变量时,它运行正常。 我觉得我错过了一些基本的东西,但我正盯着自己去死。

查询:

SELECT TOP 1 TempSelection.ErrorOccured
FROM
(
SELECT JL.CommandID AS cmdID, 
    CASE JL.Direction
        WHEN 1 THEN 'Out'
        WHEN 2 THEN 'In'
        WHEN 5 THEN 'ConcOut'
        ELSE 'Both' 
    END
    AS Direction,
    CH.ChannelName, A.Description AS AddressDescription, SG.SelectorGroupName, 
    CASE WHEN SML1.ID IS NOT NULL
            THEN SML1.FormatCode
            ELSE 
                CASE WHEN SML2.ID IS NOT NULL
                THEN SML2.FormatCode
                ELSE NULL 
                END 
    END 
    AS FormatCode,
    CASE WHEN SML1.ID IS NOT NULL
            THEN SML1.TypeCode
            ELSE 
                CASE WHEN SML2.ID IS NOT NULL
                THEN SML2.TypeCode
                ELSE NULL 
                END 
    END 
    AS TypeCode,
    CASE WHEN SML1.ID IS NOT NULL
            THEN CTP1Sender.PartnerName
            ELSE 
                CASE WHEN SML2.ID IS NOT NULL
                THEN CTP2Sender.PartnerName
                ELSE NULL 
                END 
    END 
    AS Sender,

        CASE WHEN SML1.ID IS NOT NULL
            THEN CTP1Recipient.PartnerName
            ELSE CASE 
            WHEN SML2.ID IS NOT NULL
                THEN CTP2Recipient.PartnerName
                ELSE NULL 
                END 
    END 
    AS Recipient,
    EL.ErrorDescription, EL.Assembly, EL.ErrorDetail, C.ErrorOccured


FROM
    @dbEnv.dbo.tbl_jobLog JL 
    LEFT JOIN @dbEnv.dbo.tbl_Commands C ON JL.CommandID = C.CommandID
    LEFT JOIN @dbEnv.dbo.tbl_ProcessFlows PF ON PF.ProcessFlowID = JL.ProcessFlowID 
    LEFT JOIN @dbEnv.dbo.tbl_ProcessFlowDefenitions PFD ON PFD.ProcessFlowDefID = JL.ProcessFlowDefID
    LEFT JOIN @dbEnv.dbo.tbl_Channels CH ON CH.ChannelID = JL.ItemID AND JL.ItemType LIKE 'CHA' AND CH.ChannelID IS NOT NULL
    LEFT JOIN @dbEnv.dbo.tbl_SelectorGroups SG ON SG.SelectorGroupID = JL.ItemID AND JL.ItemType LIKE 'SEL' AND SG.SelectorGroupID IS NOT NULL
    LEFT JOIN @dbEnv.dbo.tbl_ErrorLog EL ON JL.JobID = EL.JobID
    LEFT JOIN @dbEnv.dbo.tbl_inoutmessages IOM ON IOM.InOutMsgID = EL.InOutMsgID
    LEFT JOIN @dbEnv.dbo.tbl_Addresses A ON A.AddressID = IOM.AddressID 
    LEFT JOIN @dbEnv.dbo.tbl_StoredMessagesLog SML1 ON SML1.ID = IOM.StoreLinkID
    LEFT JOIN @dbEnv.dbo.VW_CodeToPartner CTP1Sender ON SML1.SenderCodeID = CTP1Sender.ID
    LEFT JOIN @dbEnv.dbo.VW_CodeToPartner CTP1Recipient ON SML1.RecipientCodeID = CTP1Recipient.ID  
    LEFT JOIN @dbEnv.dbo.tbl_StoredMessagesLog SML2 ON SML2.ID = EL.StoredmessagesID
    LEFT JOIN @dbEnv.dbo.VW_CodeToPartner CTP2Sender ON SML2.SenderCodeID = CTP2Sender.ID
    LEFT JOIN @dbEnv.dbo.VW_CodeToPartner CTP2Recipient ON SML2.RecipientCodeID = CTP2Recipient.ID

WHERE
CH.ChannelName {0}
AND A.Description {1}
AND SG.SelectorGroupName {2}
AND EL.ErrorDescription {3}
AND EL.Assembly {4}
AND EL.ErrorDetail {5}
) AS TempSelection
WHERE
Direction {6}
AND FormatCode {7}
AND TypeCode {8}
AND Sender {9}
AND Recipient {10}
";

字符串中的变量填写如下:

SqlCommand cmd = new SqlCommand();
if (errorRow["Channel"] == null || errorRow["Channel"].ToString() == "")
{
    Channel = "IS NULL";
}
else
{
    Channel = "LIKE '@ChannelName'";
    param = new SqlParameter();
    param.ParameterName = "@ChannelName";
    param.Value = errorRow["Channel"].ToString();
    cmd.Parameters.Add(param);
}

之后使用String.Format:

编辑字符串
sqlCommand = String.Format(sqlCommand, Channel,...);
cmd.CommandText = sqlCommand;

最后是执行本身:

public static Boolean readLatestErrorOccured(SqlConnection sqlConn, SqlCommand sqlCommand)
    {
        try
        {
            sqlCommand.Connection = sqlConn;
            object obj = sqlCommand.ExecuteScalar();
            if (obj != null)
            {
                return Convert.ToBoolean(obj);
            }
        }
        catch (SqlException sqlEx)
        {
            MessageBox.Show("Error in readLatestErrorOccured: SqlException" + Environment.NewLine + Environment.NewLine + sqlEx.Message.ToString());
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error in readLatestErrorOccured" + Environment.NewLine + Environment.NewLine + ex.Message.ToString());
        }
        return false;
    }

PS:我在语句中输入'WITH(NOLOCK)'时也遇到错误(例如:     LEFT JOIN GFKN.dbo.tbl_Commands C WITH(NOLOCK)ON JL.CommandID = C.CommandID)。 qry函数再次在SQL Server中运行,但不是来自应用程序。

Edit1:到目前为止,我只是通过输出命令文本和参数的一些调试信息来基本检查输出qry。 qry的下半部分看起来像这样:

WHERE
    CH.ChannelName LIKE '@ChannelName'
    AND A.Description IS NULL
    AND SG.SelectorGroupName IS NULL
    AND EL.ErrorDescription LIKE '@ErrorDescription'
    AND EL.Assembly LIKE '@Assembly'
    AND EL.ErrorDetail LIKE '@ErrorDetail'
    ) AS TempSelection
    WHERE
    Direction LIKE '@Direction'
    AND FormatCode IS NULL
    AND TypeCode IS NULL
    AND Sender IS NULL
    AND Recipient IS NULL

param @dbEnv:GFKN
param @ChannelName:FTP FR.DHL
param @ErrorDescription:A warning occured while receiving messages.
param @Assembly:Porthus.GoldFish.FTP
param @ErrorDetail:A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
param @Direction:In

1 个答案:

答案 0 :(得分:2)

你不能从C#中提交@DbEnv作为这样的参数!

使用string.format将@DbEnv放入SQL字符串。

如果你尝试使用这样的东西:

cmd.Parameters.AddWithValue("@dbEnv", "DatabaseName");

您将收到您所看到的确切错误。