T-SQL用逗号连接VarChar

时间:2013-04-24 06:20:21

标签: sql-server tsql concatenation

我是SQL的新手。我有这个工作的SQL函数,但我想用逗号连接结果,如果结果为空,则不会留下任何无关的逗号。我和COALESCE一起玩,但我无法上班。任何线索或帮助都会很棒。

在Python中我会这样做:

'abcdef'.join(', ')

现在是SQL函数:

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

3 个答案:

答案 0 :(得分:1)

尝试

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

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

而不是Return @Result

答案 1 :(得分:0)

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

RETURN REPLACE(@result,',,',',')

答案 2 :(得分: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