Sardoan
Sardoan

Reputation: 817

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

Upvotes: 0

Views: 43

Answers (2)

Ace Indy
Ace Indy

Reputation: 109

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'

Upvotes: 0

Eric J.
Eric J.

Reputation: 150118

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.

Upvotes: 2

Related Questions