SQL - 将多个记录存储在以逗号分隔的变量中

时间:2013-07-26 14:12:09

标签: sql sql-server-2008 tsql variables

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

您为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

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

enter image description here

3 个答案:

答案 0 :(得分: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),' ',',')

答案 1 :(得分:0)

您可以尝试这样的事情......显然,需要进行一些调整:

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')

然后,

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

然后,使用类似的东西来获取值:

select distinct num,dbo.GetList(num) from x

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