SQL COALESCE修改

时间:2016-06-08 16:51:32

标签: sql sql-server-2005

我有以下代码

SELECT @email = COALESCE(@email + ', ', '') + Email
FROM dbo.FTX_ALERTUSER WITH (NOLOCK)
WHERE AlertID = 9017 AND Email IS NOT NULL

SELECT @email2 = VENDOREMAIL 
FROM FTX_NCMR_VENDOR_REQUIREMENT WITH(NOLOCK) 
WHERE VENDORCODE = @param1 AND BU = @param2

SELECT @email = @email + ',' + ISNULL(@email2,''' ''')

创建字符串

[ftx_alert_list] 'updateLastRunDT','9017','FTX-Software, Karthik@XYZ.com, ray@XYZ.com, tony@XYZ.com, yen@XYZ.com,' '','FTX_F20160607004'

我想纠正这个字符串,如

[ftx_alert_list] 'updateLastRunDT','9017','FTX-Software, Karthik@XYZ.com, ray@XYZ.com, tony@XYZ.com, yen@XYZ.com','','FTX_F20160607004'`

唯一的区别是,' '',我希望{@ 1}}在yen@XYZ.com之后。

1 个答案:

答案 0 :(得分:1)

您可以更改最后一行,如下所示。使用SUBSTRING,您只能获得预期的字符。

SELECT @email = '''' + SUBSTRING(@email, 0, LEN(@email)) + '''' + ',' + ISNULL(@email2,''' ''')

使用给定数据执行示例。

DECLARE @FTX_ALERTUSER TABLE(Email VARCHAR (50));

INSERT INTO @FTX_ALERTUSER (Email) VALUES
('FTX-Software'), ('Karthik@XYZ.com'), ('ray@XYZ.com'), ('tony@XYZ.com'), ('yen@XYZ.com');

DECLARE @FTX_NCMR_VENDOR_REQUIREMENT TABLE (VENDOREMAIL VARCHAR (50));

INSERT INTO @FTX_NCMR_VENDOR_REQUIREMENT (VENDOREMAIL) VALUES (NULL);

DECLARE @email AS VARCHAR (MAX) = '';
DECLARE @email2 AS VARCHAR (MAX) = '';

SELECT @email = @email + COALESCE(Email + ', ', '') 
FROM @FTX_ALERTUSER

--SELECT @email

SELECT @email2 = VENDOREMAIL 
FROM @FTX_NCMR_VENDOR_REQUIREMENT 

--SELECT @email2

SELECT @email = '''' + SUBSTRING(@email, 0, LEN(@email)) + '''' + ',' + ISNULL(@email2, ''' ''')

SELECT @email