Im using VB.net to control a DevExpress report object, i currently have a function that handles the data of said report, and when i run it the reports data comes back completely blank. When i run SQL Server Profiler i can see the command exec dbo.sp_Get_CompanyTime #intCompanyID=1,#dteStart=NULL,#dteEnd=NULL,#strUserID=N'',#intCustomerID=1,#intProjectID=1 is ran when the report is called, returning no data at all because there UserID doesnt match anything, same for customer ID and project ID. The problem im facing is that in VB i have
Dim spcomptime As dsReporting.sp_Get_CompanyTimeDataTable = New dsReporting.sp_Get_CompanyTimeDataTable
Dim OpenDate As Nullable(Of DateTime)
Dim CloseDate As Nullable(Of DateTime)
Dim clientId As Nullable(Of Integer)
Dim cusId As Nullable(Of Integer)
Dim proID As Nullable(Of Integer)
Sp_Get_CompanyTimeTableAdapter.Fill(spcomptime, 1, OpenDate, CloseDate, clientId, cusId, proID)
which as you can hopefully see it should be passing null values for everything past the first 2 parameters! ive tried using DBNull.value as suggested elsewhere, but it tells me it cannot be converted to type "Integer?".
Somebody help me i've been trying to solve this for what feels like an age.
Related
I have two values that have dates inside in the format dd/MM/yyyy and am trying to get the dates in between these two values. The values look like these(17/06/2013) in ONE and TWO variables. And then I send from my asp to an oracle procedure to execude a query and i get ORA-01843 not a valid month. Ive searched for this error but none of the solutions seemed to work for me. The thing is that this code used to work, I didnt change anything on these code and now it doesnt work for some reason.
Here is the code from my asp:
ONE = fromDate.Value
TWO = toDate.Value
Generic.searchBetweenDates(ONE, TWO, dt)
Public Function searchBetweenDates(ByVal PFROMDATE As String, ByVal PTODATE As String, ByRef PUSERINFO As DataTable)
Dim myDataTable As New DataTable
Dim myDataAdapter As New OracleDataAdapter
Dim oraCmd As New OracleCommand("cantine_test.searchbetweendates")
oraCmd.CommandType = System.Data.CommandType.StoredProcedure
oraCmd.Parameters.Add(New OracleParameter("PFROMDATE", OracleType.VarChar, 30)).Value = PFROMDATE
oraCmd.Parameters.Add(New OracleParameter("PTODATE", OracleType.VarChar, 300)).Value = PTODATE
oraCmd.Parameters.Add(New OracleParameter("PUSERINFO", OracleType.Cursor)).Direction = ParameterDirection.Output
Dim oConn As New OracleConnection(ConnectionString)
Try
oConn.Open()
oraCmd.Connection = oConn
cleanParams(oraCmd.Parameters)
myDataAdapter.SelectCommand = oraCmd
myDataAdapter.Fill(myDataTable)
If Not myDataTable Is Nothing Then
PUSERINFO = myDataTable 'return reference using byref param
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
oraCmd.Dispose()
oConn.Close()
myDataAdapter.Dispose()
End Try
Return PUSERINFO
End Function
And here is the code from my Oracle procedure:
PROCEDURE searchbetweendates
(PFROMDATE IN VARCHAR2, PTODATE IN VARCHAR2, PUSERINFO OUT SYS_REFCURSOR)
AS
BEGIN
OPEN PUSERINFO FOR
SELECT ORDERDATE,ORDERID,ORDERTIME,ORDERLIST,QUANTITY,ITEMPRICE,ORDERPRICE,LOCATION
FROM ORDERSDETAIL
WHERE ORDERDATE >= to_date(PFROMDATE, 'dd/MM/yyyy')
AND ORDERDATE <= to_date(PTODATE,'dd/MM/yyyy');
END;
Any ideas?
Oracle hurls ORA-01843 when we pass a string which doesn't match the specified date format: for instance when the string has the US format and the format mask doesn't:
SQL> select to_date('01/13/2013', 'dd/mm/yyyy') from dual
2 /
select to_date('01/13/2013', 'dd/mm/yyyy') from dual
*
ERROR at line 1:
ORA-01843: not a valid month
SQL>
So, the most likely explanation is that you are passing values which you think have a common format but in fact don't. This is fantastically common when "dates" are stored as strings. In other words, this is a debugging question.
Although, one thought occurs: is ORDERSDETAIL.ORDERDATE itself of a DATE datatype.
#6/17/2013#{Date} is the sort of string which will definitely lead to an ORA-1843 error. So you need to trace your code to discover where it comes from.
"how should i check if the value in my columns are correct"
Debugging dot Net is not my strong point. However, there are traditionally two ways. One is to step through the code in a debugging tool. If you're using Visual Studio or a similar IDE you should be able to do this. The other suggestion is to embed logging commands in your code and write trace messages e.g. to a file.
Which approach suits you best? Only you can tell.
I have been trying to apply a solution to some functionality that a user requires on their system.
A user requires me to implement a locking system on their system. They have multiple users which may require to access the site, but the user would like the ability for them to independently lock a records in the web site site, for them to add notes to and to then unlock this so other users are able to do the same.
I have a button on my web page simply named btnLock and i have added an additional column in my database called LockedBy and have the following stored procedure...
ALTER PROCEDURE LockWeeklyTest
(
#AgendaID BIGINT,
#LockingUser VARCHAR(20)
)
AS
BEGIN
SET NOCOUNT ON
UPDATE
WeeklyAgenda
SET
LockedBy = #LockingUser
WHERE
AgendaID = #AgendaID
AND
LockedBy IS NULL
END
I have a class named Weekly Class and have the following code...
Public Shared Sub LockWeeklyAgenda(ByVal WeeklyClass As WeeklyClass)
Using dbConnection As New SqlConnection(ConfigurationManager.AppSettings("dbConnection"))
dbConnection.Open()
Dim dbTrans As SqlTransaction
dbTrans = dbConnection.BeginTransaction()
Using dbCommand As SqlCommand = dbConnection.CreateCommand
With dbCommand
.Transaction = dbTrans
.CommandType = CommandType.StoredProcedure
.CommandText = "LockWeeklyTest"
'Add Parameters for Update
.Parameters.AddWithValue("#AgendaID", WeeklyClass.AgendaID)
.Parameters.AddWithValue("#LockingUser", WeeklyClass.LockedBy)
dbCommand.ExecuteNonQuery()
End With
End Using 'dbCommand
dbTrans.Commit()
End Using
End Sub
I was thinking that the below code for the butlock would populate my Loggedby field with the username but this isnt the case.
Protected Sub btnLock_Click(sender As Object, e As System.EventArgs) Handles btnLock.Click
Dim lock As New WeeklyClass
If lock.LockedBy = "Null" Then
lock.LockedBy = System.Environment.UserName
'lock.AgendaID = AgendaID
End If
' save to the database using the Class DAL
WeeklyClassDAL.LockWeeklyAgenda(lock)
End Sub
I know that the Stored Procedure works as i have tested with the following statement as an example...
EXEC LockWeeklyTest 11, 'Betty'
Im sure that its something to do with the btnlock_click, but im not 100% sure what this is.
Any help is much appriechiated.
Your problem is this line:
If lock.LockedBy = "Null" Then
"Null" is actually a string containing the word Null. What you're after is:
If String.IsNullOrEmpty(lock.LockedBy) Then
That way, if it is actually null or empty, your LockedBy will be set. Currently, it's only setting the LockedBy if LockedBy already equals the string value "Null", which it won't directly after being declared. Is this logic really necessary considering LockedBy will always be null directly after you've declared the WeeklyClass?
Something doesn't look quite right with the AgendaID:
During the button click event the value has been commented out but is still passed through to the stored procedure inside the data layer's 'LockWeeklyAgenda' method.
It's also not defined as a nullable parameter inside the stored procedure itself, so the value that's being sent would depend on the WeeklyClass class' constructor..
can you please also show how the WeeklyClass code looks like?
I am developing an ASP.Net VB Web Application
The application contains a GridView which displays the records of a user table from my created datable. The database is an Sql server database.
The code below inserts data into one table and through the built in function ##Identity to insert the most recently added record id (tt_id) from the trainingTbl table and inserting that record id into the userAssessmentTbl. Adding the identity to the second userAssessmentTbl table works fine.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lblUsr2 As Control = FindControlRecursive(MultiTabs, "txtUsr")
Dim strQuery As String
Dim cmd As SqlCommand
strQuery = "Insert into trainingTbl(s_id, t_date, EditorId, wa_id, st_id) values(#s_id , #t_date, #EditorId, #wa_id, #st_id ) Insert into userAssessmentTbl(tt_id, UserId) values(##Identity, #UserId)"
cmd = New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#s_id", DDLCourse.Text)
cmd.Parameters.AddWithValue("#t_date", Convert.ToDateTime(txtDate.Text))
cmd.Parameters.AddWithValue("#EditorId", User.Identity.Name.ToString())
cmd.Parameters.AddWithValue("#st_id", myLblStation.Value().ToString)
cmd.Parameters.AddWithValue("#wa_id", myLblWatch.Value().ToString)
cmd.Parameters.AddWithValue("#UserId", lblUsr2.UniqueID.ToString)
InsertUpdateData(cmd)
End Sub
The issue I’m having seems to be centered on how I insert a uniqueidenifier from a GridView into a userAssessmentTbl database!
And how, I guess using a loop I can insert the UserId records from that Gridview (GridView1) into the userAssessmentTbl table along with the looped id from the ##Identity.
This part of the insert parameter seems to be incorrect:
cmd.Parameters.AddWithValue("#UserId", lblUsr2.UniqueID().ToString)
And the error I’m met with is: 'Conversion failed when converting from a character string to uniqueidentifier.'
I’ve also tried it like this:
cmd.Parameters.AddWithValue("#UserId", SqlDbType.UniqueIdentifier).Value().ToString()
And im met with the error: 'Operand type clash: int is incompatible with uniqueidentifier'
The qusetion has slightly changed to how do I Insert a String into SQL DB Where DataType Is Uniqueidentifier?
Any help will be really appreciated.
Well first of all:
##IDENTITY returns the most recently created identity for your current
connection, not necessarily the identity for the recently added row in
a table. Always use SCOPE_IDENTITY() to return the identity of the
recently added row.
Secondly, to asnwer your question:
The SQL type Uniqueidentifier and the CLR type Guid match up.
So instead of passing "#UserId" in as a parameter you need to create a Guid out of the string value.
Dim userID As Guid = New Guid(lblUsr2.UniqueID.ToString)
I have a FormView where I pull data from one table (MS Access), and then insert it (plus more data) into another table. I'm having issues with the dates.
The first table has two date fields: date_submitted and date_updated. In some records, date_updated is blank. This causes me to get a data mismatch error when attempting to insert into the second table.
It might be because I'm databinding the date_updated field from the first table into a HiddenField on the FormView. It then takes the value from the HiddenField and attempts to insert it into the second table:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
myDateRequestUpdated = hfDateRequestUpdated.Value
'... It then attempts to insert myDateRequestUpdated into the database.
It works when there is a value there, but apparently you can't insert nothing into a date/time field in Access. I suppose I could make a second insert statement that does not insert into date_updated (to use when there is no value indate_updated), but is that the only way to do it? Seems like there should be an easier/less redundant way.
EDIT:
Okay. So I've tried inserting SqlDateTime.Null, Nothing, and DBNull.Value. SqlDateTime.Null results in the value 1/1/1900 being inserted into the database. "Nothing" causes it to insert 1/1/2001. And if I try to use DBNull.Value, it tells me that it cannot be converted to a string, so maybe I didn't do something quite right there. At any rate, I was hoping that if there was nothing to insert that the field in Access would remain blank, but it seems that it has to fill it with something...
EDIT:
I got DBNull.Value to work, and it does insert a completely blank value. So this is my final working code:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
Dim myDateRequestUpdated = Nothing
If hfDateRequestUpdated.Value = Nothing Then
myDateRequestUpdated = DBNull.Value
Else
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value)
End If
Thanks everyone!
Sara, have you tried casting the date/time before you update it? The data mismatch error likely comes from the fact that the hfDateRequestUpdated.Value you're trying to insert into the database doesn't match the column type.
Try stepping through your code and seeing what the type of that value is. If you find that it's a string (which it seems it might be, since it's coming from a field on a form), then you will need a check first to see if that field is the empty string (VBNullString). If so, you will want to change the value you're inserting into the database to DBNull, which you can get in VB.Net using DBNull.Value.
We can't see your code, so we don't know exactly how you get the value into the database, but it would look something like this
If theDateValueBeingInserted is Nothing Then
theDateValueBeingInserted = DBNull.Value
EndIf
Keep in mind that the above test only works if the value you get from the HiddenField is a string, which I believe it is according to the documentation. That's probably where all this trouble you're having is coming from. You're implicitly converting your date/time values to a string (which is easy), but implicitly converting them back isn't so easy, especially if the initial value was a DBNull
aside
I think what Marshall was trying to suggest was the equivalent of the above code, but in a shortcut expression called the 'ternary operator', which looks like this in VB.Net:
newValue = IF(oldValue is Nothing ? DBNull.Value : oldValue)
I wouldn't recommend it though, since it's confusing to new programmers, and the syntax changed in 2008 from IFF(condition ? trueResult : falseResult)
Your code
Dim myDateRequestUpdated As DateTime
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value) : DBNull.Value()
has a couple of problems:
When you declare myDateRequestUpdated to be DateTime, you can't put a DbNull.Value in it.
I'm not sure you need the () for DbNull.Value: it's a property, not a method (I don't know enough VB to say for sure)
VB doesn't know that : operator
What you probably want is a Nullable(Of DateTime) to store a DateTime value that can also be missing.
Then use something like this to store the value:
myDateRequestUpdated = If(String.IsNullOrWhiteSpace(hfDateRequestUpdated.Value),
Nothing, DateTime.Parse(hfDateRequestUpdated.Value))
If hfDateRequestUpdated.Value is empty, then use Nothing as the result; else parse the value as date (which might fail if it is not a valid date!).
Try this:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim str As String
If TextBox1.Text.Length <> 0 Then
str = "'" & TextBox1.Text & "'"
Else
str = "NULL"
End If
sql = "insert into test(test1) values(" & str & ")"
dsave_sql(sql)
End Sub
Function save_sql(ByVal strsql As String, Optional ByVal msg As String = "Record Saved Sucessfully") As String
Dim sqlcon As New SqlConnection(strConn)
Dim comm As New SqlCommand(strsql, sqlcon)
Dim i As Integer
Try
sqlcon.Open()
i = CType(comm.ExecuteScalar(), Integer)
save_sql = msg
Catch ex As Exception
save_sql = ex.Message
End Try
sqlcon.Close()
Return i
End Function
I'm in the process of switching my application from MSSQL to MYSQL. When I was using MSSQL, I retrieved the last auto increment value via
Private Sub dsImpoundInformation_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles dsImpoundInformation.Inserted
_impoundId = e.Command.Parameters("impoundId").Value
End Sub
Private Sub dsImpoundInformation_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles dsImpoundInformation.Inserting
Dim impoundIdparam As New SqlClient.SqlParameter()
impoundIdparam.ParameterName = "impoundId"
impoundIdparam.Direction = System.Data.ParameterDirection.Output
impoundIdparam.DbType = DbType.Int32
impoundIdparam.Value = 0
e.Command.Parameters.Add(impoundIdparam)
End Sub
and
InsertCommand="INSERT INTO LotManager_impounds (accountId, truckId, createdBy, driver, locationId, dateArrived, towedFrom, reasonForImpound, reasonForImpoundOther, impoundCity, impoundCounty, timeOfImpound, dateDeemedAbandoned, ticketNumber) VALUES (#accountId,#truckId,#createdBy,#driver,#locationId,#dateArrived,#towedFrom,#reasonForImpound,#reasonForImpoundOther,#impoundCity,#impoundCounty,#timeOfImpound,#dateDeemedAbandoned,#ticketNumber); SET #impoundId = SCOPE_IDENTITY();"
Now when i try
InsertCommand="INSERT INTO LotManager_impounds (accountId, truckId, createdBy, driver, locationId, dateArrived, towedFrom, reasonForImpound, reasonForImpoundOther, impoundCity, impoundCounty, timeOfImpound, dateDeemedAbandoned, ticketNumber) VALUES (#accountId,#truckId,#createdBy,#driver,#locationId,#dateArrived,#towedFrom,#reasonForImpound,#reasonForImpoundOther,#impoundCity,#impoundCounty,#timeOfImpound,#dateDeemedAbandoned,#ticketNumber); SET #impoundId = LAST_INSERT_ID();"
i get the error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '0 = LAST_INSERT_ID()' at line 1
And when i try:
InsertCommand="INSERT INTO LotManager_impounds (accountId, truckId, createdBy, driver, locationId, dateArrived, towedFrom, reasonForImpound, reasonForImpoundOther, impoundCity, impoundCounty, timeOfImpound, dateDeemedAbandoned, ticketNumber) VALUES (#accountId,#truckId,#createdBy,#driver,#locationId,#dateArrived,#towedFrom,#reasonForImpound,#reasonForImpoundOther,#impoundCity,#impoundCounty,#timeOfImpound,#dateDeemedAbandoned,#ticketNumber); SET impoundId = LAST_INSERT_ID();"
I get the error:
Unknown system variable 'impoundId'
ultimately, I'm just trying to get the last auto increment value but there are other sections of my code in other applications that I plan on switching to MYSQL that depend on output parameters. I have't yet explored using stored procedures but at this time I would like to get this to work in a similar fashion to how I had it with MSSQL.
Thanks in advance.
Finally I broke down and decided to use stored procedures. This is the best way to do it any ways and makes the code a lot cleaner. For anyone that's encountering this same problem my advice to you would be don't waste you time trying to make it work and just use a stored procedure.