I'm not getting results back from a query. At first I thought it was just a bad query - that no data should be returned, but now it seems it could be a syntax error that's causing the problem.
When running the Stored Procedure (that the query is a part of) in Visual Studio's Server Explorer, I get data back from the first query, but this one (an update) doesn't return any data (no err msg, but no data, either). Yet, when I try to run just this portion of the Stored Procedure in LINQPad, that bosom companion of coders everywhere declaims that it has discovered the much-dreaded "Error 102: Incorrect syntax near ','."
It points to this line:
and ItemCode in (Select ItemCode from UnitProducts where Unit='BIG RED ONE')),'X')
...(the only line with a ','), but I don't see what the problem is. I also tried this variation on the theme:
and ItemCode in (Select ItemCode from UnitProducts where Unit='BIG RED ONE'),'X'))
...but the err msg is the same.
Here is the entire query that I'm trying in LINQPad:
isnull((Select top 1 ItemCode
From PlatypusUnitMapping
where Unit='BIG RED ONE'
and MemberNo='42'
and MemberItemCode= '314IMPie'
and ItemCode in (Select ItemCode from UnitProducts where Unit='BIG RED ONE')),'X')
So what is wrong with this? The simpler version of the query works:
Select top 1 ItemCode
From PlatypusUnitMapping
where Unit='BIG RED ONE'
and MemberNo='42'
and MemberItemCode= '314IMPie'
and ItemCode in
(Select ItemCode from UnitProducts where Unit='BIG RED ONE')
...but I need the "isNull" jazz for a subsequent query. What syntax is invalid, and how can I make it valid/fix it?
UPDATE
Based on a nudge from NMM, I tried this, too:
and (ItemCode in (Select ItemCode from UnitProducts where Unit='BIG RED ONE'))),'X')
...but to no avail.
and (ItemCode in (Select ItemCode from UnitProducts where Unit='BIG RED ONE')
OR ItemCode = 'X')
What does this go with Where NHItemCode='X'. The error code is near I have found give you a general area of where the error is. Most of the time when I get this I have a ) out of place but that Where NHItemCode='X'looks out of place. Can you comment out just that line and see what happens? The other way to troubleshoot this is start without the is null and without the in clause. Then add the in clause run again and then last but not least add the is null around.
The following works, and should run on your SQL Server... Compare to your query and see what is missing:
SELECT
ISNULL((
SELECT TOP 1
TABLE_CATALOG
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA='dbo' AND
COLUMN_DEFAULT IS NULL AND
IS_NULLABLE='NO' AND
DATA_TYPE IN (SELECT DISTINCT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE DATA_TYPE<>'numeric')
),'NONE')
Related
Can someone help me find my syntax error? I feel like I've been staring at this stupid section for hours and have tried changing things, rewriting it, etc, but it just keeps giving me an error.
SELECT DISTINCT S.customer_name
FROM depositor AS S
WHERE NOT EXIST (
(SELECT branch_name
FROM branch
WHERE branch_city='Brooklyn')
EXCEPT
(SELECT R.branch_name
FROM depositor AS T, account AS R
WHERE T.account_number = R.account_number
AND S.customer_name = T.customer_name));
EXCEPT should be between two SELECTs, eg
SELECT ...
EXCEPT
SELECT ...
So your query should be:
SELECT DISTINCT S.customer_name
FROM depositor AS S
WHERE NOT EXISTS (
SELECT branch_name
FROM branch
WHERE branch_city='Brooklyn'
EXCEPT
SELECT R.branch_name
FROM depositor AS T, account AS R
WHERE T.account_number = R.account_number
AND S.customer_name = T.customer_name
)
I also removed the unnecessary brackets and corrected the spelling error of EXIST to EXISTS.
Have to migrate the below MSSQL code to postgresql
Looking forward for postgresql code which does the following.
MSSQL codee
MERGE TO_SubFamy AS TARGET
USING
(
SELECT SF.Id as SubFamyId,
CASE WHEN COUNT(A.Id)>0 THEN 'Young' ELSE 'OLD' END as ActiveYn
FROM
TO_SubFamy SF
RIGHT JOIN TO_SubFamyAutomationLink SFA ON SF.Id=SFA.SubFamyId
RIGHT JOIN TO_AUTOMATiON A ON A.Id = SFA.AutomationId and A.State='Active'
WHERE SF.Status <> 'not exits'
GROUP BY SF.Id
EXCEPT
SELECT Id, status from TO_SubFamy WHERE Status <> 'not exits'
) as SOURCE
ON TARGET.Id = SOURCE.SubFamyId
WHEN MATCHED THEN
UPDATE SET TARGET.status = SOURCE.ActiveYn;
pls help
My experience with MySql is rather limited, but the statement looks suspiciously like the same statement in Oracle. (Not a surprise as it wasn't supported until after Oracle bought MySql.) And a little research seems to confirm.
The merge statement is typically used to either insert or update based on the result of the ON statement. But another semi-common use is strictly to update as the syntax is somewhat easier in many cases as you do need to essentially repeat the select statement. Since your statement uses only the WHEN MATCHED clause it is the latter use being employed. So the translation is just a UPDATE. I think the follow satisfies your need.
with source (subfamyid,activeyn) as
(select sf.id,
case when count(a.id)>0 then 'Young' else 'OLD' end
from to_subfamy sf
right join to_subfamyautomationlink sfa on sf.id=sfa.subfamyid
right join to_automation a on a.id = sfa.automationid and a.state='Active'
where sf.status <> 'not exits'
group by sf.id
except
select id, status from to_subfamy where status <> 'not exits'
)
update to_subfamy as target
set status = source.activeyn
where target.id = source.subfamyid;
Disclaimer: As you neglected sample data and expected results the query has not been tested. However, right joins look suspicious, appears that all rows from table "to_automation" will be kept even if they do not exist in either of the others.
Using this SQL, I can cast a boolean column to a text:
SELECT *, (CASE WHEN bars.some_cond THEN 'Yes' ELSE 'No' END) AS some_cond_alpha
FROM "foos"
INNER JOIN "bars" ON "bars"."id" = "foos"."bar_id";
So why do I get a PG::UndefinedColumn: ERROR: column "some_cond_alpha" does not exist when I try to use it in a WHERE clause?
SELECT *, (CASE WHEN bars.some_cond THEN 'Yes' ELSE 'No' END) AS some_cond_alpha
FROM "foos"
INNER JOIN "bars" ON "bars"."id" = "foos"."bar_id"
WHERE (some_cond_alpha ILIKE '%y%');
This is because the column is created on-the-fly and does not exist. Possibly in later editions of PG it will, but right now you can not refer to an alias'd column in the WHERE clause, although for some reason you can refer to the alias'd column in the GROUP BY clause (don't ask me why they more friendly in the GROUP BY)
To get around this, I would make the query into a subquery and then query the column OUTSIDE the subquery as follows:
select *
from (
SELECT *, (CASE WHEN bars.some_cond THEN 'Yes' ELSE 'No' END) AS some_cond_alpha
FROM "foos"
INNER JOIN "bars" ON "bars"."id" = "foos"."bar_id"
) x
WHERE (x.some_cond_alpha ILIKE '%y%')
NOTE: It is possible at some point in the future you will be able to refer to an alias'd column in the WHERE clause. In prior versions, you could not refer to the alias in the GROUP BY clause but since 9.4 + it is possible...
SQL evaluates queries in a rather counterintuitive way. It starts with the FROM and WHERE clauses, and only hits the SELECT towards the end. So aliases defined in the SELECT don't exist yet when we're in the WHERE. You need to do a subquery if you want to have access to an alias, as shown in Walker Farrow's answer.
When I read an SQL query, I try to do so in roughly this order:
Start at the FROM. You can generally read one table/view/subquery at a time from left to right (or top to bottom, depending on how the code is laid out); it's normally not permissible for one item to refer to something that hasn't been mentioned yet.
Go down, clause by clause, in the order they're written. Again, read from left to right, top to bottom; nothing should reference anything that hasn't been defined yet. Stop right before you hit ORDER BY or something which can only go after ORDER BY (if there is no ORDER BY/etc., stop at the end).
Jump up to the SELECT and read it.
Go back down to where you were and resume reading.
If at any point you see a subquery, apply this algorithm recursively.
If the query begins with WITH RECURSIVE, go read the Postgres docs for 20 minutes and figure it out.
I've got a table, me, that's got an e_id column, a first_name, and a last_name. (A few other columns too but I'm just trying to figure out the window function stuff.) When I try to do a query and pick out the first name values in the table for a given e_id value:
SELECT e_id, first_value(first_name), first_value(last_name)
OVER (PARTITION BY e_id)
FROM me
I get the "window function call requires an OVER clause" error. Now, like I said, I don't know what I'm doing yet, but I'm pretty sure there's at least an attempt at an OVER clause in that query. OK, so when I try it without the functions:
SELECT e_id, first_name, last_name
OVER (PARTITION BY e_id)
FROM me
I get a syntax error at OVER. I'm running psql version 9.4.4 against a 9.1.13 server. I'm staring at the documentation for 9.1 and it looks to me like OVER is documented there. Am I just missing something basic here?
Each window function must have its own OVER clause. The problem with your first query is that the first_value(first_name) window function does not have an OVER clause.
And the problem with your second query is that you have an OVER clause that is not preceded by a window function.
Try this
SELECT e_id,
first_value(first_name) OVER (PARTITION BY e_id),
first_value(last_name) OVER (PARTITION BY e_id)
FROM me
select * from (
select max(h.updated_datetime) as max, min(h.updated_datetime) as min from report r, report_history h, procedure_runtime_information PRI, study S
where
h.report_fk=r.pk and
r.study_fk=S.pk and
PRI.pk=S.procedure_runtime_fk and
extract(epoch from (max(h.updated_datetime) - min(h.updated_datetime) ) <=900 and
h.pk IN (
select pk from
(select * from report_history where report_fk=r.pk) as result
)
and r.status_fk =21 group by r.pk)as result1;
this is my query i have a syntax error can any one help me fix this
thanks in advance
As you didn't bother telling us what the error is I have to guess, that it's this line:
AND h.pk IN (SELECT pk FROM (SELECT * FROM report_history WHERE report_fk=r.pk) AS RESULT)
The nesting level for the where condition is "too deep" and I think it cannot see the r alias in the where clause.
But the nested select is totally useless in your case anyway, so you can rewrite that condition as:
AND h.pk IN (SELECT pk FROM report_history WHERE report_fk=r.pk)
Even if that doesn't solve your problem, it makes your query more readable.
Then you are using an aggregate in the where clause which is also not allowed, you have to move it to a having clause.
having extract(epoch from (max(h.updated_datetime) - min(h.updated_datetime))) <=900
The having clause comes after the group by
You were also missing a closing ) but that is hard to tell because of your formatting (which I find very hard to read)
You should also get used to explicit JOIN syntax. The implicit joins in the WHERE clause are error-prone and no longer recommended.