我收到了这个错误:
必须声明标量变量“@ObjectType”。
知道为什么吗?如果我硬编码值,则查询有效。
public static DataSet GetDatabaseObjectHistory(string objectType,
string schemaName,
string objectName,
string msConnectionString)
{
using (SqlConnection sqlConnection = new SqlConnection()
{
ConnectionString = msConnectionString
})
{
sqlConnection.Open();
using (DataSet ds = new DataSet())
{
#region sqlGetSchemaObjects
const string sql = @"SELECT
RowId
,EventTime
,LoginName
,UserName
,DatabaseName
,SchemaName
,ObjectName
,ObjectType
,DDLCommand
FROM
Audit_Log
WHERE
Audit_Log.ObjectType = @ObjectType AND
Audit_Log.SchemaName = @SchemaName AND
Audit_Log.ObjectName = @ObjectName";
#endregion
SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters.AddWithValue("@ObjectType", objectType);
sqlCommand.Parameters.AddWithValue("@SchemaName", schemaName);
sqlCommand.Parameters.AddWithValue("@ObjectName", objectName);
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql, sqlConnection))
{
sqlDataAdapter.Fill(ds, sql);
}
ds.Tables[0].TableName = "Object History";
return ds;
}
}
return null;
}
答案 0 :(得分:1)
尝试以下方法:
public static DataSet GetDatabaseObjectHistory(
string objectType,
string schemaName,
string objectName,
string msConnectionString
)
{
const string sql =
@"SELECT
RowId,
EventTime,
LoginName,
UserName,
DatabaseName,
SchemaName,
ObjectName,
ObjectType,
DDLCommand
FROM
Audit_Log
WHERE
Audit_Log.ObjectType = @ObjectType AND
Audit_Log.SchemaName = @SchemaName AND
Audit_Log.ObjectName = @ObjectName
";
using (SqlConnection con = new SqlConnection(msConnectionString))
using (SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("@ObjectType", objectType);
cmd.Parameters.AddWithValue("@SchemaName", schemaName);
cmd.Parameters.AddWithValue("@ObjectName", objectName);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
ds.Tables[0].TableName = "Object History";
return ds;
}
}
}