ExecuteScalar return null - c#

I am using below SQL Server function to check is userName and password entered by user through C# windows forms are correct or not as show below too but at first I am getting error at line cmd.ExecuteScalar(); saying
{"Object reference not set to an instance of an object."}
after trying to handle that error I get the error on
return result.ToString();
How I am getting null value if the SQL Server function not returning null value it return 1 or -1 if there is no match within the database?
Even so I searched and tried to handle the null value returned from the cmd.ExecuteScalar(); as you can see my tries but none of the gose successfully
please if anyone can help me ...thanks

you probably want to do something like this :
public string userLogin()
{
string connStr = ConfigurationManager.ConnectionStrings["SRJDconnstr"].ToString();
string cmdStr = #"SELECT dbo.USER_LOGIN(#USER_NAME, #PWD)";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#USER_NAME", TB_USER_NAME.Text);
cmd.Parameters.AddWithValue("#PWD", TB_PWD.Text);
var result = cmd.ExecuteScalar();
return result.ToString();
}
}

cmd.ExecuteScalar() will return the first column of the first row in the result set.
Your SQL Server function code ends with RETURN #vResult which is the RETURN value.
Try and replace RETURN #vResult with SELECT #vResult.

Related

Need example of calling stored procedure sp_SSISCloneConfiguration from a c# program on SQL Server

When I use this code below, I get a -1 returned from line
cmd.ExecuteNonQuery()
It may have something to do with InvalidCastException.
When we run this stored procedure manually in SSMS, it produces a SQL script in its output which we then copy and paste in a new window and run that to get what we want.
Any ideas of why it's not working from C#?
I knew the connection to the server is good.
using (SqlCommand cmd = new SqlCommand("dbo.sp_SSISCloneConfiguration", sqlConnection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#project", SqlDbType.VarChar).Value = projectName;
cmd.Parameters.Add("#destinationProject", SqlDbType.VarChar).Value = projectName;
cmd.ExecuteNonQuery();
}
Because ExecuteNonQuery() returns "The number of rows affected."
If you're expecting data as a result, you probably meant to use ExecuteReader() which returns "A SqlDataReader object", or perhaps ExecuteScalar() which returns "The first column of the first row in the result set, or a null reference if the result set is empty."
For example:
var result = cmd.ExecuteScalar();
Note that the type of result is object. So if "it produces a sql script in its output" then you would probably need to convert it to a string, for example:
var result = cmd.ExecuteScalar()?.ToString();
Note the ? operator being used, because ExecuteScalar() could return null.

how to convert sqlcommand type to String type

I am trying to fetch value from the first row and first column. After fetching I need to convert that value to a string. Please help me with the conversion.
Here is my current code:
conn.ConnectionString = "Server=localhost;Database=MIN-MAK MRO;Trusted_Connection=true";
conn.Open();
SqlCommand command = new SqlCommand("SELECT Top 1 FirstName FROM HistoryReport ", conn);
Something like this -
string getValue = command.ExecuteScalar().ToString();
Note: If there are no rows .ExecuteScalar() will return null
The result from a query with a single result is returned as bare Object. To safely convert it to string, you need to first check it against both DBNull.Value and against null, before performing ToString() on it.
public static String SafeGetString(Object databaseResult)
{
if (databaseResult == DBNull.Value || databaseResult == null)
return null;
return databaseResult.ToString();
}

Query returning NULL value

I'm trying to execute a query in C# which sums the view count of a user. I get returned a NULL value. Using the same statement in Server Management Studio gives me the correct result.
here's my code:
public static int Count_views(string username)
{
int views = 0;
StringBuilder query = new StringBuilder();
query.Append("SELECT Sum(views) FROM videos WHERE username = #username");
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query.ToString(), con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#username", username));
views = Convert.ToInt32(cmd.ExecuteScalar());
}
}
return views;
}
I have debugged the code and the parameters are correct. I get this error :
System.InvalidCastException: Object cannot be cast from DBNull to other types.
which means I'm getting a Null value in return.
The ConnectionString is alright. Every other function works fine except for this one. can anyone tell me what might me the issue here?
Edit:
Below are the screen shots of what I'm encountering. The first screenshot shows the value "Administrator" is being passed inside the function. the second screenshot shows this value is also in the database.
You can change the SUM query to return 0 instead of NULL:
query.Append("SELECT COALESCE(Sum(views),0) FROM videos WHERE username = #username");
You could also use the as operator to cast it to the desired nullable type:
int? views = cmd.ExecuteScalar() as int?;

Getting null reference exception calling stored proc

