Convert Date to yyyyMMddhhmmss using SQL Server CONVERT - asp.net

I need to compare between dates by converting the SQL Server datetime value (ex: 20-Feb-14 12:52:48 PM) to yyyyMMddhhmmss
I tried the following but still need to replace the spaces and ":" and can't do multiple replace
REPLACE(RIGHT(CONVERT(VARCHAR(19), (OrderDate), 120), 19), '-', '')
Any ideas?
Here is my full code:
Dim dsOrders As New DataSet
Dim daOrders As SqlDataAdapter
Dim Cnn As New SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString"))
Dim strSQL As String
strSQL = "Select O.OrderID,O.Status,O.OrderDate, O.DeliveryDate, OD.Title,OD.Data from SPLBL_Orders O join SPLBL_OrderData OD on O.OrderID=OD.OrderID where OD.LanguageID=1"
'''' Generate Filter Results
If txtKeyword.Text.ToString <> "" Then
strSQL = strSQL + " OR OD.Data Like N'%" + txtKeyword.Text.ToString + "%'"
End If
If txtMemberID.Text.ToString <> "" Then
strSQL = strSQL + " and O.MemberID = " + txtMemberID.Text.ToString
End If
If chkFeatured.Checked Then
strSQL = strSQL + " and O.Featured=1"
End If
Dim lstStatus As ListItem
Dim strStatus As String = ""
For Each lstStatus In ddlStatus.Items
If lstStatus.Selected Then
If strStatus <> "" Then
strStatus = strStatus + ","
End If
strStatus += lstStatus.Value.ToString()
End If
Next
If strStatus <> "" Then
strSQL = strSQL + " and O.Status IN(" + strStatus + ")"
End If
If txtStartDate.Text <> "" Then
Dim strSdate As DateTime = txtStartDate.Text.ToString
Dim strStart = strSdate.ToString("yyyyMMddhhmmss")
If txtEndDate.Text <> "" Then
Dim strEdate As DateTime = txtEndDate.Text.ToString
Dim strEnd As String
If txtEndDate.Text <> "" Then
strEnd = strEdate.ToString("yyyyMMddhhmmss")
Else
strEnd = Date.Today.ToString("yyyyMMddhhmmss")
End If
strSQL = strSQL + " and REPLACE(REPLACE(REPLACE((CONVERT(VARCHAR(19), (OrderDate), 120)), ':', ''), '-', ''), ' ', '') Between " + strStart + " and " + strEnd + ""
End If
End If
strSQL = strSQL + " order by OD.OrderID desc"

You're causing yourself unneeded trouble because you're going about this the hard way. You should be using parameterized SQL for this (and any time you want to pass a variable value into an SQL query):
strSQL = strSQL + " and OrderDate Between #dateStart and #dateEnd"
Then pass your start date and end dates to the query as DateTime parameters with the names #dateStart and #dateEnd.
For information about using parameterized queries in VB:
How do I create a parameterized SQL query? Why Should I?
Here's essentially what you need to do. Note that I've created an SqlCommand object and added parameters to it as the query is built up. You'll need to use this SqlCommand object when you execute the actual query.
Dim dsOrders As New DataSet
Dim daOrders As SqlDataAdapter
Dim Cnn As New SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString"))
Dim Cmd As New SqlCommand()
Cmd.Connection = Cnn
Dim strSQL As String
strSQL = "Select O.OrderID,O.Status,O.OrderDate, O.DeliveryDate, OD.Title,OD.Data from SPLBL_Orders O join SPLBL_OrderData OD on O.OrderID=OD.OrderID where OD.LanguageID=1"
'''' Generate Filter Results
If txtKeyword.Text <> "" Then
strSQL += " OR OD.Data Like #keyword"
Cmd.Parameters.AddWithValue("#keyword", "%" + txtKeyword.Text + "%")
End If
If txtMemberID.Text <> "" Then
strSQL += " and O.MemberID = #memberId"
Cmd.Parameters.AddWithValue("#memberId", txtMemberID.Text)
End If
If chkFeatured.Checked Then
strSQL += " and O.Featured=1"
End If
Dim lstStatus As ListItem
Dim statusCount As Integer = 1
Dim strStatus As String = ""
For Each lstStatus In ddlStatus.Items
If lstStatus.Selected Then
Dim paramName As String = "#status" + statusCount
strStatus += ", " + paramName
Cmd.Parameters.AddWithValue(paramName, lstStatus.Value.ToString)
statusCount += 1
End If
Next
If strStatus <> "" Then
strSQL += " and O.Status IN(" + strStatus.Substring(2) + ")"
End If
If txtStartDate.Text <> "" Then
Dim startDate As DateTime = DateTime.Parse(txtStartDate.Text)
Dim endDate As DateTime
If txtEndDate.Text <> "" Then
endDate = DateTime.Parse(txtEndDate.Text)
Else
endDate = DateTime.Today
End If
strSQL += " and OrderDate Between #startDate and #endDate"
Cmd.Parameters.AddWithValue("#startDate", startDate)
Cmd.Parameters.AddWithValue("#endDate", endDate)
End If
strSQL += " order by OD.OrderID desc"

