August 29, 2011 at 2:04 pm
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:
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[/code]
I am trying to get the string to show:
'Zero rows when: @Name = Main, @Number = 2, @ClassName= AnotherClass'
Thanks,
Tom
August 29, 2011 at 3:01 pm
This gets the results that you want.
DECLARE @Name varchar(100),
@Number int,
@ClassName varchar(100),
@ErrorMessage varchar(2000)
SELECT @Name = 'Main',
@Number = 2,
@ClassName = 'AnotherClass'
SELECT @ErrorMessage = 'Zero rows when: '
SELECT @ErrorMessage = CASE WHEN @Name IS NULL THEN @ErrorMessage ELSE COALESCE(@ErrorMessage , '') + '@Name = ' + @Name END
SELECT @ErrorMessage = CASE WHEN @Number IS NULL THEN @ErrorMessage ELSE COALESCE(@ErrorMessage + ', ', '') + '@Number = ' + CONVERT(varchar(10),@Number) END
SELECT @ErrorMessage = CASE WHEN @ClassName IS NULL THEN @ErrorMessage ELSE COALESCE(@ErrorMessage + ', ', '') + '@ClassName = ' + @ClassName END
SELECT @ErrorMessage
August 29, 2011 at 4:35 pm
You only need 1 SELECT. Since you're also just checking for NULL values, you also don't need any CASE statements.
DECLARE @Name VARCHAR(100),
@Number INT,
@ClassName VARCHAR(100),
@ErrorMessage VARCHAR(2000)
;
SELECT @Name = 'Main',
@Number = 2,
@ClassName = 'AnotherClass'
;
SELECT @ErrorMessage = 'Zero rows when:'
+ ISNULL(STUFF(
ISNULL(', @Name = ' + @Name,'')
+ ISNULL(', @Number = ' + CAST(@Number AS VARCHAR(10)),'')
+ ISNULL(', @ClassName = ' + @ClassName,'')
,1,1,''),'')
;
SELECT @ErrorMessage
;
--Jeff Moden
Change is inevitable... Change for the better is not.
August 29, 2011 at 9:33 pm
That works fine.
Thanks,
Tom
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply