Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 IF Statement to control SELECT Statement

Author  Topic 

rikard
Starting Member

2 Posts

Posted - 2009-02-06 : 08:12:39
Hi,

I am not that familiar with SQL.
I need to write a query that will select different columns form different tables, based on the outcome of an IF statement.

Something like:

IF(Table1.TargetType = 'some_value')
SELECT Table1.Date, Table2.Item
FROM Table1 INNER JOIN Table2 ON Table1.DocKey = Table2.DocKey

ELSE
SELECT Table3.Date, Table4.Item
FROM Table1 INNER JOIN Table3 ON Table1.TargetKey = Table3.DocKey
INNER JOIN Table4 ON Table3.DocKey = Table4.DocKey

ODRER BY Date;

How can I achieve this?

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-02-06 : 08:46:34
did you mean this?

SELECT Table1.Date, Table2.Item,t.Date, t.Item
FROM Table1
LEFT JOIN Table2
ON Table1.DocKey = Table2.DocKey
AND Table1.TargetType = 'some_value'
LEFT JOIN
(SELECT Table3.Date, Table4.Item, Table3.DocKey
FROM Table3
INNER JOIN Table4 ON Table3.DocKey = Table4.DocKey
)t
ON Table1.TargetKey = t.DocKey
AND Table1.TargetType <> 'some_value'
Go to Top of Page

rikard
Starting Member

2 Posts

Posted - 2009-02-10 : 08:15:03
Thanx for your reply.

What I needed was to list sales orders and invoices in the same query.
I found an alternative solution - I used a WHERE clause to copy the sales orders and invoices i needed to a temp table, then I used a standard SELECT statement to retrieve the data.

Thanx anyway.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-02-10 : 09:19:30
ok...cool
Go to Top of Page
   

- Advertisement -