Related

DateTimePicker Range for VB.net and Access Database

I am a frustrated Newb. I am trying to use a couple of datetimepickers to display the date range from an Access Database in a DataGridView. Here is the code I am using:
Dim dtp1 As String = DateTimePicker1.Text
Dim dtp2 As String = DateTimePicker2.Text
Dim strCriteria, task As String
Me.Refresh()
If dtp1 = "" Then
MsgBox("Please Enter The Date Range", vbInformation, "Date Range Required")
Else
strCriteria = "([Appt Date] >= #" & dtp1 & "# And [Appt Date] <= #" & dtp2 _
& "#)"
task = "SELECT * FROM BDC1 WHERE (" & strCriteria & ") order by [Appt Date]"
End If
Try to change your code to :
Dim dtp1 As String = DateTimePicker1.SelectedDate.Value.ToString("#yyyy/MM/dd#")
Dim dtp2 As String = DateTimePicker1.SelectedDate.Value.ToString("#yyyy/MM/dd#")
Dim con As SqlConnection ="Your connection string here"
task = "SELECT * FROM BDC1 WHERE [Appt Date] BETWEEN '" + dtp1 + "' AND '" + dtp2 + "'
order by [Appt Date]"
Dim da As SqlDataAdapter = New SqlDataAdapter(task , con)
dim dt as new datatable()
da.Fill(dt)
con.Close()
YourdatagridviewName.Datasource=dt

Can't UPDATE a large image size that was INSERTed in the database in asp.net

