String Constant must End with double quote SQL report - sql

Below is the query for a sql report that I am completing in SQL Server Business Studio and I keep getting an error regarding the double quotes on this line Dim SelectClause as System.String = ""
I tried a few things but I get the repeating error.
Any help would be appreciated.
Function getSelectClause(ByVal startDate as DateTime, ByVal endDate as DateTime) as String
Dim SelectClause as System.String = ""
SelectClause ="SELECT Define.meterName, SUM(Reading.volume) AS [Total Volume], MIN(Reading.time) AS [Month]
FROM [Reading] INNER JOIN Define ON Reading.meterId = Define.meterId
WHERE (Reading.[time] >= " & startDate & " AND Reading.[time]< " & endDate & ")
AND Define.meterName IN ('007080')
AND (Reading.dataQuality = '11' OR
Reading.dataQuality = '10') AND (Reading.auditVersion = '0')
GROUP BY Define.meterName"
return SelectClause
End Function

SSRS uses VB as its language for custom functions, which has a different syntax that SQL. VB does not support multi-line statements like SQL does. You need to end each line with " + _ and begin the continuation with ", and change how you append the date strings :
Function getSelectClause(ByVal startDate as DateTime, ByVal endDate as DateTime) as String
Dim SelectClause as System.String = ""
SelectClause ="SELECT Define.meterName, SUM(Reading.volume) AS [Total Volume], " + _
" MIN(Reading.time) AS [Month]" + _
" FROM [Reading] INNER JOIN Define ON Reading.meterId = Define.meterId" + _
" WHERE (Reading.[time] >= '" + startDate + "' AND Reading.[time]< '" + endDate+ "')" + _
" AND Define.meterName IN ('007080')" + _
" AND (Reading.dataQuality = '11' OR " + _
" Reading.dataQuality = '10') AND (Reading.auditVersion = '0') " + _
" GROUP BY Define.meterName"
return SelectClause

Related

filter report based on date

I have a table with date column a query for the same table and a report, on my form I have a button which loads the report using vba code which is below, I have two text fields to filter date on the report, my issue is with the date it is not being filtered. my code is below
Public Function makeMWO_RPT(Optional excelMode As Boolean = False)
Dim ctlArr(3) As String
ctlArr(0) = "Combo79"
ctlArr(1) = "Combo82"
ctlArr(2) = "WOPRCO"
ctlArr(3) = "Combo165"
Dim fldArr(3) As String
fldArr(0) = "[Group]"
fldArr(1) = "[User status]"
fldArr(2) = "[Priority]"
fldArr(3) = "iif([orders].[User status] In (""Closed"",""Open""),""YES"",""NO"")"
'for date -- for date -- for date -- for date -- for date
Dim qDef, sqlStr, frm As Form
Set frm = Forms("Statusfrm")
Set qDef = CurrentDb.QueryDefs("OrderNewQry")
sqlStr = "SELECT orders.[Group], orders.Order, orders.Description,orders.Post_Form, orders.Attachment, orders.Video_link, orders.[Estimated costs], orders.[Total], orders.Location, orders.[System status], orders.Priority, orders.date, orders.[User status], " & _
"orders.Equipment, orders.Diff, orders.Remarks,[orders].[User status] In (""Closed *"",""Open *"") AS Completed
"FROM orders"
Dim filtrStr As String
If Not IsNull(frm("Text489")) Then
filtrStr = "[date] >= #" & frm("Text489") & "#"
End If
If Not IsNull(frm("Text491")) Then
filtrStr = filtrStr & " AND [date] <= #" & frm("Text491") & "#"
End If
If filtrStr <> "" Then
sqlStr = sqlStr & " WHERE " & filtrStr
End If
qDef.SQL = sqlStr
'for date -- for date -- for date -- for date -- for date
Dim baseSQL, qName, rName
baseSQL = "SELECT orders.[Group], orders.Order, orders.Description,orders.Post_Form, orders.Attachment, orders.Video_link, orders.[Estimated costs], orders.[Total], orders.Location, orders.[System status], orders.Priority, orders.date, orders.[User status], " & _
"orders.Equipment, orders.Diff, orders.Remarks,[orders].[User status] In (""Closed *"",""Open *"") AS Completed
"FROM orders"
qName = "OrderNewQry"
rName = "FUllOpenOrdersRpt"
makeGenericRPT ctlArr, fldArr, baseSQL, qName, rName, excelMode
End Function

VB 2010 INSERT INTO syntax error

Hello Good Afternoon I have a program in VB.Net that will Input data
from textboxes into Access Database here is sample image
This is the code I am using and it gives me an error
m = TextBox1.Text
b = "'" + TextBox2.Text + "'"
x = "'" + TextBox3.Text + "'"
d = TextBox4.Text
n = "'" + TextBox5.Text + "'"
Dim s2 As String
s2 = "insert into users2 ( num , name1 , pass , add , phone ) " & " values ( " + m + " , " + n + " , " + b + " , " + x + " , " + d + " ) "
Dim cmd2 As New OleDbCommand(s2, con)
cmd2.ExecuteNonQuery()
Looking forward that someone will enlighten my problem since its im starting to program.
TYSM for future help
You need to encapsulate values you want to insert into ''
. "values('" + m + "', '" + ...
2 I don't understand & operator between two parts of query in the beginning

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.

