Using Date parameter in SQL query, ASP.net - asp.net

I am writing a code that calls a column from a dataset using a SQL query. I use two parameters to identify which rows to select. One is the ProductSerialNumber, and the other is a datetimestamp. See my SQL query below
Select TestStation FROM tblData
WHERE ProductSerialNumber = ? AND Datetimestamp = ?
In the dataset's datatable the productserialnumber is formatted as text, and the other is formatted as a date (as you would expect).
In my vb.net code, I grab the Datetimestamp from another source (don't ask why, the only thing you need to know is that it grabs a valid datetimestamp, dimensioned as a date, that matches exactly with the tblData's entry) and I use the premade query to generate a datatable. The query is a Fill query called "TestStationLookUp"
my vb.net code looks like this
Dim dt as new dataset.tbldataDataTable
Dim dta As New DataSetTableAdapters.tbldataTableAdapter
Dim ProductSerialNumber as string = "XXXXXX"
Dim DateTimeStamp as date = SomeDateVariable
dta.TestStationLookUp(dt, ProductSerialNumber, DateTimeStamp)
It is here that the code tells me:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Line 7366: dataTable.Clear
Line 7367: End If
Error: Line 7368: Dim returnValue As Integer = Me.Adapter.Fill(dataTable)
Line 7369: Return returnValue
Line 7370: End Function
I cannot understand why this error arises, as everything is dimensioned the way it should be. This exact code setup works elsewhere in my code (except it doesn't use a date), but this specific piece won't work.
Also, if I go to the dataset in my solution, I can use the "preview data" on this query and type in the EXACT same parameters (the ProductSerialNumber and DateTimeStamp that match the record in the table AND what I use in my vb code) and it will give me produce the table I want.
Can anyone assist?

This error means that you are trying to access not valid unique id "ProductSerialNumber", maybe it does not exist
Failed to enable constraints. One or more rows contain values
violating non-null, unique, or foreign-key constraints.
Instead of passing the variable that comes from dataset ,pass a valid number that you are sure it exists in database

Related

Passing a Guid through to another page ASP.NET

I have a Guid loaded with a ID that a user selected from a GridView.
I want to pass this Guid to another page, but i dont know how to append it to the statement below:
Response.Redirect("LicenseDetailsView.aspx?idLicense=" guidLicense)
Here is the full code:
Dim dvrLicense As GridViewRow
Dim guidLicense As Guid
dvrLicense = grdAllUserLicense.SelectedRow
guidLicense = StringToGUID(dvrLicense.Cells(1).Text.ToString)
Response.Redirect("LicenseDetailsView.aspx?idLicense=" guidLicense)
the variable i want to pass is called: guidLicense.
Use a format string:
Response.Redirect(String.Format("LicenseDetailsView.aspx?idLicense={0}", guidLicense))
Or perhaps just concatenate it (though the former is preferred):
Response.Redirect("LicenseDetailsView.aspx?idLicense=" & guidLicense)
The point being that there has to be some operation performed on the two values (the string literal and the variable). Putting them next to each other doesn't mean anything to the compiler. A method call with the values as arguments, or an operator between the values, will instruct the code to do something with those values.

Access database UPDATE table with subquery

I never should've expected that knowing mySQL I'd be safe using Access.
I have two tables: users and scores
users table contains: id(auto increment primary key), username, password, etc..
scoers table contains: id(number - foreign key to users.id), highScore
I've previously asked help for INSERT command, which now works as it should. Now I've got issues with a similar UPDATE command.
The non-working command looks like this:
string updateCommand = #"UPDATE scores
SET
id = (SELECT id FROM users WHERE username = #username),
highScore = #score
WHERE highScore = (SELECT MIN(highScore) FROM scores);";
which throws a: Operation must use an updateable query.
To rationalize what I'm trying to accomplish here: I'm INSERT-ing high scores until I reach 10 scores in the table, afterwards instead of adding any new scores and filling up the database needlessly I decided It'd be more sensible to just "overwrite" the currently lowest score using UPDATE.
I am supplied a username and the high score and since the scores table contains only id I need to reach the id of the current user so that's what the first subquery is doing, the second subquery in the WHERE clause is to specify which score to replace (though there is possibly a bug here if there are multiple people with the lowest score, any ideas how to fix that?)
I've also tried using OUTER RIGHT JOIN like this:
string updateCommand = #"UPDATE scores
OUTER RIGHT JOIN users ON scores.id = users.id
SET
scores.id = users.id,
scores.highScore = #score
WHERE (highScore = (SELECT MIN(highScore) FROM scores)) AND (username = #username);";
With no luck(I get a generic Syntax error in UPDATE statement.).
Browsing the net I've found that I possibly "can't" use subqueries in UPDATE statements but I seem to find conflicting opinions on the matter.
I've also tried using the DLookup function in place of subqueries like:
#"...
id = DLookup(""id"", ""users"", ""username = #username""),
...
WHERE highScore = DLookup(""MIN(highScore)"", ""scores"");";
elipses represent extraneous code which is identical to the code above.
Also as a last resort I've tried dividing into multiple queries however userId query which looks like this:
string userIdQuery = "SELECT id FROM users WHERE username = #username"
seems to return a null judging by the NullReferenceException i recieve (Object reference not set to an instance of an object.) when trying to use the variable userId after I've done this:
int userId = 0;
userId = (Int32)command.ExecuteScalar();
I'm supposed to get an integer however I get a null I think. The almost identical query for getting the minimum highscore works flawlessly and the int variable is filled with the correct value so I'm assuming that hte problem is in the query itself somehow. I've tried adding single quotes around the #username parameter assuming that it might not be recognizing the string but it seems that's not it.
Phew.. took me a while to write this. Anyone got any ideas on how to make this all work? If you need more info let me know.
So after some messing around I've found out the causes of my troubles. The bad side is that I increased the amount of code so that I'd avoid subqueries as much as possible since, at least from my experience, Access doesn't really like the use of subqueries in UPDATE or INSERT commands.
What I did first is split the command into 3 separate ones:
"SELECT id FROM users WHERE username = ?;" - To get the id of the user whose score
I'm putting in the database.
#"SELECT scores.id, scores.highScore, scores.dateTime FROM scores WHERE (((scores.highScore)=DMin(""highScore"",""scores"")));" - which gets the id, high score
and time when the entry was... well entered, of the lowest score currently in the high scores list. Thanks to a suggestion from HansUp I used DMin function instead of a subquery with MIN to avoid the Must use an updateable query error. The extraneous parentheses are due to Access since this command was generated by the Access query designer and I'm too afraid to change anything lest I break it.
#"UPDATE scores SET scores.id = ?, scores.highScore = ?, scores.[dateTime] = Now() WHERE (((scores.id)=?) AND ((scores.highScore)=?) AND ((scores.dateTime)=?));" - The update command itself, not much to say here except that it takes the previously extracted data and uses it as values for the command.
One thing I noticed is that even if I got the command working the .ExecuteNonQuery() would always return 0 rows affected. After poking around I found out that named parameters for commands in ASP.NET / C# don't always work and that instead ? should be used instead. It's kind of inconvenient but I can't complain too much.

Ms Access AddItem with VBA

I have a Form that has a button on it. The button basically copies records from one Table to the other.
As records are read and copied, it is also checked for specific values. E.g. If one of the fields in the table has a value of "" then it should call another form that allows me to enter a date. Once the date is entered and the form is closed the programme carries on with copying.
It can also happen that the key fields in the table that is being copied are duplicate. In this case I should a 'listbox form' should be launched with a listbox displaying the values of the duplicate records. I should then select the correct record that I need copied.
Dim NumberCount As Long
NumberCount = RecordsetElementValue.RecordCount
If NumberCount > 1 Then
With Form_F_ListBox.List30
RecordsetElementValue.MoveFirst
Do
With Forms!F_ListBox.List30.AddItem(RecordsetElementValue!E_ElementValue)
End With
RecordsetElementValue.MoveNext
Loop Until RecordsetElementValue.EOF = True
DoCmd.OpenForm "F_ListBox", acNormal
End With
End If
The code sample above is what I have for in case there are duplicate records (NumberCount > 1)
The listbox in my F_ListBox form should be filled with the values in my recordset.
I now run into a runtime error 6014. The RowSourceType property must be set to 'Value List' to use this method.
What am I doing wrong?
The usual way to set the row source of a combo or list box in MS Access is to use an SQL statement, however, you can also use a list. This is controlled by the row source type.
Me.MylistBox.RowSourceType = "Value List"
From your notes, it seems that an SQL statement for the row source would be easier:
Me.MylistBox.RowSource = "SELECT ID FROM MyTable"

Getting Table Field Names as a String

I'm trying to get the list of field names for a given table, to turn them into a string which I can to post back as a variable to another function.
I've Googled loads of stuff regarding GetSchemaTable but all I seem to be able to output are field parameters, but not the actual value of these parameters (ie ColumnName, which is the one I actually want!)
Found this page; What is the SQL command to return the field names of a table?
But all the queries on there give me an error "You do not have access to Table 'Columns'"
I feel sure this is pretty simple, can someone give me a little function that will simply give me
fieldNames = "fieldName1, fieldName2, etc"
I am using a MySQL server and ODBC connections ASP.NET using VB.
I don't know if this will work, but give it a try.
Instantiate a OdbcCommand with something like select * from yourtable limit 0;
Load a DataTable with the datareader returned from cmd.ExecuteReader.
DataTable dt as new DataTable()
dt.Load(cmd.ExecuteReader())
Now iterate through the columns of dt to find out what the column names are.
This is just and idea. Don't know if it will work or not.

L2Entities, stored procedure and mapping

Finally checked out L2E framework and ran into problems almost instantly.
Yeah, i know... i should read some books before.
Situation:
entity with props -> id and name.
entity is mapped to table, which has id and name columns.
sproc, which returns ONLY id column.
Problem:
ObjectResult<MyProp> result = _container.MyStoredProcedure(uberParameter);
Calling this will cause an error
[guilty method goes here] threw exception:
System.Data.EntityCommandExecutionException: The data reader is incompatible with the specified 'DataBase.MyPropTableObject'. A member of the type, 'name', does not have a corresponding column in the data reader with the same name..
Problem #2:
Can`t "just return" that field, cause that column has XML data type, but sproc uses fancy select statements, which causes:
Msg 421, Level 16, State 1, Line 1
The xml data type cannot be selected as DISTINCT because it is not comparable.
Question:
Is it possible to exclusively turn off mapping for this entity prop only for this one sproc?
Problem 1 is due to the proc not having the columns to populate the entity. You don't really need the proc if you have mapped the table, just select the field you want from it using linq
var result = MyEntities.EntityIMapped.First(r => r.id = uberParameter).Name;
Would give you the value from the Name column of the table for the given id. You don't need to use a stored proc for this.
Problem 2 sounds like it is in the proc, I would think that distinct on an xml data column would give a lot of results, but I'm only guessing as I don't know your solution.
This is not a direct answer for your question but, hopefully it will point you in the right direction.

Resources