SqlCommand SUM(NVL()) issue - c#

Hello I'm trying to select SUM of all payments but got this exception: nvl is not a recognized function name
with this code:
SqlCommand sc2 = new SqlCommand("SELECT SUM(NVL(payments,0)) AS sumcastka FROM kliplat WHERE akce=" + zakce.Text, spojeni);
spojeni.Open();
int sumOfPrice = 0;
object vysledek2 = sc2.ExecuteScalar();
if (vysledek2 != DBNull.Value)
sumOfPrice = Convert.ToInt32(vysledek2);
// int vysledek2 = Convert.ToInt32(sc2.ExecuteScalar());
spojeni.Close();
This should work as when no records are found for column "payments" I would like to get "0" if possible.
Thank you for reading this.

NVL() is an oracle-specific function. You can use the ANSI COALSECE function to perform the same task. The benefit of COALESCE is that it takes more than two parameters, and picks the first non-null value.

This should work as when no records are found for column "payments"
No, it will only treat NULL values in the payments column as 0.
If no records are found, then ExecuteScalar returns null (not DBNull):
SqlCommand sc2 = new SqlCommand("SELECT SUM(ISNULL(payments,0)) AS sumcastka FROM kliplat WHERE akce=" + zakce.Text, spojeni);
spojeni.Open();
int sumOfPrice = 0;
object vysledek2 = sc2.ExecuteScalar();
if (vysledek2 != null && vysledek2 != DBNull.Value)
sumOfPrice = Convert.ToInt32(vysledek2);
spojeni.Close();
You should also look into using SqlParameters instead of concatenating strings, but that's a separate issue.

In SQL server there is a funcation called ISNULL for the purpose. Please find the query below:
SELECT SUM(ISNULL(payments,0)) AS sumcastka FROM kliplat WHERE akce=" + zakce.Text, spojeni

Related

Object cannot be cast from DBNull to other types in C#

I wrote this code :
MySqlCommand command1 = new MySqlCommand("SELECT SUM(standard_one) FROM `challenge` WHERE (SELECT DAYOFWEEK(date)=1) AND challenge_id = #challenge_id and username = #username", db.getConnection());
command1.Parameters.Add("#challenge_id", MySqlDbType.Int32).Value = comboBox1.SelectedItem;
command1.Parameters.Add("#username", MySqlDbType.VarChar).Value = globals.username;
the problem is some times this command returns null.
how can I check if the command will return null? and if so it returns 0?
if the command will return null? and if so it returns 0?
Make the SQL:
SELECT COALESCE(SUM(standard_one), 0) ...
Bear in mind that you then won't be able to tell the difference between "there were no values that matched the where clause" and "the sum of all values that matched was 0".. If that's important, you'll either need to coalesce to a different value that would never occur in the sum, like -2_147_483_648 or persist with what you have and check for null on the C# side
var x = command1.ExecuteScalar();
if(x == null || x.GetType() == typeof(System.DBNull))
...
else
..cast to int etc..

IF condition check inside USING method and SqlConnection

