I want to check if a SQL job is currently running. Is the "run_status" column the correct one to check? Is there a simpler way of doing this without having to loop through each column?
public int CheckAgentJob(string connectionString, string jobName)
{
SqlConnection dbConnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "msdb.dbo.sp_help_jobactivity";
command.Parameters.AddWithValue("#job_name", jobName);
command.Connection = dbConnection;
using (dbConnection)
{
dbConnection.Open();
using (command)
{
SqlDataReader reader = command.ExecuteReader();
reader.Read();
Object[] values = new Object[reader.FieldCount];
int fieldCount = reader.GetValues(values);
int jobStatus = -1; // inactive
for (int i = 0; i < fieldCount; i++)
{
object item = values[i];
string colName = reader.GetName(i);
if (colName == "run_status")
{
if (values[i] != null)
{
jobStatus = (int)values[i];
break;
}
}
}
reader.Close();
return jobStatus;
}
}
}
This code is what I needed. Taken from MSDN
Thanks #JeroenMostert
SELECT sj.Name,
CASE
WHEN sja.start_execution_date IS NULL THEN 'Not running'
WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL THEN 'Running'
WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NOT NULL THEN 'Not running'
END AS 'RunStatus'
FROM msdb.dbo.sysjobs sj
JOIN msdb.dbo.sysjobactivity sja
ON sj.job_id = sja.job_id
WHERE session_id = (
SELECT MAX(session_id) FROM msdb.dbo.sysjobactivity);
You can check it through a stored procedure sp_help_job in the msdb database.
So just run:
Use msdb
go
exec dbo.sp_help_job
it will return all the jobs details where you can find one column named current_execution_status. If it's 1 means it's running. You can get more info from the link sp_help_job
You can provide parameter to the stored procedure as well.
Related
I want to replace if (Convert.ToString(rdr["Data"]) != bItems) with something that would check if data already exist in my database or not to make process faster as going in that loop taking too much time for bigger database. Plz HELP!
for (int p = 0; p < 256; p++) {
bItems += "P" + buffer[p];
}
using (SQLiteConnection con = new SQLiteConnection(databaseObject.myConnection)) {
con.Open();
SQLiteCommand cmd = new SQLiteCommand("select ID, Data from B where Data like 'P%'", con);
var rdr = cmd.ExecuteReader();
while (rdr.Read()) {
if (Convert.ToString(rdr["Data"]) != bItems) {
SQLiteCommand cmd1 = new SQLiteCommand("INSERT INTO B ('Data') SELECT #Data WHERE NOT EXISTS (SELECT ID, Data FROM B WHERE Data = #Data)", con);
cmd1.Parameters.AddWithValue("#Data", bItems);
cmd1.ExecuteNonQuery();
}
else (Convert.ToString(rdr["Data"]) == bItems) {
sItems = "B" + Convert.ToString(rdr["ID"]);
rdr.Close();
break;
}
}
}
bItems = "";
Console.WriteLine(sItems);
}
instead of reading each row and check the data against bItems. You may need to either query the table to see if there is any record matches bItems, if not then insert it. Or, you can simply insert the data if not exists (which what you did in the first condition.
To simplify your work, you can do this :
// insert the new item if not exists in the table
// returns the item Id
private int InsertDataIfNotExists(string bItems)
{
using (SQLiteConnection connection = new SQLiteConnection(databaseObject.myConnection))
using(SQLiteCommand command = new SQLiteCommand("INSERT INTO B ('Data') SELECT #Data WHERE NOT EXISTS (SELECT 1 FROM B WHERE Data = #Data);", con))
{
connection.Open();
command.Parameters.AddWithValue("#Data", bItems);
// insert data if not exists
command.ExecuteNonQuery();
// get the data's Id
cmd.CommandText = "SELECT ID FROM B WHERE Data = #Data LIMIT 1;";
cmd.Parameters.AddWithValue("#Data", bItems);
var result = cmd.ExecuteScalar()?.ToString();
return int.TryParse(result, out int id) && id > 0 ? id : -1;
}
}
with the above, you only insert the data if not exists, and then return the id.
usage :
var insertResultId = InsertDataIfNotExists(bItems);
if(insertResultId == -1)
{
// handle exceptions
}
else
{
Console.WriteLine(insertResultId);
}
I am trying to insert data into a SQL table. The data types I am having issues with are nullable floats. When the NULL values are inserted they change to 0. How can I keep them NULL.
private void InsertStatisticsData(DataTable dt)
{
//check isin periodicity and As of Date
foreach(DataRow row in dt.Rows)
{
DataTable queryResultTable = SQL.Query($#"SELECT * FROM Statistics
WHERE [CodeID] = '{row["CodeID"]}'
AND [Periodicity] = '{row["Periodicity"]}'
AND [As of Date] = '{row["As of Date"]}'");
if(queryResultTable.Rows.Count == 0)
{
//Check for Null Values
for(int i = 0; i < row.ItemArray.Count(); i++)
{
if (Convert.ToString(row[i]) == "")
row[i] = (object)DBNull.Value;
}
//Insert Data Into DataBase
SQL.NonQuery($#"INSERT INTO Statistics
VALUES ('{row["CodeID"]}' ,
'{row["Volatility"]}',
'{row["Beta"]}',
'{row["Info Ratio"]}',
'{row["Tracking"]}',
'{row["Drawdown"]}',
'{row["Periodicity"]}',
'{row["As of Date"]}')");
}
}
}
Nonquery Function:
public static void NonQuery(string query, string databaseName = "Database", string serverAddress = "server-name", int commandTimeout = 30)
{
string connString = $"Server = {serverAddress}; Database = {databaseName}; Trusted_Connection = True";
using (SqlConnection sqlConn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
cmd.CommandTimeout = commandTimeout;
cmd.ExecuteNonQuery();
}
}
You need to make sure your database column structure contains NULL types where you actually need them.
Also make sure you don't have any default constraints set, which automatically values the columns to 0 when null is assigned.
if(Convert.ToString(null) == "")
will be evaluated as false.
so below code won't get executed
row[i] = (object)DBNull.Value;
on a side note, you should use SqlParameters instead of appending values in a string.
This may seem a little heavy handed and bloaty, but if you use parameters (and you really, truly should), I have an extention method I use in my project to take any command object and loop through the parameters to turn a .NET null into a DbNull:
private static void ProcessNullParameters(this DbCommand command)
{
foreach (DbParameter param in command.Parameters)
{
if (param.Value == null)
param.Value = DBNull.Value;
}
}
This way, if your native object returns a null value, you can call the extention method against the command object. I couldn't tell what your SQL object was in your example (a framework of some type?), but presumably, somewhere behind the scenes something like this would be going on:
SqlCommand cmd = new SqlCommand("insert into Statistics values (#Code, #Volatility)", conn);
cmd.Parameters.Add("#Code", SqlDbType.VarChar);
cmd.Parameters.Add("#Volatility", SqlDbType.Decimal);
foreach (DataRow dr in dt.Rows)
{
cmd.Parameters[0].Value = dr["Code"];
cmd.Parameters[1].Value = dr["Volatility"];
// And here you convert your nulls to DbNull
cmd.ProcessNullParameters();
cmd.ExecuteNonQuery();
}
The alternative would be to do this on every value declaration that is nullable.
cmd.Parameters[0].Value = dr["Code"] ?? DbNull.Value
cmd.Parameters[1].Value = dr["Volatility"] ?? DbNull.Value;
I have a database with the infos of the buyers of my product, but I would like it to send the value provided by the program to the database, if it is null, how can I do this?
Code:
I have a database with the infos of the buyers of my product, but I would like it to send the value provided by the program to the database, if it is null, how can I do this?
Code:
string comando = "SELECT COUNT(*) FROM tbl_usuario WHERE user=#Usuario AND pw=#Senha AND tipo=1";
var connection = new MySqlConnection(connString);
var cmd = new MySqlCommand(comando, connection);
cmd.Parameters.AddWithValue("#Usuario", usuario);
cmd.Parameters.AddWithValue("#Senha", senha);
var command = connection.CreateCommand();
connection.Open();
MySqlDataReader leitor = cmd.ExecuteReader();
while (leitor.Read())
{
hd_id = leitor["id"].ToString();
}
if (hd_id == null)
{
//Code i need here
}
int retorno = Convert.ToInt32(cmd.ExecuteScalar());
connection.Close();
There is quite a bit that has been lost in translation in this question, but from I think I am reading I think you want the ID from the database to be retrieved. But the query is just running a count command which will not contain that.
string comando = "SELECT COUNT(*) FROM tbl_usuario WHERE user=#Usuario AND pw=#Senha AND tipo=1";
should actually be
string comando = "SELECT id FROM tbl_usuario WHERE user=#Usuario AND pw=#Senha AND tipo=1";
As you are only returning 1 value (or null if no record match) then you do not need to use a reader; and you can read the return directly, and check for null
var sqlReturn = cmd.ExecuteScalar();
if (sqlReturn == null) { /* Code i need here */ }
else { hd_id = (int)sqlReturn; }
If I did not understand the question; please feel free to let me know and we'll see if we can get you fixed up.
C#
cmd.Parameters.AddWithValue("#Usuario", String.IsNullOrEmpty(usuario) ? DBNull.Value : usuario);
cmd.Parameters.AddWithValue("#Senha", String.IsNullOrEmpty(senha) ? DBNull.Value : senha);
SqlConnection conn = getConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SP_PSLA_SEARCH"; //The stored procedure gets added
cmd.CommandTimeout = 0;
cmd.Connection = conn;
// Start adding the parameters of the stored procedure
cmd.Parameters.AddWithValue("#usrnm", thisUser.Username);
int constit = 0;
if (thisUser.Constituencies.Count > 0)
{
foreach (KeyValuePair<int, string> kp in thisUser.Constituencies)
{
if (kp.Value == ddlConstituency.SelectedValue.ToString())
{
constit = kp.Key;
break;
}
}
}
cmd.Parameters.AddWithValue("#cnstncy", constit);
string pdval = null;
int valtype = 0;
if (rbsearchradios.SelectedIndex == 0)
{
try
{
pdval = searchVal;
cmd.Parameters.AddWithValue("#Search", DBNull.Value);
cmd.Parameters.AddWithValue("#pd", int.Parse(pdval));
cmd.Parameters.AddWithValue("#type", valtype);
}
catch
{
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "stop", "alert('Invalid PD Number Supplied! Please Provide A Valid Submission.');", true);
return;
}
}
else
{
valtype = 1;
cmd.Parameters.AddWithValue("#Search", searchVal);
cmd.Parameters.AddWithValue("#pd", DBNull.Value);
cmd.Parameters.AddWithValue("#type", valtype);
}
cmd.Parameters.AddWithValue("#app", 1);
conn.Open();
// Creates Dataadapter for execution
SqlDataAdapter dp2 = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dp2.Fill(ds, "name");
I am trying to the arguments of the stored procedure and the having this stored procedure execute and get this results into a dataset but I get nothing.. Literally. There are no exceptions, just no result from the stored procedure.
This is the stored procedure:
DECLARE #return_value int
EXEC #return_value = [dbo].[SP_PSLA_SEARCH]
#usrnm = N'tstone',
#cnstncy = 55,
#Search = N'primary',
#pd = NULL,
#type = 1,
#app = 1
SELECT 'Return Value' = #return_value
GO
To troubleshoot:
Make sure what values has each parameter and execute the same query directly against database in Sql Server Management Studio.
Check if you properly use the result from the dataset (it's not clear from the code)
In general, you can also try to simplify and make your code more clear:
the block with return and if (rbsearchradios.SelectedIndex == 0) can be moved at the beginning, it makes no sense to create SqlCommand and then break
if SP returns only single value, you can use the ExecuteScalar() method, which is faster and straightforward.
I'm getting the error:
Invalid attempt to access a field before calling Read()
at: string result = Reader.GetString(0);
I'm not entirely sure what to do or whats wrong though
internal int GetCharGuidByName(string charactername, MySqlConnection connection)
{
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "SELECT guid FROM characters WHERE name=\""+charactername+"\";";
// Initialize MySQL Reader
Reader = command.ExecuteReader();
Reader.Read();
string result = Reader.GetString(0);
// If the character doesn't exist or isn't entered, return 0
int charguid = 0;
if (result != String.Empty)
{
charguid = Convert.ToInt32(result);
}
return charguid;
}
Change the code to:
Reader = command.ExecuteReader();
int charguid = 0;
if(Reader.Read())
{
if(Reader[0] != DBNull.Value)
{
if(int.TryParse(Reader[0].ToString(), out charguid))
{
//value read and is an integer!
}
}
}
return charguid;
You should use ExecuteScalar instead of ExecuteReader
ExecuteSaclar returns the first column of the first row in the result
set, or a null reference
ExecuteReader will return as resultset which you have to then iterate
to read
So looking at your code you just want the first column of the result set
internal int GetCharGuidByName(string charactername, MySqlConnection connection)
{
int charguid = 0;
using(MySqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT guid FROM characters WHERE name=\""+charactername+"\";";
object obj = command.ExecuteScalar();
if (obj != null && obj != DBNull.Value)
{
charguid = Convert.ToInt32(obj);
}
}
return charguid;
}
openConnection()
sql = "SELECT last, first, emp_type, active FROM employee INNER JOIN account ON employee.emp_id = account.emp_id WHERE employee.emp_id = '" & AtxtEmpID.Text & "'"
command = New MySqlCommand(sql, mySqlConnection)
reader = command.ExecuteReader
reader.Read()
AtxtEmpName.Text = reader.Item(0) & ", " & reader.Item(1)
closeConn()
have the save problem