Select query from another database using 'exists'

Susja 711 Reputation points
2021-03-09T03:19:57.66+00:00

Hello,
I hit an issue to get data using 'IN' operator from another database.
Could you please help me to fix it?
My query looks like this:

SELECT i.EXTERNAL_CODE, tc.SITE_NAME, tr.TRANSACTION_DT

FROM app4_starlims_data.dbo.INVENTORY i
JOIN app4_starlims_data.dbo.VA_TUBE_COLLECTION tc
ON tc.INVENTORYID = i.INVENTORYID
JOIN app4_starlims_data.dbo.INVENTORY_TRANSACTIONS it
ON it.INVENTORYID = i.INVENTORYID
JOIN app4_starlims_data.dbo.transactions tr
ON tr.TRANSACTION_ID = it.TRANSACTION_ID
WHERE i.EXTERNAL_CODE IN
(SELECT vacutainer_ref, quality, [timestamp]
FROM dna_lab_biospecimen.dbo.blood_sample
WHERE quality LIKE '%under%'
AND [timestamp] BETWEEN '02-19-2021' AND '03-07-2021')

Thanks

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,693 questions
{count} votes

Accepted answer
  1. Nandan Hegde 29,886 Reputation points MVP
    2021-03-09T03:36:44.75+00:00

    Hey @Susja ,
    The issue is because within IN statement it is exepecting multiple values of a single column and not multiple columns.

    SELECT vacutainer_ref, quality, [timestamp]
    FROM dna_lab_biospecimen.dbo.blood_sample
    WHERE quality LIKE '%under%'
    AND [timestamp] BETWEEN '02-19-2021' AND '03-07-2021

    So rather than having 2 columns use union statement and seperate columns as
    Select c1 from t1
    union
    Select c2 from t2

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Susja 711 Reputation points
    2021-03-09T04:24:03.987+00:00

    Well I just noticed that I was selecting multiple fields. I will try to use only vacutainer_ref which is exact same as i.EXTERNAL_CODE
    Hope it should work
    Thanks for advice


  2. Susja 711 Reputation points
    2021-03-09T15:07:00.423+00:00

    Thanks for help.
    It worked.
    My fault was that I didn't realize that subquery returns multiple rows.

    0 comments No comments