VBScript - Database - Recordset - How to pass DateDiff value in the database - asp-classic

I'm using DateDiff() function of ASP to find the date difference between two dates.
The Function works fine and displays the exact date difference between two dates but when it comes to insert this value in the database it takes 9 as the value irrespect of any date difference.
Suppose difference between two dates is more than 15 or 20 days, in the database it takes "9".
I have used INT as the DATA TYPE for the column where it displaying the date difference.
Is DATA TYPE creating an issue here?
I even tried using session variable to store the value but no luck - here's my code below:
if request.Form("sub") <> "" then
sql = "Select * from emp_leave_details"
rs.open sql , con, 1, 2
dim diff
dim todate
dim fromdate
fromdate= rs("leave_from")
todate= rs("leave_to")
session("date_diff")=datediff("d",fromdate,todate)
rs.addnew
rs("emp_name") = request.Form("name")
rs("emp_no") = request.Form("number")
rs("address") = request.Form("address")
rs("contact_no") = request.Form("contact")
rs("mobile_no") = request.Form("mobile")
rs("contact_onleave") = request.Form("contact_details")
rs("leave_type") = request.Form("rad")
rs("other_leave_details") = request.Form("PS")
rs("leave_from") = request.Form("from")
rs("leave_to") = request.Form("to")
rs("applied_by") = request.Form("apply")
rs("accepted_by") = request.Form("accept")
rs("approved_by") = request.Form("approve")
rs("no_of_leave_taken")= session("date_diff")
rs.update
response.Write("<script language='javascript'>{update();}</script>")
rs.close
end if

The datatype has nothing to do with this. Storing the value in the session is not the solution. You can use a regular variable.
From your code it looks like you always use the same values for fromdate and todate. This is because you do not iterate the rows in the resultset.
if not rs.bof and not rs.eof then
do while not rs.eof
'' code to execute for each row
rs.moveNext
loop
end if
In your current script rs will always return the results of the first row returned by the query.
The second problem your running into might be the Date datatype. Convert your value to a date using cDate and use this to calculate the difference.

Your problem is , you search for "Select * from emp_leave_details" which always gives all records from that table. You retrieve the values of the first record and do a diff of these, which results in always the same value, that is normal. From your question it is unclear what you really want to do. I suppose so want so select a record like
Select * from emp_leave_details where emp_name=<%=request.Form("name")%>
and based on that add a new record with a computed no_of_leave_taken.

Sorry guys my bad...
It was the database field name that I was calling instead of
fromdate= request.form("from")
todate= request.form("to")
I was calling this
fromdate= request.form("leave_from")
todate= request.form("leave_to")
Sorry again..but I really appreciate you all for providing me with all that possible solutions.
Thanks.

Related

The multi-part identifier could not be bound error won't fix

The Variable fileName contains the name of two columns to fetch value of it, which is in the type of "email,address"
The output of the fileName variable is sam#gmail.com102streetN, which is what I need
but when I try to insert that value into another column table then it throws me an error
The multi-part identifier "sam#gmail.com102streetN" could not be bound.
I don't know how to fix it
for each a in idParase
strSQL = "Select Award, Year, ("&fileName&") as dynamicColumns FROM dbo.Awards_TABLE Where awardID = "&a&""
cmdCRProc.CommandText = strSQL
Set rsCR = cmdCRProc.Execute
nameParase = rsCR("dynamicColumns")
sql2 = "Insert Into dbo.Queue (Award,Year,awardID,FileName) Values ("&rsCR(0)&", "&rsCR(1)&", "&a&", "&nameParase&") "
cmdCRProc.CommandText = sql2
Set rsCR = cmdCRProc.Execute
next
I think this isn't going wrong in the INSERT, but in the SELECT.
If I write out your SELECT it would be something this I think (I don't know the value of "a", but let's say it's 2):
Select Award, Year, (sam#gmail.com102streetN) as dynamicColumns FROM dbo.Awards_TABLE Where awardID = 2
I very much doubt you have a column named 'sam#gmail.com102streetN', right?
I don't know what your goal is, but it seems like you're building a query with a dynamic column name that doesn't exist.
What you can do is Response.Write() your SQL statements and see what the result is. Then maybe run them in your database management tool to check what's going on:
Response.write(strSQL)
And
Response.write(sql2)

Logic statement within a loop for ASP Classic

What would be the logic statement to notify the user that they purchased the same product within the last 90 days?
SQL = "SELECT id, PurchaseDate, ProductName from TableName where id = " & id)
Do Until objRS.EOF
if (objRS("ProductName") and objRS("PurchaseDate") <= dateadd(day,-90,getdate())) and objRS("ProductName") and isNull(objRS("PurchaseDate")) then
AlreadyPurchased = true
end if
objRS.movenext()
Loop
My loop that writes it to the page:
<%=objrs("ProductName")%><% if AlreadyPurchased then%>Last Purchased with last 90 days<%end if %>
The best answer depends on a few assumptions:
A) your query does not return any NULL values, and
B) that you have previously stored the product name in a preexisting variable.
Your code has some issues.
1) if (objRS("ProductName") is basically asking if the fieldset value is a True boolean value. My first assumption is that you already know the product name that you're testing. So, the above snippet should be replaced with this: if (objRS("ProductName").value = strMyProductName where strMyProductName is a variable that stores the product name (as a string).
2) You should consider storing the calculated date in a variable outside the loop. No need to repeatedly compute the date if you can compute it once, store it in a variable, and use the variable in your comparison.
3) Remove the last component of your conditional and objRS("ProductName") because it's redundant and has the same faulty logic as what I explained in (1) above.
4) Your DateAdd() can be written better.
TL;DR
dim strMyProductName, dat90, AlreadyPurchased
AlreadyPurchased = false
strMyProductName = "Shoes"
dat90 = dateadd("d", -90, now) '90 days ago
Do Until objRS.EOF
if cstr(objRS("ProductName").value)=strMyProductName and cdate(objRS("PurchaseDate")) <= dat90 then
AlreadyPurchased = true
exit do
end if
objRS.movenext()
Loop

