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
 Get item name from item id

Author  Topic 

feejaz
Yak Posting Veteran

68 Posts

Posted - 2008-09-04 : 01:28:28
I have two tables Ist is the named "item" and 2nd is "Report"
In report table there is a column named "ItemID" where i have stored the itemids with commas, I mean many items ids in one row. How can I get the Item name from "Item" table against the itemids that are stored in the 2nd table. Below is example of table data

Table1 = "Item"
itemId ItemName
1 Chair
2 Table
3 Box
4 Computer

Table2 = "Report"
Dated itemId
12/5/2008 1,3
13/5/2008 2,3
16/5/2008 3,4

Here i need the itemname from report table.


Navi

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-09-04 : 01:44:57
1.learn about normalisation
2.
SELECT m.Dated,i.ItemName
FROM
(
SELECT r.*,b.Val
FROM Report r
CROSS APPLY dbo.ParseValues(r.itemId)b
)m
INNER JOIN Item i
ON i.itemid=m.Val


but this works only in sql 2005. also function parsevalues can be found below




CREATE FUNCTION ParseValues  
(@String varchar(8000)
)
RETURNS @RESULTS TABLE
(ID int identity(1,1),
Val int
)
AS
BEGIN
DECLARE @Value varchar(100)

WHILE @String is not null
BEGIN
SELECT @Value=CASE WHEN CHARINDEX(',',@String) >0 THEN LEFT(@String,CHARINDEX(',',@String)-1) ELSE @String END,
@String=CASE WHEN CHARINDEX(',',@String) >0 THEN SUBSTRING(@String,CHARINDEX(',',@String)+1,LEN(@String)) ELSE NULL END
INSERT INTO @RESULTS (Val)
SELECT @Value
END
RETURN
END
Go to Top of Page
   

- Advertisement -