OPENQUERY DELETE WHERE IN - sql

Need to delete records from local person table where employee status in remote employee table is terminated. Trying something like the following but cannot get the open query syntax correct:
DELETE FROM PERSON WHERE ID IN
OPENQUERY(LSVR1,'SELECT DISTINCT ID FROM EMPLOYEE WHERE EMPLOYEE_STATUS=''T'' AND TERMINATION_DATE<SYSDATE-365')
I get
"Incorrect syntax near the keyword 'openquery'."

You could use IN (SELECT ... FROM OPENQUERY() alias):
DELETE FROM PERSON WHERE ID IN (
SELECT ID
FROM OPENQUERY(LSVR1,
'SELECT DISTINCT ID FROM EMPLOYEE WHERE EMPLOYEE_STATUS=''T'' AND TERMINATION_DATE<SYSDATE-365'
) sub);

Related

Use a select query result in an other query

Could please someone explain, how to use a result from a SELECT (1st select result)
Then use that result (1st select result) on a second query VALUES clause
there is an example (on Microsoft SQL Server) :
--1st query, select all DB1.client.name
select Name from DB1.client
--the result of that query is : 1st select result VALUES : ana,boby, ..., micky
--2nd query, compare DB1.client.name (1st select result) with DB2.client.name
--and get back who doesn't exist on second table
select v.Name
from (values
**(There i want use the result of my first query)**
) as v(Name)
where not exists (select *
from DB2.client c
where c.Name = v.Name);
--the result is ana, ..., micky
"..." mean some other results
i want compare first and second database to retrieve values which aren't in both databases
If you can, I recommend sub-query :
select Name
from DB1.client
where Name not in not exists (select name from DB2.client)
If you want reuse a query (not the result), see #Thkas answer.
It isn't possible to reuse the result in SQL Server, because SQL Server release the memory when the result is read. The trick is to insert the query's result in a temporary table, then you read this temporary table as many times as necessary :
--Insert into temporary table
insert into #tmpResult
select Name from DB1.client
--First read
select Name from #tmpResult
--Second read from sub-query
select Name
from #tmpResult
where Name not in not exists (select name from DB2.client)
According to your sample code I understood something like this. You can add two tables and do with WHERE the check you want.
select a.Name,b.Name
from DB1.client,
DB2.client as b
where a.Name != b.Name;
Also if you want to take as a result set from the first query:
Here I created a subquery which takes the results from the first query. You can correct me for columns.
with temp as (
select Name
from DB1.client
)select a.Name,b.Name
from temp as a ,
DB2.client as b
where a.Name != b.Name;

Invalid Object Name when i execute a procedure that update a table

I have the following
use salesdb
go
create procedure monthlysales as
begin
create table MyTable( SalesFactID integer identity(1,1),
ReportingMth date,
customer_id varchar(50),
ReferenceID navarchar(50),
LstOrderDte date);
Insert into MyTable
select
businessMth,
saleid as referenceid,
null as lastorderte
from sourcetble;
update MyTable
set lastorderte = sls.max_orderdte
from ( select
st.customer_id,
ftmytbl.ReportingMth,
max(salesdate) as max_orderdte
from sales_table st
left outer join mytable ftmytbl
on ftmytbl.customerid=st.customerRef
where saleste<=ftmytbl.ReportingMth
group by customer_id
)up
where mytable.customer_id=up.customer_id
and mytable.reportingmth=up.ReportingMth;
end;
execute monthlysales
error invalid object name mytable.reportingmth
How can i fix this? Please assist.
Search for that text. Where is it? It is in the where clause of the outermost select statement. You used a derived table named up (which is a crap name, btw - as are many of your names) in the join. The outer query knows only 2 tables - up and MyTable (or is it mytable? BE CONSISTENT!) and can only refer to columns in those tables.
To correct this particular problem, change this:
and mytable.reportingmth=up.ReportingMth;
to
and MyTable.ReportingMth = up.ReportingMth;
But that will only fix one problem. There seem to be others yet to be found.

Find the rows that has the same column

I want to know how to do the following in SQL :
SELECT *
FROM table_A
WHERE id IN(:myValues)
AND other_colum has the same value
For example, if i've a conversation table(iduser,idconversation), I want SQL query that returns some of Ids that have the same conversation id. It should return
35;105
37;105
35;106
37;106
With 35,37 the idUsers and 105,106 the conversations they have in common.
To go further, i work with Doctrine and PostegreSQL, and the table that I want to query is generated (many to many relation) but i've difficulty to integrate sub-query.
**public function getAllCommonConversationByUserId($ids)
{
return $this->createQueryBuilder('c')
->select('c.id')
->innerJoin('c.idUser', 'recievedConversation')
->where('recievedConversation IN (:ids)')
->andWhere('$qb->expr()->eq("SELECT id FROM table GROUP BY(id) HAVING COUNT(*) >1")')
->setParameter(':ids', $ids)
->getQuery()
->getResult();
}**
Just:
SELECT *
FROM table_A
WHERE idconversation in ('105','106') and iduser in ('35','37')
UPDATE:
Are you saying if the idconversation is duplicate? (showing multiple times?)
If so:
Select *
From table
where idconversation in
(
Select idconversation
From table
group by (idconversation)
Having count(*) >1
)
--where iduser in ('35','37')
Try to do this:
select id, conversation
from [your table name]
where
conversation in (
select conversation
from [your table name]
where id in (35)
)
It return all of the participants of the conversation with user id = 35
If you have duplicates in your table, please add distinct to select statement.
You can get the conversations using group by and having:
SELECT conversationid
FROM table_A
WHERE userid in (35, 37)
GROUP BY userid
HAVING count(distinct userid) = 2;
If you want the original rows, you can join back to the original table.

Insert to sql server table from field from another table and varchar field

I need to populate reqopt table which have two varchar fields (valeur, categorie), the first shoud be field from another table (mytable) and another should be a simple varchar ('prop').
I've tried this
INSERT INTO reqopt(valeur, categorie) (select distinct name from mytable , 'prop')
I got this error Incorrect syntax near 'prop'.
INSERT INTO reqopt(valeur, categorie)
select distinct name, 'prop'
from mytable
SELECT DISTINCT NAME AS valeur,'PROP' REMARKS AS categorie
INTO reqopt
FROM MYTABLE
--WHERE CONDITION IF REQUIRED

Insert in table, Sequence.nextval not working

I have the following 3 tables,
Data_Excel contains the names, address, city and source of person;
Person table has the name and ID;
I need to insert into person_location the address source, address, city and ID...
I am using the following query :
CREATE SEQUENCE seq
START WITH 6571
MINVALUE 6571
INCREMENT BY 1
CACHE 100
INSERT INTO Person (id,Name,source)
Select (seq.nextval),p_name,source
FROM Data_Excel
WHERE P_Name NOT IN
(SELECT name FROM Person)
GROUP BY P_Name,P_Address,P_city,Source
HAVING count(*) < 2;
but I get the following error.
I am using seq because ID is the primary key in persons but its not auto incrementing. I also tried that but there was an error :
02287. 00000 - "sequence number not allowed here"
*Cause: The specified sequence umber (CURRVAL or NEXTVAL) is inappropriate
here in the statement.
*Action: emove the sequence number.
Try moving the sequence out of the grouping query:
INSERT INTO Person (id,Name,source)
SELECT seq.nextval, p_name,source FROM (
Select p_name,source
FROM Data_Excel
WHERE P_Name NOT IN
(SELECT name FROM Person)
GROUP BY P_Name,P_Address,P_city,Source
HAVING count(*) < 2
);