SQL查询必须声明标量变量

时间:2019-06-11 07:04:30

标签: c# sql variables scalar

我有一个类文件,在其中我声明要在方法中使用的查询的readonly string。我遇到了

的错误
  

必须声明标量变量“ @DBID”

我可以知道我是否错误地声明了变量?

下面是代码段:


班级文件:

private static readonly string QUERY_GETMATCHEDRECORD = "SELECT [Title], [ItemLink], [RecordDocID] FROM [ERMS].[dbo].[Records] WHERE [ID] = @DBID AND [V1RecordID] = @recID AND [V1RecordDocID] = @recDocID";

public DataTable GetMatchedRecord(string DBID, string recID, string recDocID)
{
    string Method = System.Reflection.MethodBase.GetCurrentMethod().Name;
    DataTable dt = new DataTable();
    try
    {
        using (DB db = new DB(_datasource, _initialCatalog))
        {
            db.OpenConnection();
            using (SqlCommand command = new SqlCommand())
            {
                string commandText = QUERY_GETMATCHEDRECORD .FormatWith(DBID,recID,recDocID);
                _log.LogDebug(Method, "Command|{0}".FormatWith(commandText));
                command.CommandText = commandText;
                dt = db.ExecuteDataTable(command);
            }
            db.CloseConnection();
        }
    }
    catch (Exception ex)
    {
        _log.LogError(Method, "Error while retrieving matching records |{0}".FormatWith(ex.Message));
        _log.LogError(ex);
    }
    return dt;
}

Program .cs文件:

MatchedRecords = oDB.GetMatchedRecord(DBID, RecID, RecDocID);

1 个答案:

答案 0 :(得分:1)

仅在将参数添加到命令参数收集后,才能使用带'@'标记的变量。

尝试以下操作:

    using (DB db = new DB(_datasource, _initialCatalog))
    {
        db.OpenConnection();
        using (SqlCommand command = new SqlCommand())
        {
            command.CommandText = QUERY_GETMATCHEDRECORD;
            command.Parameters.AddWithValue("@DBID", DBID);
            command.Parameters.AddWithValue("@recID", recID);
            command.Parameters.AddWithValue("@recDocID",recDocID);
            dt = db.ExecuteDataTable(command);
        }
        db.CloseConnection();
    }