这样做的经典方法......
/*
create table Users
(
id int,
name nvarchar(max)
)
insert into Users
values
(72, 'Joe'),
(73, 'Michael'),
(74, 'Ricky'),
(75, 'Manny'),
(76, 'Bob')
*/
CREATE FUNCTION dbo.Fn_MyFunction(@IdValues VARCHAR(100))
RETURNS NVARCHAR(max) AS
BEGIN
DECLARE @Result NVARCHAR(max);
DECLARE @delimiter as nchar = ',';
WHILE LEN(@IdValues) <> 0
BEGIN
Declare @CurrentId int;
If CHARINDEX(@delimiter, @IdValues) = 0
begin
Set @CurrentId = cast(@IdValues as int);
Set @IdValues = ''
End
Else
begin
Set @CurrentId = cast(left(@IdValues, charindex(@delimiter, @IdValues) -1) as int)
Set @IdValues = Substring(@IdValues, charindex(@delimiter, @IdValues) +1, len(@IdValues))
End
select @Result = Isnull(@Result + ',', '') + Isnull((Select Name From Users Where Id=@CurrentId),'(unknown)')
END
RETURN @Result
END
GO
Select dbo.Fn_MyFunction('72,73,74')
--Joe,Michael,Ricky
Select dbo.Fn_MyFunction('72,0,74')
--Joe,(unknown),Ricky
Select dbo.Fn_MyFunction('72,73,72,74,74')
--Joe,Michael,Joe,Ricky,Ricky