How to show result based on matching keywords count in descending order - sql-server-2005

I want to show result based on highest matching keywords in descending order.
Below code shows result but not sorted in descending order.
Please help me to resolve this issue as I don't want to use full text index.
My code is as follows:
<%
Dim SearchWord, arrKeyWords, Cnt, tsearch, i
SearchWord = Trim(request("searcha"))
SearchWord = Replace(SearchWord, " and ", " ")
SearchWord = Replace(SearchWord, " in ", " ")
SearchWord = Replace(SearchWord, " or ", " ")
arrKeyWords = Split(SearchWord ," ")
%>
<%
If IsArray(arrKeyWords) Then
For i = 0 To (UBound(arrKeyWords)-1)
Dim objRSsg, objCmdsg, strsg
Set objCmdsg = Server.CreateObject("ADODB.Command")
Set objRSsg = Server.CreateObject("ADODB.Recordset")
Dim countItem, numPerPage, page, totalpages, totalRecs
countItem = 0
numPerPage = 50
objRSsg.cursorlocation = 3
If request("page") = "" Then
page = 1
Else
page = CLng(request("page"))
End If
strsg = "select rProd_name, r_id from reseller_prod " & _
"where rProd_name LIKE '%' + ? + '%' " & _
"union " & _
"select Prod_name, '' as r_id from product " & _
"where Prod_name LIKE '%' + ? + '%'"
With objCmdsg
.ActiveConnection = MM_connDUdirectory_STRING
.CommandText = strsg
.CommandType = adCmdText
.Parameters.Append(.CreateParameter("#sa1", adVarChar, adParamInput, 1000))
.Parameters.Append(.CreateParameter("#sa2", adVarChar, adParamInput, 1000))
.Parameters.Append(.CreateParameter("#sa3", adVarChar, adParamInput, 1000))
.Parameters.Append(.CreateParameter("#sa4", adVarChar, adParamInput, 1000))
.Parameters("#sa1").Value = arrKeyWords(i)
.Parameters("#sa2").Value = arrKeyWords(i)
.Parameters("#sa3").Value = arrKeyWords(i)
.Parameters("#sa4").Value = arrKeyWords(i)
End With
objRSsg.Open objCmdsg, , 1, 2
Next
End If
...
...
%>

Related

CSQL code in vb6 for displaying data between two dates?

Set COUNTER_RS = New Recordset
COUNTER_RS.Open "Select * from TT_COUNTER where Trans_dt >'" + Format(mskFdate.Text, "mm-dd-yyyy") + "' and Trans_dt <='" + Format(mskTdate.Text, "mm-dd-yyyy") + "' and Receipt_No like 'A%' and Head_Details='MED' order by Receipt_No", db, adOpenStatic, adLockOptimistic
MEDI = 0
If COUNTER_RS.RecordCount > 0 Then
While COUNTER_RS.EOF = False
MEDI = Val(COUNTER_RS!Rate)
COUNTER_RS.MoveNext
Wend
End If
Cant find the correct amount between two dates, please help with the code?

SQL Syntax error, expression of non-boolean type

