0

I have following query:

SELECT ChallanNo+'-'+CONVERT(VARCHAR(12),ChallanDate,106) 
   FROM Challan WHERE ChallanID IN 
   (SELECT ChallanID FROM ChallanDetail WHERE PTUID=42192)

This query result will be :

151468-29 May 2012
151591-31 May 2012

Now I need a string like this :

151468-29 May 2012, 151591-31 May 2012

Thanks for response

3
  • I assume this is for SQL Server? Commented Jun 7, 2012 at 6:01
  • Is the output something you want to produce out of SQL or can it be done programatically? Commented Jun 7, 2012 at 6:02
  • Concatenating Row Values in Transact-SQL Commented Jun 7, 2012 at 6:06

2 Answers 2

2

On versions of SQL Server < 2017, you had to use STUFF and a FOR XML PATH subquery.

SELECT STUFF((SELECT ', ' + CONVERT(VARCHAR(32), ChallanNo) 
  + '-' + CONVERT(CHAR(11), ChallanDate, 106)  
  FROM dbo.Challan WHERE ChallanID IN 
   (SELECT ChallanID FROM dbo.ChallanDetail WHERE PTUID = 42192)
FOR XML PATH(''), 
TYPE).value(N'./text()[1]', N'varchar(max)'), 1, 2, '');

In 2017+, you should definitely switch to STRING_AGG():

SELECT STRING_AGG(CONCAT(c.ChallanNo, '-',
    CONVERT(char(11), c.ChallanDate, 106)), ', ')
  FROM dbo.Challan AS c
  WHERE EXISTS 
  (
    SELECT 1 FROM dbo.ChallanDetail AS cd
    WHERE cd.ChallanID = c.ChallanID
    AND cd.PTUID = 42192
  );
Sign up to request clarification or add additional context in comments.

Comments

1
declare @result varchar(max) = ''

select @result = @result + ChallanNo + '-' + 
                 CONVERT(VARCHAR(12),ChallanDate,106) + ','
from ...

-- remove trailing ,
select left(@result, len(@result) - 1)

1 Comment

FWIW STUFF against a leading comma is a much more effective way to remove it than using LEFT against a trailing comma. Why? Well, you don't have to calculate the length, for one. :-) In this case it is negligible but on a larger data set that is a lot of extra cycles for nothing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.