tags:

views:

590

answers:

4

I have already googled for this

  
 I have a Table with following structure in SQL 2000

 ID ContactName Designation
 1  A           CEO
 2  B           ABC
 3  C           DEF
 4  D           GHI

I need the Output as follows


ContactName1 Contactname2 ContactName3 ContactName4
 A CEO        B ABC         C DEF         D GHI

Any Suggestions ?

+1  A: 

You need to use a PIVOTED Table

cmsjr
I have my DataBase in SQL 2000
Wasn't that link SQL Server 2000 specific?
cmsjr
My Table Schema has varchar column and the example shown in the link has int columns.. can understand it
Is the list of designations fixed or is it arbitrary?
cmsjr
+1  A: 

This should work with 2000 also - wg. without PIVOT

http://www.sqlteam.com/item.asp?ItemID=2955

dmajkic
No its not working
+1  A: 

Yet another SQL Cross Tab proc http://johnmacintyre.ca/codespct.asp

John MacIntyre
+1  A: 

It occurs to me that a lot of the examples are for cross tab queries involving aggregation, which yours does not appear to need. While I do not necessarily condone Dynamic SQL, the below should give you the results you want.

Create table #Contacts (id int)
Declare @ContactTypes int
Declare @CAD varchar(100)
Declare @I int
Declare @sql nvarchar(4000)
Set @i = 1
Select @ContactTypes =   
Sum(sub.Types) 
from ( Select Count(1) as Types from contacts
group by ContactName, Designation) as sub
Print @ContactTypes
While @i <= @ContactTypes
Begin
    set @sql = 'alter table #Contacts Add  ContactName' + 
    Cast(@I as varchar(10)) + ' varchar(100)'
    exec sp_executesql @sql
    Set @I = @i + 1
End
Insert into #Contacts (id) values (1)
Set @i = 1
Declare crsPivot  cursor 
for Select ContactName + ' ' + Designation
from contacts
open crsPivot
Fetch next from crsPivot into @CAD
While (@@Fetch_Status = 0)
Begin   
    Set @sql = 'Update  #Contacts  set ContactName' 
    + Cast(@I as varchar(10)) +' = ' + quotename(@CAD,'''')
    exec sp_executesql @sql
    Set @i = @i + 1
    Fetch next from crsPivot into @CAD
End
close crsPivot
Deallocate crsPivot
select * From #Contacts
cmsjr
Thanks So much, Really ..Thanks
np, glad it worked out for you.
cmsjr