我有一张表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
)
答案 0 :(得分: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
答案 1 :(得分:0)
首先,您需要将这些ID一起传递到字符串中,而不是作为单独的参数传递。您的程序只接受一个参数。
pr_getlistofcompaniesss '1,2,4'
然后在您的过程中,将insert子句更新为以下内容。这将把行业连接成一个用逗号分隔的字符串。
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)
我也使用join
与使用where ... in ( ... )
语法,因为连接通常表现得更快。