sql联合查询,如果将A表中的信息,合并到B表中一个字段显示
A表(dj_table1)
B表(dj_table2)
我通过语句查询
select *,
(stuff((SELECT ','+b.[typename] from dj_table2 b
where b.supportingTypeID=a.supportingTypeID and a.typeID LIKE '%'+cast(b.typeID AS nvarchar(10))+'%' FOR xml path('')), 1, 1, '')
)
from dj_table1 a
得到的结果是
其中红色的部分输出就出现错误了,麻烦大神们帮忙看看
其中生成表的语句:
CREATE TABLE [dbo].[dj_table1](
[ID] [int] IDENTITY(1,1) NOT NULL,
[typeID] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[supportingtypeID] [int] NULL,
CONSTRAINT [PK_dj_table1] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
go
CREATE TABLE [dbo].[dj_table2](
[typeID] [int] IDENTITY(1,1) NOT NULL,
[typeName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[supportingtypeId] [int] NULL,
CONSTRAINT [PK_dj_table2] PRIMARY KEY CLUSTERED
(
[typeID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
------解决方案--------------------改成这样试试:
select *,
(stuff((SELECT ','+b.[typename] from dj_table2 b
where b.supportingTypeID=a.supportingTypeID and
charindex(','+cast(b.typeID AS nvarchar(10))+',',','+a.typeID+',')>0
FOR xml path('')), 1, 1, '')
)
from dj_table1 a
------解决方案--------------------
select *,
(stuff((SELECT ','+b.[typename] from dj_table2 b
where b.supportingTypeID=a.supportingTypeID and ','+a.typeID+',' LIKE '%,'+cast(b.typeID AS nvarchar(10))+',%' FOR xml path('')), 1, 1, '')
)
from dj_table1 a
逗号的地方注意