简体   繁体   中英

SQL Server: returning combined data from two tables using c#

I hope someone can help me. My problem is that I have two tables in my database. I want to return the IDs from tableA and tableB with one stored procedure.

Therefore I have two selects:

SELECT
    id, 'WE' 
FROM
    tableX
WHERE
    value= 'x'

SELECT
    id, 'WT' 
FROM
    tableY
WHERE
    value= 'y'

How can I combine them so I get only one object in my C# code?

Any example? Did not find a sample code for this case. Somehow with a cursor?

It is old code, so no Entity Framework available.

Thanks

The UNION statement can do this for you

SELECT
id, 'WE' from
tableX
where value= 'x'
UNION
SELECT
id, 'WT' from
tableY
where value= 'y'

UNION ALL performs a similar function, but will not filter out identical rows from the UNION result. In this case, you specify different literal values for the second column, so UNION and UNION ALL will produce the same set.

And if the tables do not have the same amount of columns, you can use a dummy column:

SELECT Id, we, them from table x where value = 'x' 
UNION 
SELECT Id, we, null as them from table y where value ='y'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM