Sub Query return more than one value - sql

I have create a table in which data will be inserted.
For data inserting, Have created a query that will insert the information from another table.
If the output is single value, It's updating in the new table.
But If it's multiple value, I am getting an error " Subquery return more than one value"
How to input multiple values using query in table?
Declare #BATCHNO as Nvarchar(10)
Declare #PRODNO as Nvarchar(10)
Declare #ISSUENO AS Nvarchar(10)
set #BATCHNO = (select T2.BatchNum from OWOR T0 INNER JOIN table_P T1 ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2 ON T1.DocEntry = T2.BaseEntry AND T1.ObjType = T2.BaseType
WHERE T0.DocEntry = '14')
Set #PRODNO = (select T1.BaseRef from OWOR T0 INNER JOIN table_P T1 ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2 ON T1.DocEntry = T2.BaseEntry AND T1.ObjType = T2.BaseType
WHERE T0.DocEntry = '14' )
Set #ISSUENO = (select T1.DocEntry AS 'ISSUE NUMBER' from OWOR T0 INNER JOIN table_P T1 ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2 ON T1.DocEntry = T2.BaseEntry AND T1.ObjType = T2.BaseType
WHERE T0.DocEntry = '14')
Insert Into BATCHDETAIL (BATCHNO,PRODNO,ISSUENO) Values(#BATCHNO,#PRODNO,#ISSUENO)
[Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. FMS execution failed on field 'U_EA_LICENCE' with query name 'FMS_BATCHNO_UPDATE'

It looks like you are trying to insert multiple rows based on existing data. In which case you should use INSERT .. SELECT rather than INSERT...VALUES:
INSERT BatchDetail (BatchNo, ProdNo, IssueNo)
SELECT T2.BatchNum, T1.BaseRef, T1.DocEntry
FROM OWOR T0
INNER JOIN table_P T1
ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2
ON T1.DocEntry = T2.BaseEntry
AND T1.ObjType = T2.BaseType
WHERE T0.DocEntry = '14';
If you did only want to insert one record, based on multiple records, you can use TOP 1, and provide an ORDER BY to ensure you get repeatable results:
INSERT BatchDetail (BatchNo, ProdNo, IssueNo)
SELECT TOP 1 T2.BatchNum, T1.BaseRef, T1.DocEntry
FROM OWOR T0
INNER JOIN table_P T1
ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2
ON T1.DocEntry = T2.BaseEntry
AND T1.ObjType = T2.BaseType
WHERE T0.DocEntry = '14'
ORDER BY t2.BatchNum, T1.BaseRef, T1.DocEntry;
Finally, if you really do want 3 scalar variables, then you can still use SELECT and TOP 1, you just need to use the SELECT for variable assignment:
DECLARE #BATCHNO AS NVARCHAR(10)
#PRODNO AS NVARCHAR(10)
#ISSUENO AS NVARCHAR(10);
SELECT TOP 1
#BATCHNO = T2.BatchNum,
#PRODNO = T1.BaseRef,
#ISSUENO = T1.DocEntry
FROM OWOR T0
INNER JOIN table_P T1
ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2
ON T1.DocEntry = T2.BaseEntry
AND T1.ObjType = T2.BaseType
WHERE T0.DocEntry = '14'
ORDER BY t2.BatchNum, T1.BaseRef, T1.DocEntry;
ADENDUMEM
I would very much recommend staying away from any of the approaches that use 3 queries with TOP 1 and no order by. For example, if you had a table:
A B C
----------
1 3 2
2 1 3
3 2 1
You might expect this to assign #A, #B, and #C values that correspond to a single record (e.g. 1, 3, 2 or 2, 1, 3)
SET #A = (SELECT TOP 1 A FROM #T);
SET #B = (SELECT TOP 1 B FROM #T);
SET #C = (SELECT TOP 1 C FROM #T);
However, you are executing 3 different queries, and depending on what indexes are on the table(s) you could get 3 different query plans, and 3 different records used for each assignment.
This is fairly easily demonstrated:
-- CREATE TABLE AND FILL IT
IF OBJECT_ID(N'tempdb..#T', 'U') IS NOT NULL DROP TABLE #T;
CREATE TABLE #T (A INT NOT NULL PRIMARY KEY, B INT NOT NULL, C INT NOT NULL);
CREATE NONCLUSTERED INDEX IX_T_B ON #T (B);
CREATE NONCLUSTERED INDEX IX_T_C ON #T (C);
INSERT #T (A, B, C)
VALUES (1, 3, 2), (2, 1, 3), (3, 2, 1);
DECLARE #A INT, #B INT, #C INT;
SET #A = (SELECT TOP 1 A FROM #T);
SET #B = (SELECT TOP 1 B FROM #T);
SET #C = (SELECT TOP 1 C FROM #T);
SELECT A = #A, B = #B, C = #C;
For me this returns:
A B C
----------
3 1 1
Which does not correspond to any record in the original data. This might be absolutely fine for your needs, but it is definitely something to be aware of.
Example on db<>fiddle

You need to fix your subqueries so they return the exact single value to be inserted.
For example, if you don't really care and can insert whatever value that fulfills those conditions, then simply add a TOP 1 to your subqueries, so they will return only the first value available.
Declare #BATCHNO as Nvarchar(10)
Declare #PRODNO as Nvarchar(10)
Declare #ISSUENO AS Nvarchar(10)
set #BATCHNO = (select TOP 1 T2.BatchNum from OWOR T0 INNER JOIN table_P T1 ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2 ON T1.DocEntry = T2.BaseEntry AND T1.ObjType = T2.BaseType
WHERE T0.DocEntry = '14')
Set #PRODNO = (select TOP 1 T1.BaseRef from OWOR T0 INNER JOIN table_P T1 ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2 ON T1.DocEntry = T2.BaseEntry AND T1.ObjType = T2.BaseType
WHERE T0.DocEntry = '14' )
Set #ISSUENO = (select TOP 1 T1.DocEntry AS 'ISSUE NUMBER' from OWOR T0 INNER JOIN table_P T1 ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2 ON T1.DocEntry = T2.BaseEntry AND T1.ObjType = T2.BaseType
WHERE T0.DocEntry = '14')
Insert Into BATCHDETAIL (BATCHNO,PRODNO,ISSUENO) Values(#BATCHNO,#PRODNO,#ISSUENO)
By the way, you can simplify your script assigning the three variables on a single query :
Declare #BATCHNO as Nvarchar(10)
Declare #PRODNO as Nvarchar(10)
Declare #ISSUENO AS Nvarchar(10)
select TOP 1 #BATCHNO = T2.BatchNum,
#PRODNO = T1.BaseRef,
#ISSUENO = T1.DocEntry
from OWOR T0
INNER JOIN table_P T1 ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2 ON T1.DocEntry = T2.BaseEntry AND T1.ObjType = T2.BaseType
where T0.DocEntry = '14'
Insert Into BATCHDETAIL (BATCHNO,PRODNO,ISSUENO) Values(#BATCHNO,#PRODNO,#ISSUENO)
Finally, if you want to insert all the values that fulfill your condition, then instead of taking just the first one with TOP 1, you can insert all of them feeding the insert with a select :
Insert Into BATCHDETAIL (BATCHNO,PRODNO,ISSUENO)
select T2.BatchNum, T1.BaseRef, T1.DocEntry
from OWOR T0
INNER JOIN table_P T1 ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2 ON T1.DocEntry = T2.BaseEntry AND T1.ObjType = T2.BaseType
where T0.DocEntry = '14'

use this.
Declare #BATCHNO as Nvarchar(10)
Declare #PRODNO as Nvarchar(10)
Declare #ISSUENO AS Nvarchar(10)
set #BATCHNO = (select TOP 1 T2.BatchNum from OWOR T0 INNER JOIN table_P T1 ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2 ON T1.DocEntry = T2.BaseEntry AND T1.ObjType = T2.BaseType
WHERE T0.DocEntry = '14')
Set #PRODNO = (select TOP 1 T1.BaseRef from OWOR T0 INNER JOIN table_P T1 ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2 ON T1.DocEntry = T2.BaseEntry AND T1.ObjType = T2.BaseType
WHERE T0.DocEntry = '14' )
Set #ISSUENO = (select TOP 1 T1.DocEntry AS 'ISSUE NUMBER' from OWOR T0 INNER JOIN table_P T1 ON T0.DocEntry = T1.BaseEntry
INNER JOIN Table_I T2 ON T1.DocEntry = T2.BaseEntry AND T1.ObjType = T2.BaseType
WHERE T0.DocEntry = '14')
Insert Into BATCHDETAIL (BATCHNO,PRODNO,ISSUENO) Values(#BATCHNO,#PRODNO,#ISSUENO)

Related

How to replace an OR statement from a join in sql server

I have the following query that uses an or statement on a join, so basically if one condition on the join isn't met it must check the next condition. The problem is that with the OR statement it takes really long to run but when I remove one of the OR conditions it runs instantly. is there a better way to do this with both conditions without using the OR statement so it would speed up the query
select t5.TransactionNumber
,t4.ID
,t3.[Entry] AS Amount
,t2.Address AS AddressDetail
,t1.PhoneNumber AS ContactNumber
FROM Table1 t1 (NOLOCK)
JOIN Table2 t2 (NOLOCK) ON t2.FicaID = t1.FicaId
inner join Table3 t3 (NOLOCK) ON (t3.ID = t2.ID AND t3.Code = t2.Code) or (t3.TypeID = t2.TypeID) //on this join i have an or statement if one condition isnt met it must check the next condition
LEFT JOIN Table4 t4 (NOLOCK) ON t4.Result = t3.Result
LEFT JOIN Table5 t5 (NOLOCK) ON t5.AccNum = t3.AccNum
where t1.date>'2018-09-01' and t1.date<'2018-09-30'
By the rule of distributivity in logic,
P OR (Q AND R) can be written as
(P OR Q) AND (P OR R).. maybe that helps?
You could try by using left join and COALESCE function
select t5.TransactionNumber
,t4.ID
,COALESCE(t3.[Entry],t33.[Entry]) AS Amount
,t2.Address AS AddressDetail
,t1.PhoneNumber AS ContactNumber
FROM Table1 t1 (NOLOCK)
JOIN Table2 t2 (NOLOCK) ON t2.FicaID = t1.FicaId
left join Table3 t3 (NOLOCK) ON (t3.ID = t2.ID AND t3.Code = t2.Code)
left join Table3 t33 (t33.TypeID = t2.TypeID) //I moved it to left join
LEFT JOIN Table4 t4 (NOLOCK) ON t4.Result = t3.Result
LEFT JOIN Table5 t5 (NOLOCK) ON t5.AccNum = t3.AccNum
where t1.date>'2018-09-01' and t1.date<'2018-09-30'
You can try below query :
select * from
(
select t5.TransactionNumber
,t4.ID
,t3.[Entry] AS Amount
,t2.Address AS AddressDetail
,t1.PhoneNumber AS ContactNumber
FROM Table1 t1 (NOLOCK)
JOIN Table2 t2 (NOLOCK) ON t2.FicaID = t1.FicaId
inner join Table3 t3 (NOLOCK) ON (t3.ID = t2.ID AND t3.Code = t2.Code)
)A
join Table3 t3 (NOLOCK) ON (A.TypeID = t3.TypeID)
LEFT JOIN Table4 t4 (NOLOCK) ON t4.Result = t3.Result
LEFT JOIN Table5 t5 (NOLOCK) ON t5.AccNum = t3.AccNum
where t1.date>'2018-09-01' and t1.date<'2018-09-30'

Query to Select Data from 3 Tables when one table doent have a FOREIGN KEY to one table

I have three tables (ASSETINFO, VENDORINFO, STATEINFO)
I execute the following Query:
SELECT t2.TYPE [TYPE], t3.Status [STATUS], t4.COMPANY, T5.STATEID [STATE]
FROM ASSETINFO t1
INNER Join TYPEINFO t2 on t1.TYPEID = t2.TYPEID
INNER Join STATUSINFO t3 on t1.STATUSID = t3.STATUSID
INNER Join VENDORINFO t4 on t1.VENDORID = t4.VENDORID
INNER Join VENDORINFO t5 on t1.VENDORID = t5.VENDORID
And get back the following results:
TYPE: NETWORK FIREWALL | STATUS: ASSIGNED | COMPANY: DELL | STATE: 3
I am able to retrieve the COMPANY Name from TABLE VENDORINFO but, I don’t know how to replace the STATEID from table STATEINFO with the value in the STATE column?
Your second join of vendorInfo is not necessary. Instead join in your Stateinfo table:
SELECT t2.TYPE [TYPE], t3.Status [STATUS], t4.COMPANY, T5.STATE
FROM ASSETINFO t1
INNER Join TYPEINFO t2 on t1.TYPEID = t2.TYPEID
INNER Join STATUSINFO t3 on t1.STATUSID = t3.STATUSID
INNER Join VENDORINFO t4 on t1.VENDORID = t4.VENDORID
INNER Join stateINFO t5 on t4.State = t5.StateId
Then just bring in State

trying to add a selection to the following query

I nee to add a user selected date (DocDate) to the following query
SELECT DocNum, CardCode, CardName FROM ORDR WHERE DOCENTRY NOT IN(
select DISTINCT(T0.DOCENTRY)
from ORDR T0 JOIN RDR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
LEFT JOIN OITM T2 ON T1.ITEMCODE = T2.ITEMCODE
LEFT JOIN OITB T3 ON T2.ItmsGrpCod = T3.ItmsGrpCod
WHERE T3.ItmsGrpNam = 'Carriage Out'
AND T0.DocType = 'I'
)
AND DOCTYPE = 'I'
Improved query - not yet an answer though.
SELECT DocNum, CardCode, CardName
FROM ORDR
WHERE DOCENTRY NOT IN
(
select T0.DOCENTRY
from ORDR T0
JOIN RDR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
LEFT JOIN OITM T2 ON T1.ITEMCODE = T2.ITEMCODE
LEFT JOIN OITB T3 ON T2.ItmsGrpCod = T3.ItmsGrpCod
AND T3.ItmsGrpNam = 'Carriage Out'
WHERE T0.DocType = 'I'
)
AND DOCTYPE = 'I'
where YEAR(t0.DocDate) = YEAR(#date) where #date is your sent input, you can either check for specific date, same year or month.

How to combine these 2 SQL queries?

I have two SQL queries I would like to combine into 1. Here is the current (working) query:
select (
select sum(t3.unitWeight)
from t1
join t2 on t1.uid = t2.uid
join t3 on t3.partNo = t1.partNo
where t1.prodDate = '6/11/14'
) - (
select sum(t4.numPieces * t3.unitWeight)
from t1
join t4 on t1.uid = t4.uid
join t3 on t3.partNo = t1.partNo
where t1.prodDate = '6/11/14' and t4.threadType = 'F'
)
(Unfortunately, the join t2... is required for row expansion)
I would somehow like to have
SELECT SUM(t3.unitWeight - t4.numPieces * t3.unitWeight) ...
but of course that doesn't quite work. Thanks for any assistance.
You could use the t1.uid field to join the two selects..
SELECT SUM( a.unitWeght1 - ISNULL(b.unitWeght2, 0)) as finalResult
FROM
(
select sum(t3.unitWeight) as unitWeght1, t1.uid
from t1
join t2 on t1.uid = t2.uid
join t3 on t3.partNo = t1.partNo
where t1.prodDate = '6/11/14'
GROUP BY t1.uid
) a left outer join
( select sum(t4.numPieces * t3.unitWeight) as unitWeght2, t1.uid
from t1
join t4 on t1.uid = t4.uid
join t3 on t3.partNo = t1.partNo
where t1.prodDate = '6/11/14' and t4.threadType = 'F'
GROUP BY t1.uid
) b on a.uid = b.uid
I should imagine something like the below code would do the trick. I haven't had chance to test this.
BEGIN
DECLARE #UnitWeight DECIMAL
DECLARE #PiecesUnitWeight DECIMAL
SET #UnitWeight =
(
SELECT sum(t3.unitWeight)
FROM t1
JOIN t2 ON t1.uid = t2.uid
JOIN t3 ON t3.partNo = t1.partNo
where t1.prodDate = '6/11/14'
)
SET #PiecesUnitWeight =
(
SELECT sum(t4.numPieces * t3.unitWeight)
from t1
join t4 on t1.uid = t4.uid
join t3 on t3.partNo = t1.partNo
where t1.prodDate = '6/11/14' and t4.threadType = 'F'
)
SELECT (#UnitWeight - #PiecesUnitWeight)
END

SQL Server - use columns from the main query in the subquery

Is there any way to get a column in real time, from a main query, and use it in a subquery?
Something like this: (Use A.item in the subquery)
SELECT item1, *
FROM TableA A
INNER JOIN
(
select *
from TableB B
where A.item = B.item
) on A.x = B.x;
Ok, here is the real thing:
I need to modify this existing query. It worked before, but now that the database changed, I need to do some modifications, add some comparisons. As you can see there are a lot of JOINS, and one of them is a subquery. I need to add a comparison from a column from the main query (from the table T0 for example) to the subquery (like this: T6.UnionAll_Empresa = T0.UnionALl_Empresa)
Select T0.UnionAll_Empresa,<STUFF>
from [UNION_ALL_BASES]..OINV T0 with (nolock)
inner join [UNION_ALL_BASES]..INV6 T1 with (nolock) on t0.DocEntry = t1.DocEntry and t0.UnionAll_Empresa = t1.UnionAll_Empresa
inner join
(
select
t1.CompanyID,
T2.CompanyDb,
t1.OurNumber,
T6.BankCode,
T6.BankName,
T3.[Description] Situation,
T1.[Status],
T5.Descrption nomeStatus,
T1.Origin,
T1.DocEntry,
T1.DocType,
T1.ControlKey,
T1.CardCode,
T4.[Description] ContractBank,
T1.PayMethodCode,
T1.DueDate,
T1.DocDate,
T1.InstallmentID,
T1.InstallmentValue,
T1.Correction,
T1.InterestContractural,
T1.FineContract,
T1.ValueAbatment,
T1.ValueDiscount,
T1.ValueFineLate,
T1.ValueInterestDaysOfLate,
T1.OtherIncreases,
T1.ValueInWords,
T1.ValueDocument,
T1.DigitalLine,
T1.Document
from [IntegrationBank]..BillOfExchange T1 with (nolock)
inner join [InterCompany2]..CompanyHierarchy T2 with (nolock) on T1.CompanyID = T2.ID
left join [IntegrationBank]..BillOfExchangeSituation T3 with (nolock) on T1.Situation = T3.ID
inner join [IntegrationBank]..ContractBank T4 with (nolock) on T1.ContractBank = T4.ID
inner join [IntegrationBank]..BoeStatus T5 with (nolock) on T1.[Status] = T5.ID
inner join [UNION_ALL_BASES]..ODSC T6 with (nolock) on T4.BankKey = T6.AbsEntry and **T6.UnionAll_Empresa = T0.UnionALl_Empresa** --I need to do this
where T1.[Status] <> 5
and T2.CompanyDb = **T0.UnionAll_Empresa** --I need to do this
) TBI on (T1.DocEntry = TBI.DocEntry and T1.InstlmntID = TBI.InstallmentID and TBI.DocType = T1.ObjType )
inner join [UNION_ALL_BASES]..OCTG T2 on T0.GroupNum = T2.GroupNum and T0.UnionAll_Empresa = T2.UnionAll_Empresa
inner join [UNION_ALL_BASES]..OSLP T3 on T0.SlpCode = T3.SlpCode and T0.UnionAll_Empresa = T3.UnionAll_Empresa
where not exists (select 1
from [UNION_ALL_BASES]..RIN1 A with (nolock)
inner join [UNION_ALL_BASES]..ORIN B with (nolock) on A.DocEntry = B.DocEntry and A.UnionAll_Empresa = B.UnionAll_Empresa
where A.BaseEntry = T0.DocEntry
and B.SeqCode = ''1'' )
You can user OUTER APPLY
SELECT *
FROM tbl1
OUTER APPLY ( SELECT TOP 1
currency_id,
SUM(taxrate) AS taxrate
FROM tbl2
WHERE wuptr.currency_id = tbl1.currency_id
GROUP BY tbl2.currencyid
)
You don't need a subquery for that:
SELECT item1, *
FROM TableA A
INNER JOIN
TableB B
ON A.item = B.item
AND A.x = B.x;
I can't think of a scenario where you would need to JOIN on a subquery with a filter like that where it wouldn't be equivalent to just reference the field directly in the outer query.
You can reference the outer table in the subquery in the WHERE clause, though:
SELECT <stuff>
FROM Table t
WHERE EXISTS (SELECT 1 from TableB B
WHERE t.id = b.id)
EDIT
For your actual code, just change the JOIN criteria to this:
) TBI on (T1.DocEntry = TBI.DocEntry
and T1.InstlmntID = TBI.InstallmentID
and TBI.DocType = T1.ObjType
AND TBI.CompanyDB = T0.UnionAll_Empresa )
If you want to join on to a subquery and "get a column in real-time"/ reference a column from the main query, then there is a trick to doing this.
You can't access the tables which are outside of the subquery if it's used as an aliased table, in other words, this SQL can never access A:
...
INNER JOIN
(
select *
from TableB B
where A.item = B.item
) on A.x = B.x;
The way to access A would be like this:
SELECT item1, *
FROM TableA A
INNER JOIN TableB on TableB.item = TableA.item and TableB.item in
(
select top 1 B.Item
from TableB B
where A.item = B.item
)
Just ignore the "top 1" piece, I just added that to show that there may a reason for doing a join like this.
So, basically if you want to reference an item from the query in the subquery, just move the subquery to the ON section of a join and use the IN keyword as illustrated above.
You can do this by naming the tables of the main query and the nested query.
For example:
SELECT continent, name, population FROM world x
WHERE population >= ALL
(SELECT population FROM world y
WHERE y.continent=x.continent
AND population>0)
reference: http://sqlzoo.net/wiki/SELECT_within_SELECT_Tutorial
Not sure why people are over-complicating this. #JNK is correct that you can move the predicate into the main query. For completeness, I will demonstrate.
You have two predicates in your subquery that reference T0:
T6.UnionAll_Empresa = T0.UnionAll_Empresa
T2.CompanyDb = T0.UnionAll_Empresa
The first is an INNER JOIN predicate on the table T6, and the second a WHERE clause - these are both "hard" filters, and will filter out results that don't match (unlike a LEFT OUTER JOIN which will simply set reference to that table's values to NULL).
Well, since T6.UnionAll_Empresa and T2.CompanyDb both need to filter against T0.UnionAll_Empresa, then we can simply change the INNER JOIN predicate on T6 to this:
T2.CompanyDb = T6.UnionAll_Empresa
Then, we can remove the WHERE clause in the subquery, and we can add this JOIN predicate to TBI in the main query:
TBI.CompanyDb = T0.UnionAll_Empresa
...making the entire query this:
Select T0.UnionAll_Empresa,<STUFF>
from [UNION_ALL_BASES]..OINV T0 with (nolock)
inner join [UNION_ALL_BASES]..INV6 T1 with (nolock) on t0.DocEntry = t1.DocEntry and t0.UnionAll_Empresa = t1.UnionAll_Empresa
inner join
(
select
t1.CompanyID,
T2.CompanyDb,
t1.OurNumber,
T6.BankCode,
T6.BankName,
T3.[Description] Situation,
T1.[Status],
T5.Descrption nomeStatus,
T1.Origin,
T1.DocEntry,
T1.DocType,
T1.ControlKey,
T1.CardCode,
T4.[Description] ContractBank,
T1.PayMethodCode,
T1.DueDate,
T1.DocDate,
T1.InstallmentID,
T1.InstallmentValue,
T1.Correction,
T1.InterestContractural,
T1.FineContract,
T1.ValueAbatment,
T1.ValueDiscount,
T1.ValueFineLate,
T1.ValueInterestDaysOfLate,
T1.OtherIncreases,
T1.ValueInWords,
T1.ValueDocument,
T1.DigitalLine,
T1.Document
from [IntegrationBank]..BillOfExchange T1 with (nolock)
inner join [InterCompany2]..CompanyHierarchy T2 with (nolock) on T1.CompanyID = T2.ID
left join [IntegrationBank]..BillOfExchangeSituation T3 with (nolock) on T1.Situation = T3.ID
inner join [IntegrationBank]..ContractBank T4 with (nolock) on T1.ContractBank = T4.ID
inner join [IntegrationBank]..BoeStatus T5 with (nolock) on T1.[Status] = T5.ID
inner join [UNION_ALL_BASES]..ODSC T6 with (nolock) on T4.BankKey = T6.AbsEntry and T2.CompanyDb = T6.UnionAll_Empresa
where T1.[Status] <> 5
) TBI on (T1.DocEntry = TBI.DocEntry and T1.InstlmntID = TBI.InstallmentID and TBI.DocType = T1.ObjType and TBI.CompanyDb = T0.UnionAll_Empresa)
inner join [UNION_ALL_BASES]..OCTG T2 on T0.GroupNum = T2.GroupNum and T0.UnionAll_Empresa = T2.UnionAll_Empresa
inner join [UNION_ALL_BASES]..OSLP T3 on T0.SlpCode = T3.SlpCode and T0.UnionAll_Empresa = T3.UnionAll_Empresa
where not exists (
select 1
from [UNION_ALL_BASES]..RIN1 A with (nolock)
inner join [UNION_ALL_BASES]..ORIN B with (nolock) on A.DocEntry = B.DocEntry and A.UnionAll_Empresa = B.UnionAll_Empresa
where A.BaseEntry = T0.DocEntry
and B.SeqCode = ''1''
)
This is entirely equivalent to what you have, and removes any reference to T0 from your subquery.
You can also use WITH
http://msdn.microsoft.com/en-us/library/ms175972.aspx