我在两个表之间有多对多的关系。
表God_Restaurants
包含我的餐馆。
表God_RestaurantKat
包含不同的类别。
表God_RestKatReference
包含两列,每列包含两个表的id。
以下陈述是我能想到的,但不会给我我想要的输出。
DECLARE @Names VARCHAR(8000)
SELECT DISTINCT R.RestaurantID as Restaurantid,
R.RestaurantName as Restaurantname,
K.RestaurantKatName as RestKatName
FROM God_Restaurants R
LEFT JOIN God_RestKatReference as GodR ON R.RestaurantId = Godr.RestaurantId
LEFT JOIN God_RestaurantKat as K ON GodR.RestaurantKatId = K.RestaurantKatId
WHERE R.RestaurantPostal = 7800
我希望输出信息是关于餐馆的信息,在最后一列中,是一个连续的类别行。
答案 0 :(得分:2)
要连接值,您可以使用for xml path('')
。错误的xml路径解决方案,您应该使用value
和type
作为特殊字符。
declare @Temp table (id int, Name nvarchar(max))
declare @date datetime
declare @i int
insert into @Temp
select 1, 'asasd' union all
select 1, 'sdsdf' union all
select 2, 'asdad' union all
select 3, 'asd<a?>&sdasasd' union all
select 3, 'fdgdfg'
select @i = 1
while @i < 9
begin
insert into @Temp
select id, Name from @Temp
select @i = @i + 1
end
select count(*) from @Temp
select @date = getdate()
select
A.id,
stuff((select ', ' + TT.Name from @Temp as TT where TT.id = A.id for xml path(''), type).value('.', 'nvarchar(max)'), 1, 2, '') as Names
from @Temp as A
group by A.id
select datediff(ms, @date, getdate())
select @date = getdate()
select distinct
A.id,
stuff((select ', ' + TT.Name from @Temp as TT where TT.id = A.id for xml path(''), type).value('.', 'nvarchar(max)'), 1, 2, '') as Names
from @Temp as A
select datediff(ms, @date, getdate())
您也可以使用变量解决方案
declare @temp nvarchar(max)
select @temp = isnull(@temp + ', ', '') + str
from (select '1' as str union select '2' as str union select '3' as str) as A
select @temp