Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Build comma list from parameters

Status
Not open for further replies.

tshad

Programmer
Jul 15, 2004
386
US
Is there to easily build a comma delimited list from parameters that are passed. I know you can do it with COALESCE and a table but not with parameters:

Code:
DECLARE @Name varchar(100),
	@Number int,
	@ClassName varchar(100),
	@ErrorMessage varchar(2000
		
SELECT  @Name  = 'Main',
	@Number  = 2,
	@ClassName  = 'AnotherClass'
		
SELECT @ErrorMessage =  'Zero rows when: ' +
	CASE WHEN @Name IS NULL THEN '' ELSE COALESCE(@ErrorMessage + ', ', '') + '@Name = ' + @Name END +
		CASE WHEN @Number IS NULL THEN '' ELSE  COALESCE(@ErrorMessage + ', ', '') + '@Number = ' + CONVERT(varchar(10),@Number) END +
		CASE WHEN @ClassName IS NULL THEN '' ELSE  COALESCE(@ErrorMessage + ', ', '') + '@ClassName = ' + @ClassName END

SELECT @ErrorMessage

I am trying to get the string to show:

'Zero rows when: @Name = Main, @Number = 2, @ClassName= AnotherClass'

Thanks,

Tom
 
In the upcoming version of SQL Server (code name Denali) it will be a piece of cake with the new concat function

Until then, you will need to use CONVERT function to convert non character parameters to character.

Also, I suggest to add

set @ErrorMessage = ''

before running the second statement, so we don't need all COALESCE around @ErrorMessage

PluralSight Learning Library
 
You need to add an ELSE '' END or else you will get a null, which is clearing out your variable when you skip entering in a parameter.

Lod

You've got questions and source code. We want both!
 
I would do this that way:
Code:
DECLARE @Name varchar(100),
    @Number int,
    @ClassName varchar(100),
    @ErrorMessage varchar(2000)
        
SELECT  @Name  = 'Main',
        @Number  = 2,
        @ClassName  = 'AnotherClass'

SELECT @ErrorMessage =  'Zero rows when: @Name = ' 
                                       + COALESCE(@Name,' NULL')
                    +', @Number = '    + COALESCE( CONVERT(varchar(10),@Number),' NULL')
                    +', @ClassName = ' + COALESCE(@ClassName,' NULL')

SELECT @ErrorMessage

That way you will see which parameters are passed and which does not have values.


Borislav Borissov
VFP9 SP2, SQL Server 2000,2005 & 2008.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top