I am trying to run data validation, execute some code and pass data from one SQL query to another.
My current code looks like the below:
public string SelectUniqueKeyNumber()
{
string newList = string.Join(Environment.NewLine, listOfSkus).ToString();
string key_id;
string sqlConnectionString = #"someConnectionString";
using (SqlConnection connection = new SqlConnection(sqlConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("select top 1 KEY_NUMBER from MyTable where QTY_ON_HAND > 0 " + newList + " order by NEWID()", connection);
SqlDataReader readerKey = command.ExecuteReader();
readerKey.Read();
key_id = String.Format(readerKey[0].ToString());
}
SelectSkuNumber(key_id);
return key_id;
}
What I am trying to do is to check if my readerKey.Read() is not returning null value. If it does then stop the process, otherwise continue. I've tried it in the way as shown below:
public string SelectUniqueKeyNumber()
{
string newList = string.Join(Environment.NewLine, listOfSkus).ToString();
string key_id;
string sqlConnectionString = #"someConnectionString";
using (SqlConnection connection = new SqlConnection(sqlConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("select top 1 KEY_NUMBER from MyTable where QTY_ON_HAND > 0 " + newList + " order by NEWID()", connection);
SqlDataReader readerKey = command.ExecuteReader();
readerKey.Read();
if(readerkey.Read().ToString() == null)
{
//--- stop processing
}
else
{
key_id = String.Format(readerKey[0].ToString());
}
}
SelectSkuNumber(key_id); //---> Then ...(key_id) is not declared value
return key_id;
}
By doing so, I cannot access and pass data of SelectSkuNumber(key_id) due to: Use of unassigned local variable 'key_id'
Any ideas?
All you need do is assign something to key_id when you declare it, like:
string key_id = null; // not string key_id;
and later, after the using:
if (key_id != null)
{
SelectSkuNumber(key_id); //---> Then ...(key_id) is not declared value
}
return key_id;
The caller of the function should, of course, know what to do if a null is returned.
To avoid that particular problem, you can assign some value or nnull to key_id, eg. key_id = "";.
But you have some more problem there:
You are prone to SQL injection, you should use Parameters collection of SqlCommand class.
Are you sure you are concatenating your query correctly? Let's suppose
newList = {"some", "thing"};
Then your query would be:
select top 1 KEY_NUMBER
from MyTable where QTY_ON_HAND > 0
some
thing
order by NEWID()
Which is very, very incorrect to say the least.
if(readerkey.Read().ToString() == null) condition... Read returns bool, which is either true or false, it isn't reference type, so ToString() will never be null, thus the condition will always fail. If you want to check if there was NULL in database you should check:
if (readerKey.Read() && readerKey["KEY_NUMBER"] == DBNull.Value)
which first read row, then receives value of column in that row. It uses short-circuiting for the case, where no records are returned.
readerKey.Read(); is unnecessary before the if statement.

c# string query put null for sql server parameter

I know this question was asked many times, but i am not able to find a solution for it
This is my code
string query = #"SELECT *
FROM SMSMessage
WHERE (respondCode IS #respondCode)
and (sentOn > '08/26/2016')
";
//string query = "select * from SMSMessage";
SqlConnection con = new SqlConnection(Utilities.getConnectionString());
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#respondCode", DBNull.Value);
I want the responseCode to be null,
I am getting error:
syntax error near #responseCode
when I do this responseCode is NULL, there is no syntax error, but the query for some reaonse doesn't bring any result
Help please
I would use directly IS NULL and not passing any parameter, but the most important change is how do you apply the date constant in your query statement.
Assuming you use the Italian locale in your sql server database I would use
string query = #"SELECT * SMSMessage
WHERE respondCode IS NULL
AND (sentOn > CONVERT(DateTime, '26/08/2016', 105))
T-SQL Convert docs
On the contrary I would look carefully to the value passed for the sentOn condition. If this value changes dynamically it is better to use a parameter for this value. In this way the query optimizer of sql server will be able to build a better (faster) execution plan
string query = #"SELECT * SMSMessage
WHERE respondCode IS NULL
AND sentOn > #dateLimit";
SqlConnection con = new SqlConnection(Utilities.getConnectionString());
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#dateLimit", SqlDbType.DateTime).Value = new DateTime(2016, 8, 26);
I guess you want this
Where (respondCode = #respondCode or #respondCode is null)
and sentOn > '08/26/2016'
When a value is passed to #respondCode parameter the records will be filter based on #respondCode and sentOn > '08/26/2016'.
When nothing is passed to #respondCode parameter (ie) NULL, then records will be filtered only based on sentOn > '08/26/2016'
As mentioned in comments by Steve, If you need records only when respondCode is NULL then no need of that variable just hardcode the NULL condition in Where clause
Where respondCode is null
and sentOn > '08/26/2016'

SQL execute scalar returning NULL

queryShelf = "SELECT * FROM shelftable WHERE ShelfId= #ShelfId";
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(queryShelf, connection);
cmd.Parameters.Add(new MySqlParameter("#ShelfId", MySqlDbType.VarChar)).Value = MainWindow.shelfIds[i];
//ExecuteScalar will return one value
int Count = int.Parse(cmd.ExecuteScalar() + "");
ExecuteScalar is used to return a single value, you are selecting complete records. So normally you use ExecuteReader and use Read to get all records.
But actually you can use ExecuteScalar with SELECT *. What happens is that the first column of the first row in the result set is returned, or a null reference if the result set is empty.
Since you get NULL it seems that the filter doesn't return a record.
Since you want a count you could change your query to:
queryShelf = "SELECT COUNT(*) FROM shelftable WHERE ShelfId= #ShelfId";
// ...
int Count = (int) cmd.ExecuteScalar();
Now you never get null but the count of records, 0 if no record exists with this ShelfId.

Problem on querystring in SQL cmd

I have the next code:
private int bla(out int itemsMin, out int purchase)
{
string ID = (Request.QueryString["Ttrsid"] ?? "0").ToString();
{
SqlConnection connection = new SqlConnection("Data Source=*****;Initial Catalog=****;User ID=****;Password=*****;Integrated Security=False;");
string commandtext = "SELECT Min FROM myItems WHERE itemId=#ID";
SqlCommand command = new SqlCommand(commandtext, connection);
connection.Open();
command.Parameters.AddWithValue("#ID", ID); //Adds the ID we got before to the SQL command
itemsMin = (int)command.ExecuteScalar();
string commandtext2 = "SELECT COUNT (*) FROM purchase";
SqlCommand command2 = new SqlCommand(commandtext2, connection);
purchase = (int)command2.ExecuteScalar();
}
return 0;
}
The code is for two labels that i use - one to get the minimum number (itemsMin), and the other is for the count of the purchase.
I'm using the querystring to get the values by the itemid that the user watching on him now.. (from the address bar (for example: items.aspx?Ttrsid=5 so i want to see the minimum number of the Ttrsid = 5).
Everything works fine. when i'm on the Ttrsid = 1 , Ttrsid = 2 - i get what i want, but when i'm enterd to the Ttrsid = 3 and so on - that's give me the error:
System.NullReferenceException
To the line:
itemsMin = (int)command.ExecuteScalar();
.. and it's not null.. the item have all the required fields like Ttrsid = 2 .... so what wrong here?
The next code is the use of the command above:
int i, p; // variable need not be initialized
Console.WriteLine(bla(out i, out p));
if (i < p)
{
haha.Visible = true;
}
else
{
haha2.Visible = true;
}
Console.WriteLine(i);
Console.WriteLine(p);
i = itemsMin , p = purchase .
I'm guessing there is no matching row in the db, so no rows returned. Sanity-check the result from ExecuteScalar - in particular, check it for null before casting to int. It is also possible that the column contains a null, but maybe I'd expect DBNull.Value for that.
Also - use using on all the IDisposable objects here; the connection and command in particular.
I assume below pasted variable is a int type variable
purchase = (int)
Hence you may not be able to convert null values to an integer so try it changing the sql command as below
SELECT isNull(COUNT (*),0) FROM purchase
#Marc I'm really sorry about it
Don't you want to specify a column name next to the min statement? As below
SELECT Min(columnName) FROM myItems WHERE itemId=#ID ?

Categories

Resources