我正在使用SSMS 2008以及以下查询:
DECLARE @TestData TABLE
(
address_desc NVARCHAR(100) NULL
,people_id UNIQUEIDENTIFIER NULL
);
INSERT @TestData
SELECT a.address_desc, a.people_id
FROM dbo.address_view a
SELECT a.people_id,
(SELECT SUBSTRING(
(SELECT ';'+b.address_desc
FROM @TestData b
WHERE a.people_id = b.people_id
FOR XML PATH(''))
,2
,4000)
) GROUP_CONCATENATE
FROM @TestData a
GROUP BY a.people_id
此查询有效,但我想将其转换为视图或函数,以便我可以从不同的存储过程中调用它。我怎样才能做到这一点?据我所知,变量不能在VIEW语句中声明。
Hong,这是我根据您的建议更新的查询,它给了我错误:
DECLARE @TestData TABLE
(
address_desc NVARCHAR(100) NULL
,people_id UNIQUEIDENTIFIER NULL
);
INSERT @TestData
SELECT a.address_desc, a.people_id FROM dbo.address_view a
SELECT a.people_id,
(SELECT address_desc, people_id FROM dbo.address_view),
(SELECT SUBSTRING(
(SELECT ';'+b.address_desc
FROM @TestData b
WHERE a.people_id = b.people_id
FOR XML PATH(''))
,2
,4000)
) GROUP_CONCATENATE
FROM @TestData a
GROUP BY a.people_id
答案 0 :(得分:3)
在上一个select查询中,将@TestData替换为子查询(SELECT address_desc, people_id FROM dbo.address_view)
,然后删除临时表@TestData。
试试这个:
Create View YourView As
SELECT a.people_id,
(SELECT SUBSTRING(
(SELECT ';'+b.address_desc
FROM (SELECT address_desc, people_id FROM dbo.address_view) b
WHERE a.people_id = b.people_id
FOR XML PATH(''))
,2
,4000)
) GROUP_CONCATENATE
FROM (SELECT address_desc, people_id FROM dbo.address_view) a
GROUP BY a.people_id