Incorrect syntax near the keyword 'FROM' and 'AS' - c#

string sqlQueryString = " SELECT g.code AS GoodCode, g.name AS GoodName, " +
"msr.name AS MsrName, sm.min_quan AS KolMin, sm.max_quan AS KolMax, " +
"sm.quan AS KolNal, ord.prc AS EdPrice, s.name AS Sklad, m.name AS Mol, " +
"k.code AS KodDost, k.name AS NameDost " +
"FROM N_GOODS_{0} AS g INNER JOIN " +
"G_SMGS_{0} AS sm ON g.id = sm.good_id INNER JOIN " +
"N_KNTRS_{0} AS k ON g.id = k.id INNER JOIN " +
"N_PRC_LISTS_{0} AS pr ON g.id = pr.id INNER JOIN " +
"G_ORDD_{0} AS ord ON sm.smg_id = ord.smg_id INNER JOIN " +
"N_MOLS_{0} AS m ON sm.mol_id = m.id INNER JOIN " +
"N_STORS_{0} AS s ON sm.stor_id = s.id INNER JOIN " +
"N_MSRS_{0} AS msr ON g.id = m.id";
sqlQueryString = String.Format(sqlQueryString, dbLink.CurrentFirm.Id);
return " ( " + sqlQueryString + " ) AS t";
This is the string for an sql query, that I am trying to do in a piece of c# code. However I lost my whole day trying to make it work. This is the error that I get :
Incorrect syntax near the keyword 'FROM'.
Incorrect syntax near the keyword 'AS'.

Try:
return "SELECT * FROM ( " + sqlQueryString + " ) AS t";
Additionally you should try setting a breakpoint on your return statement. Get the value of sqlQueryString there and try running it directly in SQL Server Management Studio.

First, this probably isn't a C# question except to say that you should likely learn the...
string strSql = #"SELECT *
FROM TABLE";
syntax so that 1.) You can do away with all the " + stuff and 2.) You can cut and paste something in from an isql client.
So what you really want to do is...
Debug in your IDE by setting a breakpoint at that last line,
Hover your cursor over sqlQueryString,
Right-click sqlQueryString in the "floater" that appears (I put my mouse over strReturn, the floater comes up. Right click the strReturn that appears floating above -- blue rectangle is what you want)
Select the option to copy the value.
Paste your clipboard with sqlQueryString's contents into Notepad, gvim, whatever.
Let us know what that says.
Then tell us precisely what happens when you run that statement directly against the database.
You might also give us some idea of what you expected to happen [based on having run the original query against the database earlier, perhaps].
And then accept that even the best of us occasionally lose an hour or two doing something dumb with SQL. ;^) With the above information, however, we could probably help cut that down a bit.
EDIT: Rather, if, as your comment suggests, the query works when run directly against (MS-SQL Server?), the C# issue potentially comes after this code, when you run it against the database. First do the above and ensure what's in sqlQueryString is what you ran against the db.
EDIT2: Made the debug steps into a bulleted list to make them more obvious. Don't just tell us it work; tell us what was in sqlQueryString. But, again, as with the first edit, if that string is okay, your problem likely occurs later on in your C# code.
Are you immediately throwing against the database? What's that code look like?

Looks like the problem is in the return statement at the end.
( SELECT foo FROM bar ) AS baz; is not a valid SQL statement by itself, it's a fragment.
As #Yuck suggests, try SELECT * FROM ( " + sqlQueryString + " ) AS t"; instead.

Related

SQL statement that only fetches the newest department which has been allocated

