1

我有两个变量,1 个 varchar namedcust_ref和 1 个 int named associated_ids。我想要完成的是以下内容:

您提供cust_ref的值通常会导致从Customer表中返回 1+ 行。我关心customer_id为此收集所有记录cust_ref并将它们存储在associated_ids由逗号分隔的变量中。

这是我到目前为止的 SQL,显然只是将其中一条customer_id记录加载到变量中。基于此示例,我想选择@associated_ids返回以下内容75458,77397,94955

declare @cust_ref varchar(20) = 'ABGR55532'
declare @associated_ids int

select distinct @associated_ids = customer_id
from dbo.Customer
where cust_ref = @cust_ref

select @associated_ids

select *
from dbo.Customer
where cust_ref = @cust_ref

这是上面的结果,如您所见,associated_ids在此示例中实际上我需要将 3 个存储在变量中,但我的命令正在捕获最大的,我希望所有 3 个用逗号分隔。

在此处输入图像描述

4

3 回答 3

0

You could try something like this ... obviously, some adjustment will be needed:

create table x (id varchar(50),num int)
insert into x (id,num) values ('75458','20')
insert into x (id,num) values ('77397','20')
insert into x (id,num) values ('94955','20')

and then,

create function GetList (@num as varchar(10)) 
returns varchar(100) 
as 
begin
  declare @List varchar(100) 
  select @List = COALESCE(@List + ', ', '') + id
  from x 
  where num = @num

  return @List

end

Then, use something like this to get the values:

select distinct num,dbo.GetList(num) from x
于 2013-07-26T14:41:00.607 回答
0

干得好

DECLARE @cust_ref varchar(20) = 'ABGR55532' --from your code
DECLARE @result varchar(100)

set @result =
(SELECT distinct (cast(customer_id as varchar) + ' ')
FROM dbo.Customer 
where cust_ref = @cust_ref --from your code
ORDER BY (cast(customer_id as varchar) + ' ')
FOR XML PATH (''))

SELECT REPLACE(RTRIM(@result),' ',',')
于 2013-07-26T14:56:43.963 回答
0
declare @cust_ref varchar(20) = 'ABGR55532' --from your code
DECLARE @result varchar(100)

set @result =
(SELECT distinct (customer_id + ' ')
FROM dbo.Customer 
where cust_ref = @cust_ref --from your code
ORDER BY (customer_id + ' ')
FOR XML PATH (''))

SELECT REPLACE(RTRIM(@result),' ',',')
于 2013-07-26T14:38:35.970 回答