2

I'm new to SQL. I have this working SQL function, but I would like to join the results with a comma in a way that leaves no extraneous commas if the result is empty. I had a play with COALESCE but I couldn't get it to work. Any clues or help would be great.

In Python I would do this:

'abcdef'.join(', ')

Here is the SQL function now:

USE [Broadcast]
GO
/****** Object:  UserDefinedFunction [dbo].[MapConsumerAdvice]    Script Date: 04/24/2013 14:49:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date, ,>
-- Description: <Description, ,>
-- =============================================
ALTER FUNCTION [dbo].[MapConsumerAdvice] 
(
    @A as Int,
    @B as Int,
    @C as Int,
    @D as Int,
    @E as Int,
    @F as Int,
    @G as Int,
    @H as Int
)
RETURNS VarChar(20)
AS
BEGIN

    DECLARE @Result as VarChar(999)

    SET @Result = ''

    IF (@A > 0) SET @Result = @Result + ',' + 'a'
    IF (@B > 0) SET @Result = @Result + ',' + 'd'
    IF (@C > 0) SET @Result = @Result + ',' + 'h'
    IF (@D > 0) SET @Result = @Result + ',' + 'l'
    IF (@E > 0) SET @Result = @Result + ',' + 'm'
    IF (@F > 0) SET @Result = @Result + ',' + 'n'
    IF (@G > 0) SET @Result = @Result + ',' + 's'
    IF (@H > 0) SET @Result = @Result + ',' + 'v'

    Return @Result

END
4

3 回答 3

1

尝试

RETURN SUBSTRING(@Result, 2, LEN(@Result))

或者

RETURN RIGHT(@Result, LEN(@Result)-1)

代替Return @Result

于 2013-04-24T06:33:51.070 回答
0

您确实需要检查是否分配了任何内容。

USE [Broadcast]
GO
/****** Object:  UserDefinedFunction [dbo].[MapConsumerAdvice]    Script Date: 04/24/2013 14:49:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date, ,>
-- Description: <Description, ,>
-- =============================================
ALTER FUNCTION [dbo].[MapConsumerAdvice] 
(
    @A as Int,
    @B as Int,
    @C as Int,
    @D as Int,
    @E as Int,
    @F as Int,
    @G as Int,
    @H as Int
)
RETURNS VarChar(20)
AS
BEGIN

DECLARE @Result as VarChar(999)

SET @Result = ''

IF (@A > 0) SET @Result = @Result + ',' + 'a'
IF (@B > 0) SET @Result = @Result + ',' + 'd'
IF (@C > 0) SET @Result = @Result + ',' + 'h'
IF (@D > 0) SET @Result = @Result + ',' + 'l'
IF (@E > 0) SET @Result = @Result + ',' + 'm'
IF (@F > 0) SET @Result = @Result + ',' + 'n'
IF (@G > 0) SET @Result = @Result + ',' + 's'
IF (@H > 0) SET @Result = @Result + ',' + 'v'

IF PATINDEX(',%', @Result) > 1 Set @Result = SUBSTRING(@Result, 2, LEN(@Result));

Return @Result

END
于 2013-04-24T06:38:43.230 回答
0

在函数末尾添加以下代码,

RETURN REPLACE(@result,',,',',')
于 2013-04-24T06:25:58.770 回答