This code is supposed to create a graph of revenue from money made through sales tickets at an event.
The code only executes up to da.Fill(ds) when it returns the error, which can be seen at the end of the code.
Does anybody know why
Private Sub frmRevenue_Load(sender As Object, e As EventArgs) Handles Me.Load
frmMDI.addFormToCMS()
Dim dt As DataTable
dt = New DataTable
dt.Columns.Add("Fee")
Dim sales As Integer = 0
Dim gridtable As New DataTable
gridtable.Columns.Add("Month")
gridtable.Columns.Add("Total")
gridtable.Columns.Add("#")
For i = 1 To 12
sql = "SELECT Fee FROM tblTickets WHERE MONTH(DatePurchased) = " & i & " AND (YEAR(DatePurchased) = " & Today.Year & " OR " & Year(Today.AddYears(1)) & ") AND (Status = 'SOLD' OR RESERVED" _
& " = 'AWAITING CONFIRMATION' OR Status = 'AVAILABLE' OR Status = 'AWAITING PAYMENT');"
da = New OleDb.OleDbDataAdapter(sql, con)
ds = New DataSet
da.Fill(ds)
Dim dr As DataRow
For Each dr In ds.Tables(0).Rows
monthly(i) = monthly(i) + 1
contracts = sales + 1
total(i) = total(i) + dr.Item("Fee")
yearlytotal = yearlytotal + dr.Item("Fee")
Next
Next
For i = 1 To 12
Dim month As String
Select Case i
Case 1
month = "Jan"
Case 2
month = "Feb"
Case 3
month = "Mar"
Case 4
month = "Apr"
Case 5
month = "May"
Case 6
month = "Jun"
Case 7
month = "Jul"
Case 8
month = "Aug"
Case 9
month = "Sep"
Case 10
month = "Oct"
Case 11
month = "Nov"
Case 12
month = "Dec"
Case Else
month = "ERR"
End Select
gridtable.Rows.Add(month, FormatCurrency(total(i)), monthly(i))
Next
ugTickets.DataSource = gridtable
ugTickets.DisplayLayout.Bands(0).Columns("Month").Width = 35
ugTickets.DisplayLayout.Bands(0).Columns("#").Width = 20
ugTickets.DisplayLayout.Override.AllowUpdate = DefaultableBoolean.False
txtAnnual.ReadOnly = True
txtAnnual.BackColor = Color.White
txtAnnualContracts.ReadOnly = True
txtAnnualContracts.BackColor = Color.White
chRevenue.Titles("chTitle").Text = "Predicted revenue for " & Today.Year & " - " & Year(Today.AddYears(1))
txtAnnual.Text = FormatCurrency(yearlytotal, 2)
txtAnnualContracts.Text = contracts
chRevenue.Series("Series1").Name = "Revenue"
For i = 1 To 12
chRevenue.Series("Revenue").Points.AddY(total(i))
Next
Try
chRevenue.BackColor = Color.Transparent
chRevenue.Legends("Revenue").BackColor = Color.Transparent
chRevenue.Series("Revenue").ChartArea = "ChartArea1"
chRevenue.Series("Revenue").Color = Color.SkyBlue
chRevenue.Series("Revenue").ToolTip = FormatCurrency("#VALY", 2)
Catch
End Try
End Sub
An expression of non-boolean type specified in a context where a condition is expected, near ')'.
The problem is with this bit of the SQL:
(YEAR(DatePurchased) = " & Today.Year & " OR " & Year(Today.AddYears(1)) & ")
It should probably be
(YEAR(DatePurchased) = " & Today.Year & " OR YEAR(DatePurchased) = " & Year(Today.AddYears(1)) & ")
The OR in SQL (and in most other languages) needs to have two independently valid conditions on each side. The left hand side currently looks like this:
YEAR(DatePurchased) = 2016
...which is fine. But the right looks like this:
2017
...which isn't a valid boolean.
When you get an error like this on the da.Fill() line (ie. the line that's actually running the SQL in the database), the easiest way to debug it is to print out the value of the "sql" variable.
Often, you can just look at the SQL it's generated and the problem will be obvious. Other times you have to copy it and run it directly against your database to see what the problem is.
Might be your SQL, try:
"SELECT Fee FROM tblTickets WHERE MONTH(DatePurchased) = '" & i &
"' AND (YEAR(DatePurchased) = '" & Today.Year &
"' OR '" & Year(Today.AddYears(1)) & "') " &
"AND (Status = 'SOLD' OR RESERVED = 'AWAITING CONFIRMATION' " &
"OR Status = 'AVAILABLE' " &
"OR Status = 'AWAITING PAYMENT');"

vb.net implict inner join syntax error (missing operator) in query expression

This is the code where I am getting exception message. However this code worked perfect in sql server 2005 but generating error in access.
This code working fine in sql server project but in access its generating exception as I mentioned..
Public Function CalculateFeeReciept(ByVal monthid As Integer) As DataTable
Dim cmd1 As New OleDbCommand("Select * from mstFeeHead", sqlcon)
Dim dtmstFeeHead As New DataTable 'dtmstFeeHead contains all the fee heads id's
Dim adp1 As New OleDbDataAdapter(cmd1)
adp1.Fill(dtmstFeeHead)
cmd1.Dispose()
Dim selectedmonth As Integer
Dim feeheadid As Integer
Dim arr(25) As Integer 'arr contains Fee head id's that should be paid in the selected month
If monthid = 13 Then
monthid = 1
ElseIf monthid = 14 Then
monthid = 2
ElseIf monthid = 15 Then
monthid = 3
End If
selectedmonth = monthid + 3
Dim m As Integer = 0
For j As Integer = 0 To dtmstFeeHead.Rows.Count - 1
feeheadid = Convert.ToInt32(dtmstFeeHead.Rows(j)(0))
If dtmstFeeHead.Rows(j)(selectedmonth) Then
arr(m) = feeheadid
m = m + 1
End If
Next
Dim cmd2 As New OleDbCommand("SELECT txnStudentFeeHead.FeeHeadID, mstFeeHead.FeeHeadName, mstFeePlan.Amount " & _
"FROM " & _
"txnStudentFeeHead " & _
"INNER JOIN " & _
"mstFeeHead " & _
"ON " & _
"txnStudentFeeHead.FeeHeadID = mstFeeHead.FeeHeadID " & _
"INNER JOIN " & _
"mstFeePlan " & _
"ON " & _
"mstFeeHead.FeeHeadID = mstFeePlan.FeeHeadID " & _
"WHERE " & _
"txnStudentFeeHead.StudentID = #StudentID) " & _
"AND " & _
"(mstFeePlan.SessionID = #SessionID) " & _
"AND " & _
"(mstFeePlan.ClassID = #ClassID) ", sqlcon)
cmd2.CommandType = CommandType.Text
cmd2.Parameters.Add("#StudentID", OleDbType.Integer).Value = StudentID()
cmd2.Parameters.Add("#ClassID", OleDbType.Integer).Value = Convert.ToInt32(cmbClass.SelectedValue)
cmd2.Parameters.Add("#SessionID", OleDbType.Integer).Value = Convert.ToInt32(cmbSession.SelectedValue)
Dim dt As New DataTable 'dt contains all the fee head id's that are alloted to the students
Dim adp As New OleDbDataAdapter(cmd2)
adp.Fill(dt)
cmd2.Dispose()
Dim dt2 As New DataTable 'dt2 contains all the fee head id's that are alloted to the student and that should be paid in that particular month
' dt2 contains the filtrate of dt and arr
dt2 = dt.Clone()
For i As Integer = 0 To arr.Length - 1
For j As Integer = 0 To dt.Rows.Count - 1
Dim dtrow As DataRow = dt2.NewRow()
If arr(i) = dt.Rows(j)(0) Then
dtrow(0) = arr(i)
dtrow(1) = dt.Rows(j)(1)
dtrow(2) = dt.Rows(j)(2)
dt2.Rows.Add(dtrow)
End If
Next
Next
cmd2 = New OleDbCommand("Select Sum(TotalFees) as TotalFees, Sum(LateFees) as TotalLateFees, Sum(OldBalance) as TotalOldBalance, Sum(Discount) as TotalDiscount, Sum(Scholarship) as TotalScholarship, Sum(Concession) as TotalConcession, Sum(AmountReceived) as TotalAmountReceived from txnFeePayment where SessionID=#SessionID and StudentID=#studentid and MonthID=#monthid Group by StudentId,MonthID", sqlcon)
cmd2.CommandType = CommandType.Text
cmd2.Parameters.Add("#studentid", OleDbType.Integer).Value = StudentID()
cmd2.Parameters.Add("#SessionID", OleDbType.Integer).Value = cmbSession.SelectedValue
cmd2.Parameters.Add("#monthid", OleDbType.Integer).Value = monthid
Dim dtStudentReciept As New DataTable 'dt contains all the fee head id's that are alloted to the students
adp = New OleDbDataAdapter(cmd2)
adp.Fill(dtStudentReciept)
cmd2.Dispose()
Dim dtrow1 As DataRow = dt2.NewRow()
If (dtStudentReciept.Rows.Count > 0) Then
dtrow1(0) = 0
dtrow1(1) = "Total Late Fees"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(1))
dt2.Rows.Add(dtrow1)
dtrow1 = dt2.NewRow()
dtrow1(0) = 0
dtrow1(1) = "Total Discount"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(3)) * -1
dt2.Rows.Add(dtrow1)
dtrow1 = dt2.NewRow()
dtrow1(0) = 0
dtrow1(1) = "Total Scholarship"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(4)) * -1
dt2.Rows.Add(dtrow1)
dtrow1 = dt2.NewRow()
dtrow1(0) = 0
dtrow1(1) = "Total Concession"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(5)) * -1
dt2.Rows.Add(dtrow1)
dtrow1 = dt2.NewRow()
dtrow1(0) = 0
dtrow1(1) = "Total Amount Received"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(6)) * -1
dt2.Rows.Add(dtrow1)
Dim totalamount As Integer = 0
For k As Integer = 0 To dt2.Rows.Count - 1
totalamount = totalamount + dt2.Rows(k)(2)
Next
'dtrow1 = dt2.NewRow()
'dtrow1(0) = totalamount
'dtrow1(1) = "Current Month Fee"
'dtrow1(2) = totalamount
'dt2.Rows.Add(dtrow1)
Else
Dim totalamount As Integer = 0
For k As Integer = 0 To dt2.Rows.Count - 1
totalamount = totalamount + dt2.Rows(k)(2)
Next
'dtrow1 = dt2.NewRow()
'dtrow1(0) = totalamount
'dtrow1(1) = "Current Month Fee"
'dtrow1(2) = totalamount
'dt2.Rows.Add(dtrow1)
End If
dgvDisplay.DataSource = dt2
For i As Integer = 0 To dgvDisplay.Columns.Count - 1
dgvDisplay.Columns.Item(i).SortMode = DataGridViewColumnSortMode.NotSortable
dgvDisplay.Columns(2).Width = 65
dgvDisplay.Columns(1).Width = 132
Next
dgvDisplay.Columns.Item(0).Visible = False
'txtTotalFees.Text = dt2.Rows(dt2.Rows.Count - 1)(0)
Return dt2
End Function
There are a couple of things wrong with your query.
You havent left any spaces once a line in code is finished and whole query may look like they are separate lines but it is a one long string without any spaces.
I have added spaces in the following piece of code at the end of each line.
("SELECT [txnStudentFeeHead].[FeeHeadID],[mstFeeHead].[FeeHeadName]," & _
"[mstFeePlan].[Amount] " & _
"FROM " & _
"[txnStudentFeeHead] " & _
"INNER JOIN " & _
"[mstFeeHead] " & _
You have put your variables in sqaure brackets [] , which means SQL Server will treat them as SQL Server Object(table name, Column Name) names and not as Variables. Remove the Square brackets.
"WHERE " & _
"([txnStudentFeeHead].[StudentID] = #StudentID) " & _
"AND" & _
"([mstFeePlan].[SessionID] = #SessionID) " & _
"AND" & _
"([mstFeePlan].[ClassID] = #ClassID) ", sqlcon)
Solved it myself by long time of effort and headache
Dim cmd2 As New OleDbCommand("SELECT txnStudentFeeHead.FeeHeadID, mstFeeHead.FeeHeadName, mstFeePlan.Amount, txnStudentFeeHead.StudentID, mstFeePlan.ClassID, mstFeePlan.SessionID FROM (txnStudentFeeHead INNER JOIN mstFeeHead ON txnStudentFeeHead.FeeHeadID = mstFeeHead.FeeHeadID) INNER JOIN mstFeePlan ON mstFeeHead.FeeHeadID = mstFeePlan.FeeHeadID WHERE (((txnStudentFeeHead.StudentID)=#StudentID) AND ((mstFeePlan.ClassID)=#ClassID) AND ((mstFeePlan.SessionID)=#SessionID))", sqlcon)
cmd2.CommandType = CommandType.Text
cmd2.Parameters.Add("#StudentID", OleDbType.Integer).Value = StudentID()
cmd2.Parameters.Add("#ClassID", OleDbType.Integer).Value = Convert.ToInt32(cmbClass.SelectedValue)
cmd2.Parameters.Add("#SessionID", OleDbType.Integer).Value = Convert.ToInt32(cmbSession.SelectedValue)
Dim dt As New DataTable 'dt contains all the fee head id's that are alloted to the students
Dim adp As New OleDbDataAdapter(cmd2)
adp.Fill(dt)
cmd2.Dispose()