SQL unable to cast object of type 'system.string' to type 'system.iformatprovider' error in vb.net

I am trying to run this Query in my VB Application but receive an error saying:
unable to cast object of type 'system.string' to type 'system.iformatprovider'
SQL = "insert into billing_pdf_archive (reseller_sequence, invoice_number, pdf, worddoc, csv_cdr_file, csv_services_file, sub_total, vat_amount, grand_total, invoice_type, directdebit) values ('" + reseller.ToString + "','" + invoice_number.ToString + "', '" + Replace(reseller_company_name + "-" + invoice_number + ".pdf", " ", "_") + "', '" + Replace(reseller_company_name + "-" + invoice_number + ".doc", " ", "_") + "', '" + Replace(reseller_company_name + "-" + invoice_number.ToString + "_CDR.xlsx", " ", "_") + "', '" + Replace(reseller_company_name + "-" + invoice_number.ToString + "_Services.xlsx", " ", "_") + "', " + total.ToString("F2") + ", " + vat_amount.ToString("F2") + ", " + grand_total.ToString("F2") + ", 'Month End Reseller', '" + customer_direct_debit + "')"
conn3.ConnectionString = "server=" + global_variables.web_server_ip + "; user id=" + global_variables.web_server_username + "; password=" + global_variables.web_server_password + "; database=" + global_variables.web_server_database + "; "
conn3.Open()
myCommand3.Connection = conn3
myCommand3.CommandText = SQL
myCommand3.ExecuteNonQuery()
conn3.Close()
This is not a complete answer but I'll post it as an answer so that I can post formatted code. If you do as suggested in the comments and write clean, readable code then it will become obvious where the issue is and how to fix it. When you have one line that does lots of different things then working out what on that line is causing an issue is all but impossible. You should use an XML literal for your SQL code, parameters for your values and a connection string builder, e.g.
Dim sql = <sql>
INSERT INTO MyTable
(
Column1,
Column2
)
VALUES
(
#Column1,
#Column2
)
</sql>
command.CommandText = sql.Value
command.Parameters.AddWithValue("#Column1", value1)
command.Parameters.AddWithValue("#Column2", value2)
Dim builder As New SqlConnectionStringBuilder
builder.DataSource = server
builder.InitialCatalog = database
connection.ConnectionString = builder.ConnectionString
Now you'll be able to see exactly what part of your code is causing the issue and, if you still can't solve it yourself, will be able to point out where the issue is to us instead of expecting us to read that dog's breakfast.

Incredibly slow performance with this query