Selecting values between 2 dates

I am currently working on a website that offers tutoring services and I have been stuck on this issue quite a while..
I have 2 text boxes where the user chooses a start date and a finish date, when the user clicks view he would be suppose to see the results in a gridview. I am using FormParameters to insert the date into the query.
SelectCommand of the sqldatasource
SelectCommand="SELECT [Session].Session_num AS Num, [Session].Session_Time_Stamp AS Session_Date, Student.Student_First & ' ' & Student.Student_Last AS Student FROM (([Session] INNER JOIN Student ON [Session].Student_Num = Student.Student_Num) INNER JOIN Class ON [Session].Class_ID = Class.Class_ID) WHERE ((([Session].Session_Time_Stamp) Between #firstdate And #seconddate))">
Parameters of the SqlDataSource
<SelectParameters>
<asp:FormParameter Name="firstdate" Type="DateTime"/>
<asp:FormParameter Name="seconddate" Type="DateTime"/>
</SelectParameters>
This is executed when the user clicks the view button, it is where I set the values of the parameters and execute the sql select.
Dim fdate As DateTime = Format(CDate(txtStartDate.Text), "MM/dd/yyyy")
Dim ldate As DateTime = Format(CDate(txtEndDate.Text), "MM/dd/yyyy")
gridTutor.SelectParameters("firstdate").DefaultValue = fdate
gridTutor.SelectParameters("seconddate").DefaultValue = ldate
gridTutor.Select(DataSourceSelectArguments.Empty)
gridTutorSessions.DataBind()
fdate and ldate are not empty, however after this is executed the query result is empty. Could it be that wrong methods to execute the select?
Edit: I realized the problem is probably with the query and DateTime format. When I transformed my textbox value to DateTime it put it like this #2/20/2014#. However, it doesn't return anything even if there are values between the two dates.
If anybody have an access query with DateTime I would like to see it. Thanks
I managed to fix it by formatting the date in my access database it's not the best solution but it is a fix for the situation
I believe you need to manually set fdate and ldate just before you do your 'selectparameters' (i.e. use "fdate = Format(CDate(txtStartDate.Text), "MM/dd/yyyy")". According to the following, values asigned to Dim in the manner you have would not reflect the realtime values you want. See the following regarding VB: "You can assign a value to a variable when it is created. For a value type, you use an initializer to supply an expression to be assigned to the variable. The expression must evaluate to a constant that can be calculated at compile time.

Returning in Oracle INSERT is not returning proper value

I have an ASP.NET web application (VB.NET) using an Oracle database. On an insert, I need to get the identity of the inserted row back. I am trying to use RETURNING, but I keep getting a value of 1 returned.
Dim strInsert As String = "INSERT INTO L.TRANSACTIONS (LOCATION_KEY, TRANS_CREATOR, TRANS_EMAIL, TRANS_PHONE) VALUES (:location_key, :trans_creator, :trans_email, :trans_phone) RETURNING TRANS_ID INTO :ukey"
Try
If oConn.State <> ConnectionState.Open Then
oConn.Open()
End If
Dim oCmnd As New OracleCommand(strInsert, oConn)
oCmnd.Parameters.Add("location_key", Session.Item("location").ToString.Trim())
oCmnd.Parameters.Add("trans_creator", Session.Item("userID").ToString.Trim())
oCmnd.Parameters.Add("trans_email", Session.Item("mail").ToString.Trim())
oCmnd.Parameters.Add("trans_phone", Session.Item("phone").ToString.Trim())
oCmnd.Parameters.Add("ukey", Oracle.DataAccess.Client.OracleDbType.Varchar2, System.Data.ParameterDirection.ReturnValue)
Dim strUkey As String = oCmnd.ExecuteNonQuery()
When I run the application, the record gets inserted and the TRANS_ID is incrementing but the returned value is always "1".
You're assigning the result of ExecuteNonQuery to the variable, rather than getting the value assigned to the parameter you've created. I believe you want to change the last line to something like this (untested):
oCmnd.ExecuteNonQuery
Dim strUkey As String = oCmnd.Parameters.GetParameter("ukey").Value
That's because the ExecuteNonQuery will return the number of rows affected:
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command. For CREATE TABLE and DROP
TABLE statements, the return value is 0. For all other types of
statements, the return value is -1.
You can see that exist another question that covers the practices for doing it:
Best practices: .NET: How to return PK against an oracle database?

Having problems with sqlDataReader

I am using a sqlDataReader to get data and set it to session variables. The problem is it doesn't want to work with expressions. I can reference any other column in the table, but not the expressions. The SQL does work. The code is below. Thanks in advance, Anthony
Using myConnectionCheck As New SqlConnection(myConnectionString)
Dim myCommandCheck As New SqlCommand()
myCommandCheck.Connection = myConnectionCheck
myCommandCheck.CommandText = "SELECT Projects.Pro_Ver, Projects.Pro_Name, Projects.TL_Num, Projects.LP_Num, Projects.Dev_Num, Projects.Val_Num, Projects.Completed, Flow.Initiate_Date, Flow.Requirements, Flow.Req_Date, Flow.Dev_Review, Flow.Dev_Review_Date, Flow.Interface, Flow.Interface_Date, Flow.Approval, Flow.Approval_Date, Flow.Test_Plan, Flow.Test_Plan_Date, Flow.Dev_Start, Flow.Dev_Start_Date, Flow.Val_Start, Flow.Val_Start_Date, Flow.Val_Complete, Flow.Val_Complete_Date, Flow.Stage_Production, Flow.Stage_Production_Date, Flow.MKS, Flow.MKS_Date, Flow.DIET, Flow.DIET_Date, Flow.Closed, Flow.Closed_Date, Flow.Dev_End, Flow.Dev_End_Date, Users_1.Email AS Expr1, Users_2.Email AS Expr2, Users_3.Email AS Expr3, Users_4.Email AS Expr4, Users_4.FNAME, Users_3.FNAME AS Expr5, Users_2.FNAME AS Expr6, Users_1.FNAME AS Expr7 FROM Projects INNER JOIN Users AS Users_1 ON Projects.TL_Num = Users_1.PIN INNER JOIN Users AS Users_2 ON Projects.LP_Num = Users_2.PIN INNER JOIN Users AS Users_3 ON Projects.Dev_Num = Users_3.PIN INNER JOIN Users AS Users_4 ON Projects.Val_Num = Users_4.PIN INNER JOIN Flow ON Projects.id = Flow.Flow_Pro_Num WHERE id = "
myCommandCheck.CommandText += QSid
myConnectionCheck.Open()
myCommandCheck.ExecuteNonQuery()
Dim count As Int16 = myCommandCheck.ExecuteScalar
If count = 1 Then
Dim myDataReader As SqlDataReader
myDataReader = myCommandCheck.ExecuteReader()
While myDataReader.Read()
Session("TL_email") = myDataReader("Expr1").ToString()
Session("PE_email") = myDataReader("Expr2").ToString()
Session("DEV_email") = myDataReader("Expr3").ToString()
Session("VAL_email") = myDataReader("Expr4").ToString()
Session("Project_Name") = myDataReader("Pro_Name").ToString()
End While
myDataReader.Close()
End If
End Using
This may be because column names need to be unique for the SqlDataReader to be able to index them using a string name for the column.
A couple of things:
1) You are executing the query 3 times. You can lose the ExecuteNonQuery and ExecuteScalar calls, and replace the while loop with "if myDataReader.Read() / end if" to get the data values for the first resulting record. If no records are found, no session variables are set, just as in your current code.
2) It looks more like the problem lies in your session management (ie getting values from Session) rather than your sql query, which looks OK to me.
Check:
that you have sessionState enabled in your web.config file,
that you don't reset the Session values anywhere, and
that you ask for the same Session field name when you are trying to send the email. (e.g. are you setting Session("DEV_Email") but asking for Session("DEV Email") (space instead of underscore) ?
Sorry everyone. The code works just fine. The sqlDataReader WILL accept expressions as column names.
The reason I was getting an error saying the value of the from and to parameters cannot be null. There was no data in that column for any of the records in my table.

Resources