Home > Net >  How can I display multiple ID's and value in single column SQL?
How can I display multiple ID's and value in single column SQL?

Time:01-15

I have a 'Knowledge' table where I'm adding tags. I'm saving a many-to-many relationship to other tables. Let me show my table structure:

enter image description here

I want to store a comma delimited string in a single table of persons. For example:

Id TagNames
28 Azure, SQL, WebConfig
29 Network

Thanks a lot of for answers.

CodePudding user response:

I found that. I used cursor and I'm listing my tags in one column.

SELECT kn.ID,Title,ExplainProblem,SolutionDescription,kn.CreateUserID, M.Name  ' 
'   M.Surname as 'TechNameAndSurname',kn.CreateDate,IsPrivate,kn.IsActive,
case
when kn.IsPrivate=1 then 'Sadece Ben'
when kn.IsPrivate=0 then 'Seçili Gruplar'
else ''
end WhoIsShowing
into #temp FROM Knowledges kn
inner join Members M on M.ID = kn.CreateUserID where kn.IsActive=1
alter table #temp add  TagsNames nvarchar(250)

DECLARE @ID int
DECLARE db_cursor CURSOR FOR SELECT Id FROM #temp
OPEN db_cursor  FETCH NEXT FROM db_cursor INTO @ID  
WHILE @@FETCH_STATUS = 0  
BEGIN  
  IF OBJECT_ID('tempdb..#tags') IS NOT NULL DROP TABLE #tags

  select tag.TagName,ktg.ID into #tags from KnowledgeTags ktg
  inner join Tags tag on tag.ID = ktg.TagID
  where ktg.KnowledgeID=@ID 
  order by ktg.TagID       
  
  --
  DECLARE @tags nvarchar(250) = ''   
  DECLARE @kID int, @tagName nvarchar(250)
  DECLARE db_cursor2 CURSOR FOR SELECT ID,TagName FROM #tags
  OPEN db_cursor2  FETCH NEXT FROM db_cursor2 INTO @kID,  @tagName
  WHILE @@FETCH_STATUS = 0  
        BEGIN  
            SET @tags = @tags   ', '   @tagName
        FETCH NEXT FROM db_cursor2 INTO @kID,  @tagName  
   END CLOSE db_cursor2 DEALLOCATE db_cursor2 
  --

  update #temp set TagsNames = RIGHT(@tags, LEN(@tags)-1) where ID = @ID

  FETCH NEXT FROM db_cursor INTO @ID  
  END CLOSE db_cursor DEALLOCATE db_cursor 
  SELECT * FROM #temp

enter image description here

  •  Tags:  
  • Related