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.
| Author |
Topic |
|
mrgr8avill
Starting Member
16 Posts |
Posted - 2007-12-26 : 22:56:22
|
| Hello, thanks in advance for reading this. I am having difficulty trying to get a statement to work.There is a MAIN table:ItemNo int identity(1,0),ItemType tinyintThere is a WETPAINT table:ItemNo int,Color varchar(20)There is a DRYPAINT table:ItemNo int,Color varchar(20)Now, what I want to do is JOIN the MAIN table to either the WETPAINT table or the DRYPAINT table depending on the value of MAIN.ItemTypeSo I created a table function called getTable:CREATE FUNCTION [dbo].[gettable] ( @ItemType int = 1)RETURNS @thistable TABLE ( Color varchar(20) )ASBEGIN if @ItemType = 1 insert into @thistable (color) select color from WETPAINT if @ItemType = 2 insert into @thistable (color) select color from DRYPAINT RETURN ENDThis is all fine and dandy if I iterate through the MAIN table one row at a time, but how can I JOIN the tables, like:SELECT MAIN.ItemNo, a.Color FROM MAININNER JOIN gettable(Main.ItemNo) as aON a.ItemNo = MAIN.ItemNoObviously, there is more than one field in the DRYPAINT and WETPAINT tables, and there is a need to have both tables instead of combining them into one.Any help in how to create a table alias by passing a value from the select statement would be greatly appreciated! Thanks again.PS -- I am trying to create a view with this, so I can't use variables and iterate through the MAIN table one row at a time. |
|
|
Koji Matsumura
Posting Yak Master
141 Posts |
Posted - 2007-12-27 : 00:31:00
|
| SELECT MAIN.ItemNo, IsNull(A.Color , B.Color)FROM MAINLEFT OUTER JOIN WETPAINT A ON A.ItemNo = MAIN.ItemNo AND A.ItemType = 1LEFT OUTER JOIN DAYPAINT B ON B.ItemNo = MAIN.ItemNo AND A.ItemType = 2 |
 |
|
|
kiruthika
Yak Posting Veteran
67 Posts |
Posted - 2007-12-27 : 03:01:26
|
| Hi!Try thisselect m.itemno,(case when itemtype=1 then d.color elsew.color end) as color from main m left outer join drypaint d on m.itemno=d.itemno left outer join wetpaint w on m.itemno=w.itemno kiruthika!http://www.ictned.eu |
 |
|
|
|
|
|
|
|