vb.net - using case select query in sql for jtable

If anyone knows how to use case in query for jtable, pls take a look my code.
Dim batch_status As String = " case when status = 0 then 'Created' when status = 1 then 'Scanning' when status = 2 then 'Scan Saved' end as status"
cmd.CommandText = "SELECT * FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY " & jtSorting & " ) AS RowNum, batch_id, batch_name, date_created, profile_id, total_page, " & batch_status & ", First_ScanID, file_id " & _
" FROM [ip_ent_site].[dbo].[tbl_batch] WHERE STATUS IN (0,1,2) ) AS RowConstrainedResult " & _
" WHERE RowNum >= #jtStartIndex AND RowNum < #jtEndIndex ORDER BY RowNum ; "
if i use like this, it is working:
Dim batch_status As String = "status"
but with case, not.
whats problem here?
another part of code:
If dt.Rows.Count > 0 Then
students = (From item In dt.AsEnumerable() Select New Class1 With { _
.No = Convert.ToInt32(item(1)), _
.batch_id = Convert.ToInt64(item(2)), _
.batch_name = DirectCast(item(3), String), _
.date_created = item(4).ToString, _
.profile_id = Convert.ToInt32(item(5)), _
.total_page = Convert.ToInt32(item(6)), _
.status = Convert.ToInt32(item(7)), _
.First_ScanID = Convert.ToInt32(item(8)), _
.file_id = CheckDBNullInteger(item(9)) _
}).ToList()
End If
Use your declare statement like below.
Dim batch_status As String = " case when status = 0 then ''Created'' when status = 1 then ''Scanning'' when status = 2 then ''Scan Saved'' end as status"
may be the problem with #jtStartIndex AND #jtEndIndex.
Just found, change .status = Convert.ToInt32(item(7)) to .status = item(7).ToString,
displaying in Jtable is quite different

