-3

So i would like to select a few values separated by a comma into a comment field where the values equal certain matches.

Here is how my table looks.

[dbo].[ValuationDetail](
[ValuationDetailId] [int] IDENTITY(1,1) NOT NULL,
[ValuationId] [int] NOT NULL,
[TagName] [varchar](100) NOT NULL,
[TagValue] [varchar](max) NULL,
[Mod] [varchar](50) NOT NULL,
[IncludePdf] [bit] NOT NULL,
[IsBinary] [bit] NOT NULL,

enter image description here

I would like to do something like.

SELECT 
  ValuationId,
  TagValue as Comment WHERE TagName = 'Sale_8_township', 'Sale_8_portion', 'Sale_8_erf'
WHERE ValuationId = 21702

Result being

Comment = ST HELENA BAY,0,1719

Please let me know if you need more info.

Pomster
  • 14,567
  • 55
  • 128
  • 204

2 Answers2

0

You need something like GROUP_CONCAT of MySQL

SELECT 
  ValuationId,
  GROUP_CONCAT(TagValue) as Comment 
FROM table
WHERE TagName IN (Tag1, Tag2, Tag3)
AND ValuationId = 123
GROUB BY ValuationId

if you don't want to create a new function in SQL Server, you can workaround with the STUFF built in function :

STUFF(
         (SELECT ', ' + TagValue
          FROM table
          WHERE ValuationId = outer. ValuationId
          FOR XML PATH (''))
          , 1, 1, '')  AS Comment
aleroot
  • 71,077
  • 30
  • 176
  • 213
  • *aleroot Group_Concat is not recognized as a built in function name. and i am not understanding the Stuff. STUFF( (SELECT ', ' + TagValue FROM ValuationDetail WHERE ValuationId = 21701 AND TagName = 'comparable_sale_1_sales_price' OR 'comparable_sale_2_sale_price' OR 'comparable_sale_3_sale_price' FOR XML PATH ('')) , 1, 1, '') AS Comment – Pomster Oct 29 '15 at 11:19
  • *aleroot Please look at my edit to get a better idea of what i am trying to achieve – Pomster Oct 29 '15 at 11:31
  • @Pomster Follow the link on codeplex and add the group_concat function ... http://groupconcat.codeplex.com – aleroot Oct 29 '15 at 11:34
0

Coalesce helped me concatenate the string stored in a temp table.

SELECT @Comment = COALESCE(@Comment + ',','') + TagValue FROM #TempComment

CREATE TABLE #TempComment (id int, TagValue varchar(500))

INSERT INTO #TempComment
        SELECT
            CASE
                WHEN TagName = @saleErf THEN  1
                WHEN  TagName = @salePortion THEN 2
                WHEN  TagName = @saleTownship THEN 3
                WHEN  TagName = @salePrice THEN 4
                WHEN  TagName = @saleDate THEN 5
                WHEN  TagName = @saleOverall THEN 6
            END,
            TagValue
        FROM ValuationDetail
        WHERE TagName IN (@saleErf,@salePortion,@saleTownship, @salePrice, @saleDate, @saleOverall) AND ValuationId = @ValuationId

SELECT @Comment = COALESCE(@Comment + ',','') + TagValue FROM #TempComment ORDER BY Id
Pomster
  • 14,567
  • 55
  • 128
  • 204