Dim sql As String = "SELECT DISTINCT LED.IDX As IDX, CORPCODE, UNITTYPECODE, UPPERFORMATIONCODE, FORMATIONCODE, LED.UNITCODE As UNITCODE,LED.STORECODE As STORECODE, LED.SECTIONNO As SECTIONNO, LED.PARTNO As PARTNO, "
sql &= " LED.BATCHNO As BATCHNO, UNITITEMCATEGORYCODE, LEDGERDATE, ENTITLEMENT, HOLDING, SURPLUS, SHORTAGE, COSTHOLDING, COSTENTITLEMENT, INITIALSTOCK, EMPLOYQTY, FIGHTQTY, ITEMAGE1, ITEMAGE2, ITEMAGE3,"
sql &= " ITEMAGE4, LED.BAH_BEREK, LED.JENIS_BEREK, JPTD_NO, LASTUPDATE, LED.ITEMTYPECODE As ITEMTYPECODE, LED.TOOLTYPECODE As TOOLTYPECODE, LED.PAKAIBHGCODE, LED.PAKAICODE, ITEMNIDX, LED.CREATEID As CREATEID, "
sql &= " LED.UPDATEID As UPDATEID, LED.CREATEDATE As CREATEDATE, LED.UPDATEDATE As UPDATEDATE, "
sql &= " USERID, RANKCODE, SERVICENO, USERNAME, DESIGNATIONCODE, PASSWORD, "
sql &= " 'OPER' AS GROUPCODE,5 AS ACESSID, 0 AS STATUS "
sql &= " FROM (LEDGER AS LED) "
sql &= " LEFT JOIN NUSER On NUSER.USERID = LED.UPDATEID WHERE (1=1) "
If condation <> "" Then
sql += condation
End If
sql &= " UNION SELECT DISTINCT LED.IDX As IDX, CORPCODE, UNITTYPECODE, UPPERFORMATIONCODE, FORMATIONCODE, LED.UNITCODE As UNITCODE, LED.STORECODE As STORECODE, LED.SECTIONNO As SECTIONNO, LED.PARTNO As PARTNO, "
sql &= " LED.BATCHNO As BATCHNO, UNITITEMCATEGORYCODE, LEDGERDATE, ENTITLEMENT, HOLDING, SURPLUS, SHORTAGE, COSTHOLDING, COSTENTITLEMENT, INITIALSTOCK, EMPLOYQTY, FIGHTQTY, ITEMAGE1, ITEMAGE2, ITEMAGE3,"
sql &= " ITEMAGE4, LED.BAH_BEREK, LED.JENIS_BEREK, JPTD_NO, LASTUPDATE, LED.ITEMTYPECODE As ITEMTYPECODE, LED.TOOLTYPECODE As TOOLTYPECODE, LED.PAKAIBHGCODE, LED.PAKAICODE, ITEMNIDX, LED.CREATEID As CREATEID, "
sql &= " LED.UPDATEID As UPDATEID, LED.CREATEDATE As CREATEDATE, LED.UPDATEDATE As UPDATEDATE,"
sql &= " ('' AS USERID), ('' AS RANKCODE),('' AS SERVICENO),('' AS USERNAME),('' AS DESIGNATIONCODE), ('' AS PASSWORD), 'OPER',5 , STATUS "
sql &= " FROM LEDGER_HISTORY LED WHERE (1=1) "
error is Syntax error (missing operator) in query expression '('' AS USERID)'.
Can anyone help me to solve this
The error is correct. The problem is the parentheses.
This syntax is not appropriate for SQL:
SELECT ('' AS USERID)
However, this is:
SELECT ('') AS USERID
Or just:
SELECT '' AS USERID
You have the same problem with FROM (LEDGER AS LED).
Related
I'm currently trying to exclude a comment that has the words "Not Issue" but for some reason it is partially working. When I remove the code below, I get 100 values, but when I add the syntax below it returns 50, but of those 50 fields, there are still some rows that contain "Not Issue".
INSERT INTO Combined_Comments ( [ID], [Comment] )
SELECT [Comments_001].[ID], IIf([Comments]<>" ","BR
#" & [Branch Number] & " - " & [Comments],[Comments]) AS [Dup Comment]
FROM [Comments_001]
WHERE ((Not (IIf([Comments]<>" ","BR #" & [Branch Number] & " - " & [Comments],[Comments]))<>"%not issue%") AND (([Dup Vin Comments_085].[Dup Ind])<>" "));
In MS Access, the like wildcard symbol is '*' while in SQL Server it is '%' so your sql in your query should be:
INSERT INTO Combined_Comments ( [ID], [Comment] )
SELECT [Comments_001].[ID], IIf([Comments]<>" ","BR
#" & [Branch Number] & " - " & [Comments],[Comments]) AS [Dup Comment]
FROM [Comments_001]
WHERE ((Not (IIf([Comments]<>" ","BR #" & [Branch Number] & " - " & [Comments],[Comments])) not like "*not issue*") AND (([Dup Vin Comments_085].[Dup Ind])<>" "));
I see a lot of "not" operators and assume the double negatives give you what you need.
Hello, I'm getting a syntax error on this sql statement, can anyone advise thanks
String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
"FROM tblStudent LEFT JOIN tblSchool " +
"ON (tblStudent.schoolID = tblSchool.schoolID) " +
"LEFT JOIN tblAgents " +
"ON (tblStudent.agentID = tblAgents.agentID) " +
"WHERE tblStudent.StudentID='" + studentID + "'";
I was hoping that I could do multiple joins
But I am getting a syntax error.
For access, parenthesis with multiple joins means the following. If you have three joins, there are two left parenthesis after the from. The last join does not have a right parenthesis.
String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
"FROM (tblStudent LEFT JOIN tblSchool " +
"ON (tblStudent.schoolID = tblSchool.schoolID)) " +
"LEFT JOIN tblAgents " +
"ON (tblStudent.agentID = tblAgents.agentID) " +
"WHERE tblStudent.StudentID='" + studentID + "'";
Access SQL injection has been covered in other threads .
String sql = "Select
tblStudent.StudentID,tblStudent.studentFirstName,"+
tblStudent.studentLastName,tblSchool.schoolName," +
tblAgents.agentFirstName,tblAgents.agentLastName " +
"FROM (tblStudent LEFT JOIN tblSchool " +
"ON (tblStudent.schoolID = tblSchool.schoolID)) " +
"LEFT JOIN tblAgents " +
"ON (tblStudent.agentID = tblAgents.agentID) " +
"WHERE tblStudent.StudentID=#studentID";
I believe your final SQL should look like this:
SELECT tblStudent.*
,tblSchool.*
,tblAgents.*
FROM tblSchool
RIGHT JOIN (
tblAgents RIGHT JOIN tblStudent ON tblAgents.agentID = tblStudent.agentID
) ON tblSchool.schoolID = tblStudent.schoolID
WHERE tblStudent.StudentID=111;
So, the VBA code for creating this SQL should be
Dim sql As String
sql = "SELECT tblStudent.* ,tblSchool.* ,tblAgents.* " & _
"FROM tblSchool RIGHT JOIN (" & _
"tblAgents RIGHT JOIN tblStudent ON tblAgents.agentID = tblStudent.agentID" & _
") ON tblSchool.schoolID = tblStudent.schoolID " & _
"WHERE tblStudent.StudentID=" & studentID
Here I assume that studentID is numeric field. Also I would recommend to do not use * for selecting the data from more than one table, otherwise column names may be unpredictable and as mentioned in comments, it will require additional resources, which won't be used.
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.
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
I started off with SQL (access)
IIf(Len([CAT]) < 3,
Left([CAT],1) & 0 & Right([CAT],1),
[CAT]) AS CAT1,
[HD0] &
IIf([TABLE].[HD1]<>"00",
" / " & [HD1_ABR],
Null) &
IIf([HD2]<>"00",
" / " & [HD2_NAME],
Null) &
IIf([HD3]<>"000",
" / " & [HD3_NAME],
Null) &
IIf([HD4]<>"00",
" / " & [HD4_NAME]) AS NAME,
and did Oracle (Sql Developer)
Case
When length(cat) < 3
Then SubStr(cat,1,1) || '0' || SubStr(cat,-1,1)
Else cat
End cat1,hd0
Case
When TABLE <>"00"
then " / "
else HD1_ABR,null
When I run query in SQLDev I get error
Error at Command Line:9 Column:4
Error report:
SQL Error: ORA-00923: FROM keyword not found where expected
00923. 00000 - "FROM keyword not found where expected"
MS Access syntax is entirely different to Oracle syntax. No square brackets, and different names for the SQL functions. http://docs.oracle.com/cd/E11882_01/server.112/e17118/functions.htm#SQLRF006
Case
When length(cat) < 3
Then SubStr(cat,1,1) || '0' || SubStr(cat,-1,1)
Else cat
End cat1