I run code that produces a datatable. From this datatable, I gleen the State & CRID. I use these pieces of information to run code to get the PRID. Problem is, every time I run this, I get a Null Reference Exception. I've tried declaring int PRID = 0 before running the code; however, I then end up with 0 as my answer every time. I've executed the code in SQLServer 2008 using the same parameters, and I get the correct result.
I am unable to determine why this code is not running correctly.
public int GetPRID(int RRID, string State, int PCID)
{
try
{
SQLCON = new SqlConnection(connectionString);
SQLCON.Open();
SQLCmd = new SqlCommand("spGetPRID", SQLCON);
SQLCmd.CommandType = CommandType.StoredProcedure;
SQLCmd.Parameters.Add("#RRID", SqlDbType.Int).Value = RRID;
SQLCmd.Parameters.Add("#State", SqlDbType.VarChar).Value = State;
SQLCmd.Parameters.Add("#PCID", SqlDbType.Int).Value = PCID;
int PRID = (Int32)SQLCmd.ExecuteScalar();
return PRID;
}
catch(Exception ex)
{
HttpContext.Current.Response.Redirect("~/ErrorRedirect.aspx?" + ex.Message, false);
return 0;
}
finally
{
SQLCON.Close();
}
}
This line is problematic here
int PRID = (Int32)SQLCmd.ExecuteScalar();
of course I can't know the result of your stored procedure, but ExecuteScalar could return NULL and if this is the case the cast to Int32 will fail with the error null reference exception
MSDN says
Returns the first column of the first row in the result set, or a null
reference (Nothing in Visual Basic) if the result set is empty
So the correct approach if there is a possibility to get a null as return value is
object result = SQLCmd.ExecuteScalar();
if(result != null)
PRID = Convert.ToInt32(result);
From memory SQLCmd.ExecuteScalar() will return null if no value is returned, which will give you a null reference exception. If a value is returned but the value is a database null it will return BDNull.value, which will also fail because it can't be cast to an int32.
I found the issue. It wasn't in my C# code - it was within the SQL itself. I was declaring #PRID as int, and asking it to return #PRID.
Once I removed this, it worked fine. Thank you all for your contributions.

Invalid Cast when dealing with ##Identity

I have a winforms app that includes the following class method:
public aSqlQuery(SqlCommand pSqlCom, string pMode = "object", bool pGetID = false)
{
try
{
string strConnection = aSystem.ConnectionString;
SqlConnection linkToDB = new SqlConnection(strConnection);
pSqlCom.Connection = linkToDB;
switch (pMode)
{
case "non query":
{
linkToDB.Open();
pSqlCom.ExecuteNonQuery();
if (pGetID == true)
{
SqlCommand sqlCom = new SqlCommand("SELECT ##IDENTITY;", linkToDB);
this.LastID = (int)sqlCom.ExecuteScalar();
}
linkToDB.Close();
}
break;
plus other switches
The pSqlCom (SqlCommand) executes fine becuase I can see the data written into the database. However the subsequent "SELECT ##IDENTITY" statement gives an invalid cast error
What am I doing wrong and how can I retrieve the new ID created by SQL within my class method?
Insert the row and get the Id it is was given with SCOPE_IDENTIY(), don't use ##IDENTITY.
You need to use SCOPE_IDENTITY() on the same connection and scope, just after the INSERT.
In your example no INSERT is performed on your connection so you can't expect to get the last generated Id.
In your example its not clear that pSqlCom performs an INSERT, if it does not any indentity function will return NULL which cannot be converted to int
EDIT
You want to use SCOPE_IDENTITY() and you want to do it in the same Command as the INSERT.
So, your statement should be somthing like
var sql =
#"INSERT <Your Data> <Your Table>;
SELECT SCOPE_IDENTIY();"
using (SqlConnection connection = new SqlConnection(strConnection))
{
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
object result = command.ExecuteScalar();
}
}
int? id = (int?)(!Convert.IsDBNull(result) ? result : null);
The correct answer it turns out was that the SELECT SCOPE_IDENTITY() statement had to form part of the same SqlCommand as the INSERT statement which preceeded it, but which I had contained in the previous SqlCommand 'pSqlCom'. Once the SELECT SCOPE_IDENTITY() was incuded as part of pSqlCom the code correctly returned the Identity.
Your call to the command should be returning something not of scalar type. Indeed you need to use Int32 instead. Chek ExecuteScalar on MSDN.
Also, I recommend you to use SCOPE_IDENTITY() instead of ##Identity. Check the following link for a detailed explanation.

Categories

Resources