How to make stored procedure in if..End if condition

I am beginner at stored procedures. I tried the following stored procedure in IF...End If condition so how to make it ... I am confused.... so anyone create it
strSql = "SELECT count(*) " & _
" FROM hist_billgen_report r, hist_billgen_header h " & _
" WHERE r.invoice_number=h.invoice_number " & _
" and h.macnum = '" & l_macnum & "' " & _
" and r.rep_type = 1 " & _
" and r.rep_call_type = '" & line_type & "' " & _
" and h.billing_job_id = '" & arg_job & "' "
'Special code for data lines for Newcore
If gcompany = "NCW" Then
strSql += " and r.rep_number not in ( "
strSql += "select distinct a.mdn from order_wireless a where"
strSql += " a.id in"
strSql += " ("
strSql += " select c.serviceid from cust_charge_file b, service_charges c, main_company_utilities d"
strSql += " where(b.chg_main_index = c.chargeid)"
strSql += " and c.serviceid = a.id"
strSql += " and (b.chg_main_category_id = d.utilities_id and d.utilities_type = 'CS' and (utilities_desc_short like '%FDS1%' or utilities_desc_short like '%FDS2%' or utilities_desc_short like '%FDS3%' or utilities_desc_short like '%MBS1%' or utilities_desc_short like '%MBS2%' or utilities_desc_short like '%MBS3%' ) )"
strSql += " )"
strSql += " and a.accountnumber = '" & l_macnum & "' "
strSql += " )"
End If
Putting a query into a stored procedure doesn't necessarily always mean a performance increase. Depending on the data in your tables, this query could be quite slow due to the OR LIKES '%%' in it, but you could do something like this:
create procedure [dbo].[spname]
#l_macNum int -- note, you haven't given a lot of information, create all query parameters with appropriate types here
-- more parameters
#arg_job int -- same
AS
BEGIN
if (#company = 'NCW')
begin
SELECT count(*)
FROM hist_billgen_report r, hist_billgen_header h
WHERE r.invoice_number=h.invoice_number
and h.macnum = #l_macNum
-- etc
and r.rep_number not in (
-- etc
)
end
else
begin
SELECT count(*)
FROM hist_billgen_report r, hist_billgen_header h
WHERE r.invoice_number=h.invoice_number
and h.macnum = #l_macNum
-- etc
end
END
GO
note the If and else logic are completely separate queries, as you cannot do what I think you were hoping to do in a contiguous query, without using dynamic sql. there are certain caveats to this but given you're new to sql, going to stick with that
I used -- etc as place holders for your text, as I'm not going to provide the entire solution :P
If that doesn't make sense, let me know.