I am getting incredibly slow performance when executing this query,
i cannot see anything obvious,can any one suggest me the best way to get through it
CREATE TABLE #tmp_NominalPurchase (
NomCode varchar(16),
NomDesc varchar(61),
GoodsSold money
)
declare #Pos Int
select #Pos = 1
while #Pos <= (select max(dbo.fn_DCount(NValues,'~')) from pledger)
begin
INSERT INTO #tmp_NominalPurchase (NomCode, NomDesc, GoodsSold) (
select
a.keyCode NomCode,
a.descr NomDesc,
sum(convert(money, dbo.fn_Field(pl.NValues,'~', #Pos) )) GoodsSold
from pledger pl
inner join accts a
On dbo.fn_Field(pl.NCodes,'~', #Pos) = a.keycode
and (acctType='N' and pb='P' and category='cs')
where convert(datetime, pl.batch) >='2014-01-01'
and convert(datetime, pl.batch) <'2014-06-25'
group by a.keyCode, a.descr)
select #Pos = #Pos + 1
end
select o.* FROM
(
select t.NomCode,
t.NomDesc,
0 GoodsCost,
0 GoodsDisc,
sum(t.GoodsSold) GoodsSold,
'24/06/2014 05:01:14 PM' as LocalDateAndTime
from #tmp_NominalPurchase t
group by
t.NomCode,
t.NomDesc
) o
Order By o.NomCode Asc
DROP TABLE #tmp_NominalPurchase
One obvious thing I see is you are converting pl.batch to a string before you do the comparison in the where clause. That would defeat any indices that might prevent a table scan.
You are also doing a join on a user defined function fn_field. Not knowing the purpose of that function, I'm wondering if that is creating an issue. When I see things like that, I suspect it's there because the data schema isn't well thought out.
No rewritten query and performance has increased majorly, this has reduced the query runtime from 12 seconds to < 1 second
added a function to get the count
SQL rewritten to use the count
The Improved SQL
SELECT dbo.fn_Field(pl.NValues,'~',1) AS [nVals1], dbo.fn_Field(pl.Ncodes,'~',1) as [nCodes1], dbo.fn_Field(pl.NValues,'~',2) as [nVals2], dbo.fn_Field(pl.Ncodes,'~',2) as [nCodes2],
'x' AS x INTO #tmp_NominalPurchase
FROM pledger pl
WHERE convert(datetime, pl.batch) >='2014-06-01'
AND convert(datetime, pl.batch) <'2014-06-28'
SELECT a.keycode AS NomCode,
a.descr AS NomDesc,
max(0) AS goodsCost,
max(0) AS GoodsDisc,
sum(CAST (NValue AS money)) AS GoodsSold ,
'06/27/2014 11:44:47 AM' AS LocalDateAndTime
FROM
(SELECT [nVals1] AS NValue,[nCodes1] AS NCode
FROM dbo.#tmp_NominalPurchase tnp
UNION ALL SELECT [nVals2]AS NValue,[nCodes2] AS NCode
FROM dbo.#tmp_NominalPurchase tnp) x
INNER JOIN dbo.Accts a ON x.Ncode = a.keycode
AND acctType='N'
AND category='cs'
AND pb='P'
GROUP BY a.keycode,
a.descr
ORDER BY NomCode
DROP TABLE #tmp_NominalPurchase
Function to get count
Public Function getNCodeCount(ByVal sWhere) As Integer '00528591
Dim Ds As DataSet
Dim sqlSb As StringBuilder = New StringBuilder
Dim nCodesCount As Integer = 0
sqlSb.Append("SELECT isnull(max(dbo.fn_DCount(NValues,'~')),0) FROM PLEDGER PL with (nolock)" & sWhere)
Ds = SqlConnect.SqlNet.OpenSQLdataset(sqlSb.ToString)
If Ds Is Nothing Then GoTo report_failed
If Ds.Tables.Count < 1 Then
GoTo report_failed
End If
With Ds.Tables(0)
For Each r In .Rows
nCodesCount = r(0)
Next
End With
Return nCodesCount
Exit Function
report_failed:
Return 0
'00528591 END
End Function
Function to build the SQL string and output the report
Public Function LedgerNominalListingReportPurchase(ByVal DateFrom As String, ByVal DateTo As String, ByVal SortType As String, Optional ByVal DetailReport As Boolean = False, Optional ByVal NominalCode As String = "") As DataView 'L754303 (163.47)
Dim sql As String = ""
Dim gs As New GeneralSQL
Dim aWhere As New ArrayList
Dim sWhere As String = ""
If IsDate(DateFrom) Then aWhere.Add("convert(datetime, pl.batch) >=" & gs.SqlDate(CDate(DateFrom)))
If IsDate(DateTo) Then aWhere.Add("convert(datetime, pl.batch) <" & gs.SqlDate(CDate(DateTo).AddDays(1)))
For Each s As String In aWhere
If sWhere = "" Then
sWhere &= " where "
Else
sWhere &= " and "
End If
sWhere &= s
Next
If Not DetailReport Then 'L754303 (163.47)
'NEW SQL (FASTER) 00528591
sql &= "SELECT max(dbo.fn_DCount(NValues,'~')) FROM PLEDGER"
Dim nCodeCount As Integer = (getNCodeCount(sWhere))
If nCodeCount = Nothing Or 0 Then
sql = "CREATE TABLE #tmp_NominalPurchase (NomCode varchar(16), NomDesc varchar(61), GoodsCost money, GoodsDisc money, GoodsSold money) SELECT * FROM #tmp_NominalPurchase DROP TABLE #tmp_NominalPurchase"
Else
Dim qCount As Integer = 1
sql = "SELECT "
While qCount <= nCodeCount
sql &= "dbo.fn_Field(pl.NValues,'~'," + qCount.ToString
sql &= ") "
sql &= " as [nVals" + qCount.ToString
sql &= "], "
sql &= "dbo.fn_Field(pl.Ncodes,'~'," + qCount.ToString
sql &= ") "
sql &= " as [nCodes" + qCount.ToString
sql &= "], "
qCount += 1
End While
sql &= " 'x' as x "
sql &= "INTO #tmp_NominalPurchase FROM pledger pl " & sWhere
sql &= "SELECT a.keycode as NomCode, a.descr as NomDesc,max(0) AS goodsCost,max(0) AS GoodsDisc, sum(cast (NValue AS money) ) AS GoodsSold "
sql &= String.Format(", '{0}' as LocalDateAndTime", Format(General.UserNow, vars.Ses.FmtDate & " " & "hh:mm:ss tt")) 'V759658 (163.31) - format the date column based on the CountryMode setting
sql &= " FROM ("
sql &= "SELECT [nVals1] AS NValue,[nCodes1] AS NCode FROM dbo.#tmp_NominalPurchase tnp "
qCount = 2
While qCount <= nCodeCount
sql &= " UNION all "
sql &= "SELECT [nVals" + qCount.ToString
sql &= "]AS NValue,[nCodes" + qCount.ToString
sql &= "] AS NCode FROM dbo.#tmp_NominalPurchase tnp"
qCount += 1
End While
sql &= ") x inner join dbo.Accts a on x.Ncode = a.keycode and acctType='N' AND category='cs' AND pb='P' group by a.keycode,a.descr "
sql &= "ORDER BY " & SortType
sql &= " DROP TABLE #tmp_NominalPurchase"
End If
End If
Return SqlConnect.SqlNet.OpenSQLdataset(sql).Tables(0).DefaultView '00529265
End Function