SQL, How to Concatenate results?

前端 未结 7 1929
渐次进展
渐次进展 2020-11-29 08:08

I currently have a SQL query that returns a number of fields. I need one f the fields to be effectively a sub query sub that.

The Problem in detail:

相关标签:
7条回答
  • 2020-11-29 08:32

    Small update on Marc we will have additional " , " at the end. i used stuff function to remove extra semicolon .

           SELECT STUFF((  SELECT ',' + ModuleValue AS ModuleValue
                               FROM ModuleValue WHERE ModuleID=@ModuleID
                          FOR XML PATH('') 
                         ), 1, 1, '' )
    
    0 讨论(0)
  • 2020-11-29 08:35

    This one automatically excludes the trailing comma, unlike most of the other answers.

    DECLARE @csv VARCHAR(1000)
    
    SELECT @csv = COALESCE(@csv + ',', '') + ModuleValue
    FROM Table_X
    WHERE ModuleID = @ModuleID
    

    (If the ModuleValue column isn't already a string type then you might need to cast it to a VARCHAR.)

    0 讨论(0)
  • 2020-11-29 08:36

    In SQL Server 2005 and up, you could do something like this:

    SELECT 
        (SELECT ModuleValue + ','
         FROM dbo.Modules
         FOR XML PATH('')
        ) 
    FROM dbo.Modules
    WHERE ModuleID = 1
    

    This should give you something like what you're looking for.

    Marc

    0 讨论(0)
  • 2020-11-29 08:39

    It depends on the database you are using. MySQL for example supports the (non-standard) group_concat function. So you could write:

    SELECT GROUP_CONCAT(ModuleValue) FROM Table_X WHERE ModuleID=@ModuleID
    

    Group-concat is not available at all database servers though.

    0 讨论(0)
  • 2020-11-29 08:42

    With MSSQL you can do something like this:

    declare @result varchar(500)
    set @result = ''
    select @result = @result + ModuleValue + ', ' 
    from TableX where ModuleId = @ModuleId
    
    0 讨论(0)
  • 2020-11-29 08:48

    In mysql you'd use the following function:

    SELECT GROUP_CONCAT(ModuleValue, ",") FROM Table_X WHERE ModuleID=@ModuleID
    

    I am not sure which dialect you are using.

    0 讨论(0)
提交回复
热议问题