table adapter weired returning value - c#

I have a table adapter in Visual studio dataset. I aligned a value to the query inside the table adapter so I can get if the query returns 1 if there is data or 0 for null. example:
document.documentDataSetTableAdapters.Job_NoTableAdapter jnta =
new documentDataSetTableAdapters.Job_NoTableAdapter();
int result = jnta.FillBygetJob_No(documentDataSet1.Job_No);
It never happened to me that result get a value other than 0 or 1. here I got result = 2. so when I made the IF statement
if(result == 1){....}
else if(result == 0)
so I got the error. I solved the problem by doing this:
if(result == 0){...}
else{...}
So what I need is an explanation of how result got the value 2.

So you're filling a DataSet with this query(your comment):
SELECT JN_Full_Form, Job_No, Job_No_ID, year
FROM Job_No
WHERE (JN_Full_Form = (SELECT MAX(JN_Full_Form) AS Expr1
FROM Job_No AS Job_No_1))
Now you expect that it always returns none or a single record. But what if there are two or more records with the same JN_Full_Form which are equal to MAX(JN_Full_Form)?!
So it's absolutely fine to change th if:
if(result == 0)
{
//...
}
else
{
//...
}
Another option is to change the query itself to select one record at a max(presuming sql-server):
SELECT TOP 1 JN_Full_Form, Job_No, Job_No_ID, year
FROM Job_No
WHERE (JN_Full_Form = (SELECT MAX(JN_Full_Form) AS Expr1
FROM Job_No AS Job_No_1))

Related

C# SqlDataAdapter Fill Inconsistent Results

I would greatly appreciate some help with my SqlDataAdapter code below.
I am getting inconsistent results and am at a loss as to what the issue is.
SCENARIO:
This is a windows form project.
I have a routine that loops through a list of stations and calls the code below for each station.
The problem code executes the query (SQL Server) and fills a dataset with the returned rows.
Depending on what the station is up to, the returned rowcount will be >= 0 (typically 1 or 2).
PROBLEM:
The code does not always fill the dataset. Sometimes the dataset fills and sometimes it does not, or more accurately sometimes the rowcount = correct and sometimes rowcount = 0.
Currently, it is the same subset of stations that are not filling correctly.
There are no issues if rowcount is actually = 0.
TROUBLESHOOTING SO FAR:
The code does not throw any exceptions.
Looking at the parameters/ vars in the local window during step through I do not see any differences between stations that return correctly and those that do not.
The query itself does work without issue. I can execute the query in SSMS with the same parameters and I get the expected/ correct results in SSMS.
I do not see any difference in the SSMS query results between between stations that return/ fill correctly and those that do not (columns all have data, etc.).
My first thought was that I must have something amiss with these stations in the underlying tables, but again I see nothing out of place (no missing columns, nulls, etc.).
I have looked at quite a few posts regarding SqlDataAdapter and fill, but they appear to be dealing with all or nothing problems.
I would think if there was a problem with the code, the fill would fail all of the time.
I would also think if there was a problem with the query, the problem would be
present all of the time.
I would further think if there was a problem with the data, I would see something in the query results in SSMS.
RESULTS:
CODE:
string strSql =
#"SELECT
ISNULL(a.ToolGroupId, 0) AS ToolGroupId, ISNULL(a.PartId, 0) AS PartId,
ISNULL(a.CycleCount, 0) AS CycleCount, ISNULL(a.BDT, 0) AS BDT,
start.starttime, endx.endtime,
ISNULL(start.ProgName, 'none') AS Program, ISNULL(a.gName, 'none') AS gName,
ISNULL(a.ProductionMetrics, 1) AS ProductionMetrics
FROM
(SELECT
MIN(datetime) AS starttime, ProgName
FROM
V_CycleTime
WHERE
eocr_no = #stationId
AND datetime >= #startTime
AND datetime < #endtime
GROUP BY
ProgName) AS start
LEFT JOIN
(SELECT
MAX(datetime) AS endtime, ProgName
FROM
V_CycleTime
WHERE
eocr_no = #stationId
AND datetime >= #startTime
AND datetime < #endtime
GROUP BY
ProgName) AS endx ON (endx.ProgName = start.ProgName)
LEFT JOIN
(SELECT
ISNULL(p.ToolGroupId, 0) AS ToolGroupId,
ISNULL(p.PartId, 0) AS PartId,
COUNT(ID) AS CycleCount,
AVG(Expected_Ct) AS BDT,
Program, p.gName, p.ProductionMetrics
FROM
V_CycleTime
LEFT JOIN
(SELECT
ToolGroupId, Program, PartId, t.gName, t.ProductionMetrics
FROM
PartsToPrograms
LEFT JOIN
(SELECT ID, gName, ProductionMetrics
FROM ToolGroups) t ON (t.ID = PartsToPrograms.ToolGroupId)
WHERE
StationId = #stationId
AND IsActive = 1) p ON (p.Program = V_CycleTime.ProgName)
WHERE
eocr_no = #stationId
AND datetime >= #startTime
AND datetime < #endtime
GROUP BY
p.ToolGroupId, p.PartId, Program, p.gName, p.ProductionMetrics) AS A ON (a.Program = start.ProgName)
WHERE
a.ToolGroupID IS NOT NULL
ORDER BY
start.starttime;";
// retrieve the dataset
DataSet ds = new DataSet();
string connetionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
using (var adapter = new SqlDataAdapter(strSql, connetionString))
{
try
{
adapter.SelectCommand.Parameters.AddWithValue("#stationId", GlobalVars.stationId);
adapter.SelectCommand.Parameters.AddWithValue("#startTime", GlobalVars.currentHourStartTime);
adapter.SelectCommand.Parameters.AddWithValue("#endTime", GlobalVars.currentHourEndTime);
adapter.Fill(ds);
}
catch (SqlException ex)
{
SimpleLogger.SimpleLog.Log(ex);
return;
}
}
// test row count
int rowCount = ds.Tables[0].Rows.Count;
if (ds.Tables[0].Rows.Count == 0)
{
//do this
}
else
{
//do that
}