In my database i have the following rows and columns: https://i.imgur.com/ktUZY9d.jpg
My problem is the same employee has 3 different departments, but he is currently only active in 1. How do I change this SQL statement to only include the latest department he is in, which started in 2018 and ends in 2100, as seen by the ALLOCATION_START and ALLOCATION_END?
Query
string agentIdSubQuery = "SELECT DISTINCT " +
"AGENT_ID " +
"FROM " +
"KS_DRIFT.V_AGENT_ALLOCATION " +
"WHERE " +
"LENGTH(AGENT_INITIALS) < 5";
if(queryParams.SnapshotDate.HasValue)
agentIdSubQuery += " AND " + OracleConversion.ToOracleDate(queryParams.SnapshotDate) + " BETWEEN ALLOCATION_START AND ALLOCATION_END";
Update:
Tried alot of different solutions, but it crashes everytime, when i run through the debugger, further Down in this method this Query is causing me to crash:
string sql = "SELECT " +
"age1.* " +
"FROM " +
"KS_DRIFT.V_AGENT_ALLOCATION age1 " +
"INNER JOIN " +
"(" + agentIdSubQuery + ") age2 ON age1.AGENT_ID = age2.AGENT_ID " +
"ORDER BY " +
"AGENT_INITIALS";
Error Message:
{"Error occured during execution of SQL query: SELECT age1.* FROM KS_DRIFT.V_AGENT_ALLOCATION age1 INNER JOIN (SELECT max(DISTINCT AGENT_ID FROM KS_DRIFT.V_AGENT_ALLOCATION WHERE LENGTH(AGENT_INITIALS) < 5 AND '2018-08-15' BETWEEN ALLOCATION_START AND ALLOCATION_END AND (UPPER(AGENT_INITIALS) = 'JKKA')) age2 ON age1.AGENT_ID = age2.AGENT_ID ORDER BY AGENT_INITIALS."}
Also giving me an inner exception:
{"ORA-00904: \"AGE2\".\"AGENT_ID\": ugyldig identifikator"}
Debugging error screeenshot
Order it by the newest start date (descending) and select Top 1!
string agentIdSubQuery = "AGENT_ID " +
"FROM " +
"KS_DRIFT.V_AGENT_ALLOCATION " +
"WHERE " +
"LENGTH(AGENT_INITIALS) < 5 " +
" AND ROWNUM = 1 " +
" ORDER BY ALLOCATION_START DESC";
EDIT, changed Top 1 to Rownum = 1, for Oracle syntax
The table V_AGENT_ALLOCATION contains various departments per agent along with the dates the agent worked there. You want an agent's last department, which you get with Oracle's KEEP LAST. You haven't given us much information on your table, though. Let's say that the department is referenced by an allocation_id:
select
agent_id,
max(id_allocation) keep (dense_rank last order by allocation_start)
as id_current_allocation
from v_agent_allocation
group by agent_id
order by agent_id;
Your error message shows the final generated SQL:
{"Error occurred during execution of SQL query: SELECT age1.* FROM KS_DRIFT.V_AGENT_ALLOCATION age1 INNER JOIN (SELECT max(DISTINCT AGENT_ID FROM KS_DRIFT.V_AGENT_ALLOCATION WHERE LENGTH(AGENT_INITIALS) < 5 AND '2018-08-15' BETWEEN ALLOCATION_START AND ALLOCATION_END AND (UPPER(AGENT_INITIALS) = 'JKKA')) age2 ON age1.AGENT_ID = age2.AGENT_ID ORDER BY AGENT_INITIALS."}
If you format that so that it's readable, you get:
select age1.*
from ks_drift.v_agent_allocation age1
inner join
( select max(distinct agent_id
from ks_drift.v_agent_allocation
where length(agent_initials) < 5
and '2018-08-15' between allocation_start and allocation_end
and (upper(agent_initials) = 'JKKA') ) age2
on age1.agent_id = age2.agent_id
order by agent_initials
Two syntax issues should jump out:
There is a missing closing bracket after max(distinct agent_id (the distinct is also redundant)
The date literal is missing its date keyword - it should be date '2018-08-15' (or better still, a bind variable).
The brackets around (upper(agent_initials) = 'JKKA') are redundant but perhaps they arise from your generator logic and it's easiest to keep them.
I'm not sure how that relates to your 'newest allocated department' requirement, though. Some sample data (not a screenshot) would help.
If you're looking for the current department, you should compare the allocation dates with the current date.
Your query already has this WHERE clause, so it should work just fine for the example provided. But if you might want to specify that you need only ONE row using the ROWNUM special variable clause (assuming it's Oracle).
SELECT DISTINCT AGENT_ID
FROM KS_DRIFT.V_AGENT_ALLOCATION
WHERE LENGTH(AGENT_INITIALS) < 5
AND ALLOCATION_START < CURRENT_DATE AND CURRENT_DATE < ALLOCATION_END
AND ROWNUM = 1

Xamarin sql using left join for an android Tablet app

var db = new SQLiteConnection(dbPath);
try
{
var results = db.Query<Xclass>("SELECT X.COL1, X.COL2, " +
" X.COL3, X.Col4, X.Col5, " +
" A.Col2, A.COL3, B.Col2, C.Col2 " +
"FROM left join Xam X " +
"left join TABLE1 A on X.COL1 = A.COL1 " +
"left join TABLE2 B on X.COL2 = B.COL1 " +
"left join TABLE3 C on X.COL3 = C.COL1 " +
"WHERE X.COL1 ='"+ somevalue +"'");
}
catch (Exception e)
{
// display message
}
XCLASS Contains all the getters and setters.
But it only pulls in the Xam table and not the A, B, or C table values.
I originally had the table name in the Class but took it out to see if that would help.
Any assistance is appreciated. I am trying to avoid linq but if is necessary I will try it.
The instance(s) of Xclass object is created from the results of your query via reflection.
The columns in query's result set are translated to properties of the class
and the setters of hese properties are used to assign their values.
Therefore you must supply some hints to SQlite so it will know which column corresponds to which property. This is done via as keyword.
So, if you want assign the value of A.COL2 column in the result to property named MyCol2Property inside Xclass, you must retrieve it in the query using the syntax
A.Col2 as MyCol2Property

How to do the following in SQL, access?

I have the following query
SELECT dictionaryEncryptedIndex, filelocation FROM `DictionaryTable`
WHERE `dictionaryEncryptedWord` LIKE '0x0E6E'";
In c# I loop over the results from the above query and for every loop iteration I use the following query to get my end results:
SELECT * FROM `MaskedIndexTable`
WHERE `maskedIndexEncryptedIndex`
LIKE '" + dictionaryEncryptedIndexFROMABOVEQUERY + "'
AND `fileLocation` = '" + filelocationFROMABOVEQUERY + "'";
The relation between dictionaryEncryptedIndex and maskedIndexEncryptedIndex is not a one on one relation.
Does anyone know how to do the above in one SQL query that can be used in Microsoft Access?
I've tried multiple things like:
SELECT * from DictionaryTable, MaskedIndexTable
WHERE MaskedIndexTable.maskedIndexEncryptedIndex = DictionaryTable.dictionaryEncryptedIndex
AND MaskedIndexTable.fileLocation =DictionaryTable.fileLocation
AND `dictionaryEncryptedWord` LIKE '0x0E6E'
SELECT dictionaryEncryptedWord, DictionaryTable.filelocation
FROM DictionaryTable
INNER JOIN MaskedIndexTable
ON (MaskedIndexTable.maskedIndexEncryptedIndex =DictionaryTable.dictionaryEncryptedIndex )
WHERE `dictionaryEncryptedWord` LIKE '...'
SELECT distinct *
FROM MaskedIndexTable
INNER JOIN DictionaryTable
ON (MaskedIndexTable.maskedIndexEncryptedIndex = DictionaryTable.dictionaryEncryptedIndex )
WHERE MaskedIndexTable.Id IN
(
SELECT DictionaryTable.Id
FROM DictionaryTable
WHERE `dictionaryEncryptedWord` LIKE '..')
AND `dictionaryEncryptedWord` LIKE '...'
but none of them seem to produce the correct results (the results I get with my c# code)
You will need to change this if you want to use a wildcard in your LIKE criteria.
First create a query in Access similar to your first one called encryptedWordsQuery
SELECT DictionaryTable.dictionaryEncryptedIndex, DictionaryTable.fileLocation
FROM DictionaryTable
WHERE (((DictionaryTable.dictionaryEncryptedWord) Like "0x0E6E"));
Second create a query in Access as follows:
SELECT MaskedIndexTable.maskedIndex, MaskedIndexTable.maskedIndexEncryptedIndex, MaskedIndexTable.fileLocation
FROM MaskedIndexTable
WHERE Exists (SELECT *
FROM encryptedWordsQuery
WHERE MaskedIndexTable.maskedIndexEncryptedIndex = encryptedWordsQuery.dictionaryEncryptedIndex
AND MaskedIndexTable.fileLocation = encryptedWordsQuery.FileLocation);
I find it easier to create two separate queries rather than just one in Access.
I think this should work--if you are able to post sample data we could make a SQLFiddle to demo it.
SELECT dt.dictionaryEncryptedIndex, dt.filelocation
FROM DictionaryTable dt
INNER JOIN MaskedIndexTable mit
ON mit.fileLocation = dt.fileLocation
AND mit.maskedIndexEncryptedIndex = dt.dictionaryEncryptedIndex
WHERE dt.dictionaryEncryptedWord LIKE '0x0E6E*'

SQL Like statement not return a wildcard output asp.net c#

i have these sql statement to output job field based on user input.
SELECT jf.name, j.jname, c.cname, cj.url
FROM company_has_job cj
INNER JOIN job j ON j.id = cj.job_id
INNER JOIN company c ON c.id = cj.company_id
INNER JOIN jobfield_has_job jhj ON jhj.job_id = j.id
INNER JOIN jobfield jf ON jf.id = jhj.jobfield_id
WHERE jf.name LIKE '%' + #InputJob + '%'
for example when user input query "Programmer", the system will output all programmer job defined in the database.but the system does not show any result if i enter "Program" in the search box. This is my control parameter:
<SelectParameters>
<asp:ControlParameter ControlID="TextBox4" Name="InputExpertise"
PropertyName="Text"/>
</SelectParameters>
can you tell me where i did wrong? your help is much appreciated.
I am not sure if this is just a typo, but shouldn't it be
WHERE jf.name LIKE '''%' + #InputJob + '%'''
Notice that I made it so that the code will end up as LIKE '%Program%', whereas it looks like it will end up as LIKE %Program% currently.
Can't comment yet, but perhaps this will answer the question, do any of the columns that you join on allow NULLs? The inner join will not return results that include a null.
consider this query:
select wb.employee,wb.Dept from web_user wb
inner join Employee e on wb.Dept = e.Department
where wb.employee like '%Ted%'
No results
but this:
select wb.employee,wb.Dept from web_user wb
left join Employee e on wb.Dept = e.Department
where wb.employee like '%Ted%'
Returns:
Ted NULL
Also it my be helpful to debug, set a breakpoint on the actual call to the database to get the SQL statement it is using and then paste that into a query editor. I've done this many times when a query does not behave. Once you know what the program is using for the SQL statement that may also help you find the issue.

SQL Query to access database

I'm writing a database query that will show me where there is a space for parking. It is only used in July.
There is one table that shows all the spaces and whether they are rented that day. There is another table that has the spaces and their sizes. I want to be able to select those spaces that are available on all the days within the selected time period and have the correct size.
I am having a problem, though, selecting only the spaces available within the given time period. Here is the query so far but it does not contain anything concerning the space size as I want this part to work first.
SELECT C.Plads, SUM[C.optaget] C.[ledlig] FROM
(SELECT Plads FROM OptagetPladser AS A Inner JOIN Bådpladser as B ON
A.plads=B.Pladsnummer
WHERE
(A.dato>=" + Startdato + "and A.dato<="+Slutdato+") //checking the time period
and (a.optaget = 0)) //0 means the space is availible
as C
GROUP BY C.Plads
HAVING SUM(C.optaget) >="+ diffResult+")";//diff result is the timespan
At the moment I'm getting the error
Syntax error (missing operator) in query expression 'SUM[C.optaget]'
Any ideas?
First of all, you should rework your SQL query - it contains too many simple errors.
Here are a few.
Try adding a ',' and make some changes in query:
SELECT C.Plads, SUM(C.optaget), C.ledlig FROM
Your subquery C doesn't have an optaget and ledlig fields too. To fix this add those fields right after sebquery's SELECT
Fix a syntax error here:
(A.dato>=" + Startdato + "and A.dato<="+Slutdato+") which should be:
(A.dato >= " + Startdato + " and A.dato <= "+Slutdato+")
Your last double quote is redundant as well as last ')'. Remove it:
HAVING SUM(C.optaget) >= "+ diffResult+" ;//diff result is the timespan
Below is how your SQL query should look. Please, note: there are still missing fields optaget and ledlig in subquery C.
SELECT C.Plads, SUM(C.optaget), C.ledlig FROM
(
SELECT Plads FROM OptagetPladser AS A
INNER JOIN Bådpladser as B
ON A.plads = B.Pladsnummer
WHERE (A.dato >= " + Startdato + " AND A.dato <= " + Slutdato + ")
AND (a.optaget = 0)
)
AS C
GROUP BY C.Plads
HAVING SUM(C.optaget) >= " + diffResult + ";
I believe, there could appear an architectural or performance issues, but without table data I can't say it for sure.

Categories

Resources