Here is the problem, when I insert an image (let's call it Data A) which is 1.32MB, it will be inserted successfully. But if I will insert again Data A(but it will update now because i used UPSERT, see my code), it will not be updated and it will result to connection time out.
But when i insert another data (Data B) which is only 4KB, it will also be inserted successfully and if I will insert again into it(which is update), it will be updated successfully. What can I do? I cannot understand the problem. I already made my command timeout for 2 mins but nothing happened and it just loaded forever. I also used sql transaction but it did nothing.
Here is my code:
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim strConnString As String = DataSource.ConnectionString
Using con As New SqlConnection(strConnString)
Dim SQLStr As String
Dim base64String = TextArea1.Value
Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
Dim FileSizeOfIMG As String
FileSizeOfIMG = imageBytes.Length
Dim ImageTypeDataOfImage As New SqlParameter("#Data", SqlDbType.Image)
ImageTypeDataOfImage.Value = imageBytes
SQLStr = "SELECT 1 FROM [Patient_Data].[dbo].[tbPatientImage] where HospNum='" & Session.Item("HospNum") & "'" & _
" and IDNum='" & Session.Item("IDNum") & "' and FileType= '" & lblHeader.Text & "'"
Dim cmd As New SqlCommand(SQLStr, con)
cmd.Connection = con
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
SQLStr = "UPDATE [Patient_Data].[dbo].[tbPatientImage] SET PatImage= #Data, FileSize= '" & FileSizeOfIMG.ToString & "' , TransDate = GetDate() where HospNum='" & Session.Item("HospNum") & "' and IDNum='" & Session.Item("IDNum") & "' and FileType= '" & lblHeader.Text & "'"
Else
SQLStr = "INSERT INTO [Patient_Data].[dbo].[tbPatientImage](HospNum,IDNum, DoctorID, PatImage , FileType, FileName, FileSize , TransDATE) " & _
" VALUES (#HospNum,#IDNum, #DoctorID, #Data, #FileType, 'Patient Photo' , #FileSize, GETDATE())"
End If
reader.Close()
cmd.CommandText = SQLStr
cmd.Parameters.AddWithValue("#HospNum", Session.Item("HospNum"))
cmd.Parameters.AddWithValue("#IDNum", Session.Item("IDNum"))
cmd.Parameters.AddWithValue("#DoctorID", Session.Item("DoctorID"))
cmd.Parameters.AddWithValue("#FileType", lblHeader.Text)
cmd.Parameters.AddWithValue("#FileSize", FileSizeOfIMG.ToString)
cmd.Parameters.Add(ImageTypeDataOfImage)
cmd.ExecuteNonQuery()
con.Close()
GetData()
End Using
End Sub
I haven't figured out what causes this but i have figured out a remedy by having a delete query first then insert data.
SQLStr = "delete FROM [Patient_Data].[dbo].[tbPatientImage] where HospNum='" & Session.Item("HospNum") & "'" & _
" and IDNum='" & Session.Item("IDNum") & "' and FileType= '" & lblHeader.Text & "'"
Dim cmd As New SqlCommand(SQLStr, con)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
SQLStr = " INSERT INTO [Patient_Data].[dbo].[tbPatientImage](HospNum,IDNum, DoctorID, PatImage , FileType, FileName, FileSize , TransDATE) " & _
" VALUES (#HospNum,#IDNum, #DoctorID, #Data, #FileType, 'Patient Photo' , #FileSize, GETDATE())"
cmd.CommandText = SQLStr
'cmd.CommandTimeout = 120
cmd.Parameters.AddWithValue("#HospNum", Session.Item("HospNum"))
cmd.Parameters.AddWithValue("#IDNum", Session.Item("IDNum"))
cmd.Parameters.AddWithValue("#DoctorID", Session.Item("DoctorID"))
cmd.Parameters.AddWithValue("#FileType", lblHeader.Text)
cmd.Parameters.AddWithValue("#FileSize", FileSizeOfIMG)
cmd.Parameters.Add(ImageTypeDataOfImage)
cmd.ExecuteNonQuery()
con.Close()
GetData()
lblMessage.Text = "Saved."
End Using
End Sub

Customized ToolTip on MSChart Data

I'm trying to show a 'customized' ToolTip on an MSChart on an asp.net page, using vb.net
The chart displays OK, but I'm trying to get it to show the 'YEAR' as part of the tooltip, as well as the XY values.
I can't figure out how to do it.
Here's the code that I'm using to build the chart:
dt = New DataTable
dt.Columns.Add("Topic")
dt.Columns.Add("Value")
dt.Columns.Add("Year")
For i = 0 To t_YEARS.Count - 1
Sql = "SELECT att_Topic, att_Value, att_Year from Att "
Sql += " WHERE att_Year = '" & t_YEARS(i) & "' "
conn.ConnectionString = strConnString
conn.Open()
cmd = New SqlCommand(Sql, conn)
dr = cmd.ExecuteReader
While dr.Read
dt.Rows.Add(dr(0), dr(1), dr(2))
End While
dr.Close()
cmd.Dispose()
conn.Close()
Next
Chart1.DataSource = dt
Chart1.Series("Series1").XValueMember = "Topic"
Chart1.Series("Series1").YValueMembers = "Value"
Chart1.Series("Series1").ToolTip = "#VALX - #VALY"
Chart1.ChartAreas("ChartArea1").Area3DStyle.Enable3D = True
Chart1.DataBind()
Well, there may be a better answer, but I figured out a work-around anyhow ... I'm adding the YEAR to the axislabel. Then, in chart1_customize, changing the color of the bar, based on different axislabel. Seems to work.
dt = New DataTable
dt.Columns.Add("Topic")
dt.Columns.Add("Value")
dt.Columns.Add("Year")
For i = 0 To t_YEARS.Count - 1
showDATA = False
Sql = "SELECT att_Topic, att_Value, att_Year, att_Data from BWS_Att "
If (RBL_LIMIT.SelectedValue = 1) Then
showDATA = True
Sql += " WHERE att_Attrib = 'Location' "
Sql += " AND att_Data IN ('" & String.Join("','", t_LOCS) & "')"
ElseIf (RBL_LIMIT.SelectedValue = 2) Then
showDATA = True
Sql += " WHERE att_Attrib = 'Department' "
Sql += " AND att_Data IN ('" & String.Join("','", t_DEPTS) & "')"
Else
Sql += " WHERE att_Attrib = 'Company' "
End If
Sql += " AND att_Year = '" & t_YEARS(i) & "' "
Sql += " AND att_Topic IN ('" & String.Join("','", t_CATS) & "')"
Sql += " Order By att_ind"
conn.ConnectionString = strConnString
conn.Open()
cmd = New SqlCommand(Sql, conn)
dr = cmd.ExecuteReader
While dr.Read
'dt.Rows.Add(dr(0), dr(1), dr(2))
thisYR = dr(2).ToString
If (lastYR <> thisYR) Then
Chart1.Series("Series1").Points.Add(vbEmpty)
Chart1.Series("Series1").Points.Add(vbEmpty)
lastYR = thisYR
End If
If (showDATA = True) Then
Chart1.Series("Series1").Points.AddXY(dr(2).ToString & "|" & dr(3).ToString & ":" & dr(0).ToString, dr(1))
Else
Chart1.Series("Series1").Points.AddXY(dr(2).ToString & ":" & dr(0).ToString, dr(1))
End If
Chart1.Series("Series1").ToolTip = " #AXISLABEL | #VALY"
End While
dr.Close()
cmd.Dispose()
conn.Close()
Next
~~~~~~~~~~
Private Sub Chart1_Customize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Chart1.Customize
Dim C() As Drawing.Color = { _
Drawing.Color.Khaki, _
Drawing.Color.DarkSalmon, _
Drawing.Color.Goldenrod, _
Drawing.Color.MediumAquamarine, _
Drawing.Color.Tan _
}
Dim CN As Int16 = 0
Dim thisC As Int16 = 0
Dim LAST As String = String.Empty
For Each dp As System.Web.UI.DataVisualization.Charting.DataPoint In Chart1.Series("Series1").Points
Dim x As Array = dp.AxisLabel.Split(":")
If (x(0) <> "") Then
Dim H As String = x(0)
If (LAST <> H) Then
CN += 1
LAST = H
thisC = (CN Mod 5)
End If
dp.Color = C(thisC)
End If
Next
End Sub

VBNet Expected Expression when calling function returning string matrix

I have a function that (should) return a 2d string array/matrix from random records in a DB
Function GetRndRecords(table As String, fields As String(), num_records As Integer) As String(,)
If not connected Then
Connect()
End If
Dim Rand as New Random()
Dim strSQL As String
Dim ID_Max As Integer
Dim Results(num_records,fields.Length) As String
strSQL = "SELECT COUNT(*) FROM " & table
dbcomm = New OleDbCommand(strSQL,dbconn)
ID_Max = dbcomm.ExecuteScalar()
Dim i As Integer
For i=0 To num_records-1
Do
Dim Rand_ID As Integer = Rand.Next(1,ID_Max)
Dim j As Integer
strSQL = "SELECT " ' strSQL begin
For j = 0 To fields.Length-1
If(j <> 0) Then
strSQL &= ", "
End If
strSQL &= fields(j)
Next
strSQL &= " FROM " & table & " WHERE ID = " & Rand_ID ' strSQL end
dbcomm = New OleDbCommand(strSQL,dbconn)
dbread = dbcomm.ExecuteReader()
dbread.Read()
For j = 0 To fields.Length-1
Results(i,j) = dbread.GetString(j)
Next
Loop Until dbread.GetString(0) <> ""
Next
Return Results
End Function
I don't get any problem IN this function, but i get one ("BC30201: Expression expected.") when i call it (in Page_Load event)
Sub Page_Load
Dim Rand_Records As String(,)
Rand_Records = GetRndRecords("Autore",{"ID","Nome"},PossibleAnswers-1)
End Sub
I even tried this, with the same result
Sub Page_Load
Dim Rand_Records As String(,)
Rand_Records = new String({"ID1","Nome1"},{"ID2","Nome2"},{"ID3","Nome3"})
End Sub
Can anyone explain me why?

ASP Classic searching multiple

Question: anyone have multiple searching coding using asp ? Can you share?
This is what I want to do..
There are 3 option or searching..by name, by location, by region
For the first display all data with paging..on top it has searching.
<textfield>name</textfield><list/menu>location</list/menu><list/menu>region</list/menu>
when search by region it will display all region are selected.
Then it allow to filter by name to get specific
<%
Dim adoCon
Dim rsGuestbook
Dim strSQL
Dim lngRecordNo
lngRecordNo = CLng(Request.QueryString("ID"))
Set rsGuestbook = Server.CreateObject("ADODB.Recordset")
'Initialise the strSQL variable with an SQL statement to query the database'
strSQL = "SELECT * FROM tbl_Master WHERE ID=" & lngRecordNo
rsGuestbook.Open strSQL, oConn
%>
Here is a querystring search be name,department,age. It works properly. It might help you. Just fetch your values. Put those in proper places. And don't forget to change your tablename
name1=request.QueryString("name")
dept1=request.QueryString("dept")
age1=request.QueryString("age")
sqlStr="Select * from Student_Entry"
sqlWhere=""
if name1<>"" then
sqlWhere = " Where S_name='"&name1&"'"
end if
if dept1<>"" then
if sqlWhere = "" then
sqlWhere = " Where S_dept='"&dept1&"'"
else
sqlWhere = sqlWhere&" And S_dept='"&dept1&"'"
end if
end if
if age1<>"" then
if sqlWhere = "" then
'sqlWhere = " Where S_age="&age1&""
sqlWhere = " Where S_age"&agestr&age1
else
'sqlWhere = sqlWhere&" And S_age="&age1&""
sqlWhere =sqlWhere&" And S_age"&agestr&age1
end if
end if
sqlStr = sqlStr & sqlWhere
it sounds like you are describing multiple dependent lists (?)
there is an example here with demo:
http://www.aspkey.net/aspkey/_articles/asp/showarticle.asp?id=100
strname , strlocation and strregion value will depend on selection if not select then default value will be "".
strSQL = "SELECT * FROM tbl_Master WHERE ID=" & lngRecordNo
if strname <> "" THEN
strSQL = strSQL & " and name ='"& strname &"' "
END IF
if strlocation <> "" THEN
strSQL = strSQL & " and location='"& strlocation &"'
END IF
if strregion <> "" THEN
strSQL = strSQL & " and region='"& strregion &"'
END IF
rsGuestbook.Open strSQL, oConn

Resources