Boolean cast Specified cast is not valid error - Passing value from a case statement to a reader.GetBooleanVal

The error that I'm getting when I hit the item.FinancialHold when I'm going through my loop of reader.GetBooleanVal is "specified cast is not valid." But everything seem to be correct on my select statement. Not sure why I'm getting this exception.
My goal was depending of a certain value that I'm returning I'm changing the results of another column, reason why I'm using a case statement... Any help would be greatly appreciated.
List<CollectionCodeParameter> list = new List<CollectionCodeParameter>();
var sql = #"IF EXISTS (SELECT 1 FROM dbo.[collcode_Agency_Codes])
BEGIN
select
[collcode],
case when([collcode] = 'PIE') then 1
else 0
end as [fin_hold],
FROM[dbo].[collcode_Agency_Codes]
WITH(NOLOCK)
WHERE type = #AgencyType
END";
....code....
using (SqlDataReader reader = cmd.ExecuteReader())
{
var ordinals = reader.GetOrdinals();
while (reader.Read())
{
CollectionCodeParameter item = new CollectionCodeParameter();
item.FinancialHold = reader.GetBooleanVal(ordinals.GetOrdinal("fin_hold")).HasValue ?
reader.GetBooleanVal(ordinals.GetOrdinal("fin_hold")).Value : false; ;
list.Add(item);
}
The error is coming from below. My fin_hold is a bit in my table definitions.
public static bool? GetBooleanVal(this SqlDataReader reader, int ordinal)
{
if (ordinal < 0) return null;
return reader.IsDBNull(ordinal) ? null : (bool?)reader.GetBoolean(ordinal);
}
It would help you debugging to resolve the if statement you cut short, so you can debug it line for line.
I can't try the SQL right now, so I have to guess:
In your SQL, your case-statement is not returning bit , but an int.
case when([collcode] = 'PIE')
then 1
else 0
end as [fin_hold],
Edit:
My fin_hold is a bit in my table definitions.
You are not returning your column, but a number from your case-statement. The alias as [fin_hold] does not relate to your table definition.
Try this:
case when([collcode] = 'PIE')
then Cast(1 as bit)
else Cast(0 as bit)
end as [fin_hold],

Getting empty answer when I should get nothing

I'm working on a C# program that uses a SQL Server Compact database. I have a query where I want to select the highest number in a specific field that looks like this:
SELECT MAX(nr2) FROM TABLE WHERE nr1 = '10'
This works as inteneded when there is a row where nr1 is 10. But I would expect to not get an answer when that row doesn't exist, but instead I get an empty field. So in my C# code I have:
text = result[0].ToString();
When I get a value from my SQL query the string contains a number and when the specified row doesn't exist I get an empty string.
This isn't really a big problem but I would be able to do the following check:
if (result.Count > 0)
Instead of:
if (result[0].ToString() == "")
which I have to do at the moment since count is always larger than 0.
Talk about using a sledgehammer to crack a nut, but...
I don't test it with C# code, but in SQL Server Management Studio, if you run...
SELECT MAX(nr2) FROM TABLE WHERE nr1 = '10' HAVING MAX(nr2) IS NOT NULL
, the result is an empty collection, not a collection with one null (or empty) element.
NOTE: My answer is based on this SO Answer. It seems that MAX and COUNT SQL functions returns always a single row collection.
That SQL statement will always return a result... if the base query returns no result then the value of max() is null !
if you are using ADO.NEt, you could use ExecuteScalar, here an example :
private int GetIDNum()
{
SqlConnection connection = new SqlConnection("connectionstring");
using(SqlCommand command = new SqlCommand("SELECT MAX(nr2) FROM TABLE WHERE nr1 = '10'", connection))
{
try
{
connection.Open();
object result = command.ExecuteScalar();
if( result != null && result != DBNull.Value )
{
return Convert.ToInt32( result );
}
else
{
return 0;
}
}
finally
{
connection.Close();
}
}
}

C# Check null in LINQ query and Transaction Scope giving underlying connection failed to open

I have been messing with 2 problems for quite some time and i have tried alot of things but still i am getting the problems. Following is the simplified version of the first problem.
I have a LINQ query in which p.XP and XP is of type double? . When the value of XP is "null" the query return wrong results even though i have a null in the p.XP field in the database.
from p in entity.positions
where p.XP == XP
select p;
I also tried different things suggested by other threads on SO like
from p in entity.positions
where Object.Equals(p.XP , XP)
select p;
This gives me following exception
Unable to cast type System.Nullable to System.Object.
How to resolve this issue ?
Problem 2:
For LINQ i am using TransactionScope to handle transactions. When i execute the queries i get an exception
Underlying connection failed to Open.
and the inner exception is saying something about DTC. I read online that i will have to enable some service on the server. But i donot want to do that. How can i use transcactions without enabling DTC. My code is something like this
public void function1()
{
using(TransactionScope t = new TransactionScope())
{
RunSomeSelectQueries();
RunSomeInsertQueries();
RunSomeUpdate Queries();
t.Complete();
}
}
These are really two problems and should be separated into two questions.
But I do have an answer for the first one. In SQL database NULL is not equal to NULL. This is because NULL is meant to represent and unknown value and it is not possible to declare that an unknown is equal to another unknown.
To clarify:
"SELECT * FROM sometable where 1 = 1" would return all rows, because "1 = 1" is TRUE
"SELECT * FROM sometable where 1 = 0" would return no rows, because "1 = 0" is FALSE
"SELECT * FROM sometable where NULL = NULL" or "SELECT * FROM sometable where 1 = NULL" would return no rows, because "NULL = NULL" or "1 = NULL" is equal to a new "boolean" state called NULL. A query will only return a row if the WHERE clause is TRUE.
To extract the row where XP is NULL, you must expand your where clause to something like this:
from p in entity.positions
where p.XP == XP || (p.XP == null && XP == null)
select p;
In your first problem, you need to check for nulls separately from the comparisons, because nulls are treated separately.
var foo = (from p in entity.positions
where (p.XP == null && XP == null)
|| (p.XP == XP)
select p);

PetaPoco not returning expected data

I have a BIT data type on one of my columns.
I have written a query that does SELECT * FROM TABLE WHERE BITCOLUMN <> #0
It works fine if I pass in 1 or 0 but if I pass in 3 PetaPoco doesn't return the results I expect.
Executing the SQL in a query window does return all records when I use 3 as the parameter value.
Any ideas?
UPDATE: If I use string SQL = "SELECT * FROM TABLE WHERE BITCOLUMN <> " + MethodParam; This returns data as expected.
Could you tell me what result you expecting? According to MSDN, A bit column can either be 1, 0 or null. It does not make senses to me when you pass 3 to it, since it will select all rows.
And my quick test shows that Petapoco behaves as expected.
using (var database = new Database("sql"))
{
string sql = "SELECT COUNT(*) FROM TBLTESTBIT WHERE BITCOLUMN <> " + "3";
var test = database.ExecuteScalar<long>("SELECT COUNT(*) FROM TBLTESTBIT WHERE BITCOLUMN <> #0", 3);
var test2 = database.ExecuteScalar<long>(sql);
Console.WriteLine(test == test2); // this output true
Console.Read();
}
I think it will be because when you use a parametrised sql string, you are passing in int with a value of 3 in as one of the args. PetaPoco will then create an IDataParameter for that argument and the DbType will be set to DbType.Int32 by default since PetaPoco has no idea what the underlying table column type is.
Use new Sql() not Append.
You should use Query = new PetaPoco.Sql( over Query = PetaPoco.Sql.Append

Categories