0

我有一张桌子Companiesdata

CREATE TABLE [dbo].[Companiesdata]
(
[Company Name] nvarchar(255),
[Industry] varchar(40),
[ParentId] int NULL,
)

并且行是

CompanyName               Industry          Parent ID  
--------------------------------------------------------
Xyz technologies          Software             1
apple Technologies        software             1
Sun network               media                2
abc Technologies          advertising          4
PQR Technnologies         Marketing            5
abc Technologies          Media                4

我还有一张桌子

create table dbo.companiesss
(
autoid int identity(1,1),
companyname varchar(max),
Industry  varchar(max)
)

我写了一个这样的程序:

create proc pr_getlistofcompaniesss (@tparentid varchar(20))   
as 
begin
   insert into dbo.companiesss(companyname, industry) 
      select  
          [CompanyName], [Industry] 
      from 
          [Companiesdata]
      where 
          parentid in (select items from dbo.split(@tparentid,',')) 
      except
      select company name, industry 
      from dbo.companiesss 
end

输出如下:

pr_getlistofcompaniesss 1,2,4

行显示为

AutoID    Company name              Industry
---------------------------------------------------
  1       apple Technologies        software
  2       Sun network               Media
  3       xyz Technologies          software
  4       abc Technologies          advertising
  5       abc technologies          media

相反,我的输出应如下所示:

pr_getlistofcompaniesss 1,2,4

AutoID    Company name              Industry
---------------------------------------------------
  1       apple Technologies        software
  2       Sun network               Media
  3       xyz Technologies          software
  4       abc Technologies          advertising,media

即如果我有同一个公司(这里abc technologies)有不同的行业名称,那么行业字段应该用逗号分隔,在同一行显示记录,即(advertising, media

4

2 回答 2

0

首先,您需要将这些 ID 一起传递到一个字符串中,而不是作为单独的参数。您的过程只接受一个参数。

pr_getlistofcompaniesss '1,2,4'

然后在您的过程中,将您的插入子句更新为以下内容。这会将行业连接成一个以逗号分隔的字符串。

insert into dbo.companiesss(companyname,industry) 
select [CompanyName],
       STUFF((select distinct ',' + [Industry]
              from [Companiesdata] as child
              where child.parentid = parent.parentid
              for xml path ('')),
             1, 2, '')
from [Companiesdata] as parent
join dbo.split(@tparentid,',')
    on (parent.parentid = split.items)

我还使用 ajoin与 usingwhere ... in ( ... )语法,因为连接通常执行得更快。

于 2012-08-08T12:05:15.187 回答
0

我创建了一个标量函数来实现类似的结果,然后交叉应用该函数您的存储过程。代码如下:

CREATE  FUNCTION [dbo].[fnListIndustry] (@ParentID varchar(10))
RETURNS VARCHAR(1000)
AS
BEGIN 
DECLARE @IndustryList   varchar(1000)
SELECT  @IndustryList   = COALESCE(@IndustryList + ',', '') + rtrim(dbo.Companiesdata.Industry)
FROM    dbo.Companiesdata 
WHERE   dbo.Companiesdata.parenid = @ParentID

RETURN  @IndustryList
END
于 2012-08-08T11:53:16.410 回答